2 * This file is part of NixNote
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.evernote.NoteMetadata;
168 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
169 import cx.fbn.nevernote.filters.FilterEditorTags;
170 import cx.fbn.nevernote.gui.AttributeTreeWidget;
171 import cx.fbn.nevernote.gui.BrowserWindow;
172 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
173 import cx.fbn.nevernote.gui.ExternalBrowse;
174 import cx.fbn.nevernote.gui.MainMenuBar;
175 import cx.fbn.nevernote.gui.NotebookTreeWidget;
176 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
177 import cx.fbn.nevernote.gui.SearchPanel;
178 import cx.fbn.nevernote.gui.TableView;
179 import cx.fbn.nevernote.gui.TagTreeWidget;
180 import cx.fbn.nevernote.gui.Thumbnailer;
181 import cx.fbn.nevernote.gui.TrashTreeWidget;
182 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
183 import cx.fbn.nevernote.sql.DatabaseConnection;
184 import cx.fbn.nevernote.sql.WatchFolderRecord;
185 import cx.fbn.nevernote.threads.IndexRunner;
186 import cx.fbn.nevernote.threads.SyncRunner;
187 import cx.fbn.nevernote.threads.ThumbnailRunner;
188 import cx.fbn.nevernote.utilities.AESEncrypter;
189 import cx.fbn.nevernote.utilities.ApplicationLogger;
190 import cx.fbn.nevernote.utilities.FileImporter;
191 import cx.fbn.nevernote.utilities.FileUtils;
192 import cx.fbn.nevernote.utilities.ListManager;
193 import cx.fbn.nevernote.utilities.SyncTimes;
194 import cx.fbn.nevernote.xml.ExportData;
195 import cx.fbn.nevernote.xml.ImportData;
196 import cx.fbn.nevernote.xml.ImportEnex;
197 import cx.fbn.nevernote.xml.NoteFormatter;
200 public class NeverNote extends QMainWindow{
202 QStatusBar statusBar; // Application status bar
204 DatabaseConnection conn;
206 MainMenuBar menuBar; // Main menu bar
207 FindDialog find; // Text search in note dialog
208 List<String> emitLog; // Messages displayed in the status bar;
209 QSystemTrayIcon trayIcon; // little tray icon
210 QMenu trayMenu; // System tray menu
211 QAction trayExitAction; // Exit the application
212 QAction trayShowAction; // toggle the show/hide action
213 QAction trayAddNoteAction; // Add a note from the system tray
214 QNetworkAccessManager versionChecker; // Used when checking for new versions
216 NotebookTreeWidget notebookTree; // List of notebooks
217 AttributeTreeWidget attributeTree; // List of note attributes
218 TagTreeWidget tagTree; // list of user created tags
219 SavedSearchTreeWidget savedSearchTree; // list of saved searches
220 TrashTreeWidget trashTree; // Trashcan
221 TableView noteTableView; // List of notes (the widget).
223 public BrowserWindow browserWindow; // Window containing browser & labels
224 public QToolBar toolBar; // The tool bar under the menu
225 QComboBox searchField; // search filter bar on the toolbar;
226 QShortcut searchShortcut; // Shortcut to search bar
227 boolean searchPerformed = false; // Search was done?
228 QuotaProgressBar quotaBar; // The current quota usage
230 ApplicationLogger logger;
231 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
232 List<String> selectedTagGUIDs; // List of selected tag GUIDs
233 List<String> selectedNoteGUIDs; // List of selected notes
234 String selectedSavedSearchGUID; // Currently selected saved searches
235 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
237 NoteFilter filter; // Note filter
238 String currentNoteGuid; // GUID of the current note
239 Note currentNote; // The currently viewed note
240 boolean noteDirty; // Has the note been changed?
241 boolean inkNote; // if this is an ink note, it is read only
242 boolean readOnly; // Is this note read-only?
245 ListManager listManager; // DB runnable task
247 List<QTemporaryFile> tempFiles; // Array of temporary files;
249 QTimer indexTimer; // timer to start the index thread
250 IndexRunner indexRunner; // thread to index notes
253 QTimer syncTimer; // Sync on an interval
254 QTimer syncDelayTimer; // Sync delay to free up database
255 SyncRunner syncRunner; // thread to do a sync.
256 QThread syncThread; // Thread which talks to evernote
257 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
258 QThread thumbnailThread; // Thread that generates pretty pictures
259 QTimer saveTimer; // Timer to save note contents
261 QTimer authTimer; // Refresh authentication
262 QTimer externalFileSaveTimer; // Save files altered externally
263 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
264 List<String> externalFiles; // External files to save later
265 List<String> importFilesKeep; // Auto-import files to save later
266 List<String> importFilesDelete; // Auto-import files to save later
268 int indexTime; // how often to try and index
269 boolean indexRunning; // Is indexing running?
270 boolean indexDisabled; // Is indexing disabled?
272 int syncThreadsReady; // number of sync threads that are free
273 int syncTime; // Sync interval
274 boolean syncRunning; // Is sync running?
275 boolean automaticSync; // do sync automatically?
276 QTreeWidgetItem attributeTreeSelected;
278 QAction prevButton; // Go to the previous item viewed
279 QAction nextButton; // Go to the next item in the history
280 QAction downButton; // Go to the next item in the list
281 QAction upButton; // Go to the prev. item in the list;
282 QAction synchronizeButton; // Synchronize with Evernote
283 QAction allNotesButton; // Reset & view all notes
284 QTimer synchronizeAnimationTimer; // Timer to change animation button
285 int synchronizeIconAngle; // Used to rotate sync icon
286 QAction printButton; // Print Button
287 QAction tagButton; // Tag edit button
288 QAction attributeButton; // Attribute information button
289 QAction emailButton; // Email button
290 QAction deleteButton; // Delete button
291 QAction newButton; // new Note Button;
292 QSpinBox zoomSpinner; // Zoom zoom
293 QAction searchClearButton; // Clear the search field
295 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
297 QSplitter mainLeftRightSplitter; // main splitter for left/right side
298 QSplitter leftSplitter1; // first left hand splitter
299 QSplitter browserIndexSplitter; // splitter between note index & note text
301 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
302 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
303 List<String> importedFiles; // History of imported files (so we don't import twice)
305 OnlineNoteHistory historyWindow; // online history window
306 List<NoteVersionId> versions; // history versions
308 QTimer threadMonitorTimer; // Timer to watch threads.
309 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
310 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
311 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
312 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
313 int tagDeadCount=0; // number of consecutive dead times for the tag thread
314 int trashDeadCount=0; // number of consecutive dead times for the trash thread
315 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
316 boolean disableTagThreadCheck=false;
317 boolean disableNotebookThreadCheck=false;
318 boolean disableTrashThreadCheck=false;
319 boolean disableSaveThreadCheck=false;
320 boolean disableSyncThreadCheck=false;
321 boolean disableIndexThreadCheck=false;
323 HashMap<String, String> noteCache; // Cash of note content
324 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
325 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
326 List<String> historyGuids; // GUIDs of previously viewed items
327 int historyPosition; // Position within the viewed items
328 boolean fromHistory; // Is this from the history queue?
329 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
330 List<Thumbnailer> thumbGenerators; // generate preview image
331 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
332 boolean encryptOnShutdown; // should I encrypt when I close?
333 boolean decryptOnShutdown; // should I decrypt on shutdown;
334 String encryptCipher; // What cipher should I use?
335 Signal0 minimizeToTray;
336 boolean windowMaximized = false; // Keep track of the window state for restores
337 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
338 List<QPixmap> syncIcons; // Array of icons used in sync animation
339 private boolean closeAction = false; // Used to say when to close or when to minimize
340 private static Logger log = Logger.getLogger(NeverNote.class);
341 private String saveLastPath; // last path we used
342 private final QTimer messageTimer; // Timer to clear the status message.
343 private QTimer blockTimer;
344 BrowserWindow blockingWindow;
346 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
349 //***************************************************************
350 //***************************************************************
351 //** Constructor & main entry point
352 //***************************************************************
353 //***************************************************************
354 // Application Constructor
355 @SuppressWarnings("static-access")
356 public NeverNote(DatabaseConnection dbConn) {
358 if (conn.getConnection() == null) {
359 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
360 "is accessing the database or NixNote is already running.\n\n" +
361 "Please end any other process or shutdown the other NixNote before starting.\n\nExiting program."));
363 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
366 setObjectName("mainWindow");
367 // thread().setPriority(Thread.MAX_PRIORITY);
369 logger = new ApplicationLogger("nevernote.log");
370 logger.log(logger.HIGH, "Starting Application");
372 decryptOnShutdown = false;
373 encryptOnShutdown = false;
374 conn.checkDatabaseVersion();
378 // Start building the invalid XML tables
379 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
380 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
382 for (int i=0; i<elements.size(); i++) {
383 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
386 logger.log(logger.EXTREME, "Starting GUI build");
388 QTranslator nevernoteTranslator = new QTranslator();
389 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
390 QApplication.instance().installTranslator(nevernoteTranslator);
392 Global.originalPalette = QApplication.palette();
393 QApplication.setStyle(Global.getStyle());
394 if (Global.useStandardPalette())
395 QApplication.setPalette(QApplication.style().standardPalette());
396 setWindowTitle(tr("NixNote"));
398 mainLeftRightSplitter = new QSplitter();
399 setCentralWidget(mainLeftRightSplitter);
400 leftSplitter1 = new QSplitter();
401 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
403 browserIndexSplitter = new QSplitter();
404 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
406 //* Setup threads & thread timers
407 // int indexRunnerCount = Global.getIndexThreads();
408 // indexRunnerCount = 1;
409 QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount); // increase max thread count
411 logger.log(logger.EXTREME, "Building list manager");
412 listManager = new ListManager(conn, logger);
414 logger.log(logger.EXTREME, "Building index runners & timers");
415 indexRunner = new IndexRunner("indexRunner.log",
416 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
417 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
418 indexThread = new QThread(indexRunner, "Index Thread");
419 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
420 indexRunner.indexImageRecognition = Global.indexImageRecognition();
421 indexRunner.indexNoteBody = Global.indexNoteBody();
422 indexRunner.indexNoteTitle = Global.indexNoteTitle();
423 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
426 synchronizeAnimationTimer = new QTimer();
427 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
429 indexTimer = new QTimer();
430 indexTime = 1000*Global.getIndexThreadSleepInterval();
431 indexTimer.start(indexTime); // Start indexing timer
432 indexTimer.timeout.connect(this, "indexTimer()");
433 indexDisabled = false;
434 indexRunning = false;
436 logger.log(logger.EXTREME, "Setting sync thread & timers");
438 syncRunner = new SyncRunner("syncRunner.log",
439 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
440 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
441 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
442 syncTimer = new QTimer();
443 syncTimer.timeout.connect(this, "syncTimer()");
444 syncRunner.status.message.connect(this, "setMessage(String)");
445 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
446 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
449 automaticSync = true;
450 syncTimer.start(syncTime*60*1000);
452 automaticSync = false;
455 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
456 syncThread = new QThread(syncRunner, "Synchronization Thread");
460 logger.log(logger.EXTREME, "Starting thumnail thread");
461 pdfReadyQueue = new ArrayList<String>();
462 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
463 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
464 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
465 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
466 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
467 thumbnailThread.start();
468 thumbGenerators = new ArrayList<Thumbnailer>();
469 thumbnailTimer = new QTimer();
470 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
472 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
473 thumbnailTimer.start();
475 logger.log(logger.EXTREME, "Starting authentication timer");
476 authTimer = new QTimer();
477 authTimer.timeout.connect(this, "authTimer()");
478 authTimer.start(1000*60*15);
479 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
481 logger.log(logger.EXTREME, "Setting save note timer");
482 saveTimer = new QTimer();
483 saveTimer.timeout.connect(this, "saveNote()");
484 if (Global.getAutoSaveInterval() > 0) {
485 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
488 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
490 logger.log(logger.EXTREME, "Starting external file monitor timer");
491 externalFileSaveTimer = new QTimer();
492 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
493 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
494 externalFiles = new ArrayList<String>();
495 importFilesDelete = new ArrayList<String>();
496 importFilesKeep = new ArrayList<String>();
497 externalFileSaveTimer.start();
499 notebookTree = new NotebookTreeWidget(conn);
500 attributeTree = new AttributeTreeWidget();
501 tagTree = new TagTreeWidget(conn);
502 savedSearchTree = new SavedSearchTreeWidget();
503 trashTree = new TrashTreeWidget();
504 noteTableView = new TableView(logger, listManager);
506 searchField = new QComboBox();
507 searchField.setObjectName("searchField");
508 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
509 searchField.setEditable(true);
510 searchField.activatedIndex.connect(this, "searchFieldChanged()");
511 searchField.setDuplicatesEnabled(false);
512 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
513 searchShortcut = new QShortcut(this);
514 setupShortcut(searchShortcut, "Focus_Search");
515 searchShortcut.activated.connect(this, "focusSearch()");
517 quotaBar = new QuotaProgressBar();
519 zoomSpinner = new QSpinBox();
520 zoomSpinner.setMinimum(10);
521 zoomSpinner.setMaximum(1000);
522 zoomSpinner.setAccelerated(true);
523 zoomSpinner.setSingleStep(10);
524 zoomSpinner.setValue(100);
525 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
527 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
530 QGridLayout leftGrid = new QGridLayout();
531 leftSplitter1.setContentsMargins(5, 0, 0, 7);
532 leftSplitter1.setLayout(leftGrid);
533 leftGrid.addWidget(searchLayout,1,1);
534 leftGrid.addWidget(tagTree,2,1);
535 leftGrid.addWidget(attributeTree,3,1);
536 leftGrid.addWidget(savedSearchTree,4,1);
537 leftGrid.addWidget(trashTree,5, 1);
539 // Setup the browser window
540 noteCache = new HashMap<String,String>();
541 readOnlyCache = new HashMap<String, Boolean>();
542 inkNoteCache = new HashMap<String, Boolean>();
543 browserWindow = new BrowserWindow(conn);
545 mainLeftRightSplitter.addWidget(leftSplitter1);
546 mainLeftRightSplitter.addWidget(browserIndexSplitter);
548 if (Global.getListView() == Global.View_List_Wide) {
549 browserIndexSplitter.addWidget(noteTableView);
550 browserIndexSplitter.addWidget(browserWindow);
552 mainLeftRightSplitter.addWidget(noteTableView);
553 mainLeftRightSplitter.addWidget(browserWindow);
556 // Setup the thumbnail viewer
557 thumbnailViewer = new ThumbnailViewer();
558 thumbnailViewer.upArrow.connect(this, "upAction()");
559 thumbnailViewer.downArrow.connect(this, "downAction()");
560 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
561 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
563 //Setup external browser manager
564 externalWindows = new HashMap<String, ExternalBrowse>();
566 listManager.loadNotesIndex();
567 initializeNotebookTree();
569 initializeSavedSearchTree();
570 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
571 attributeTreeSelected = null;
572 initializeNoteTable();
574 selectedNoteGUIDs = new ArrayList<String>();
575 statusBar = new QStatusBar();
576 setStatusBar(statusBar);
577 menuBar = new MainMenuBar(this);
578 emitLog = new ArrayList<String>();
580 tagTree.setDeleteAction(menuBar.tagDeleteAction);
581 tagTree.setMergeAction(menuBar.tagMergeAction);
582 tagTree.setEditAction(menuBar.tagEditAction);
583 tagTree.setAddAction(menuBar.tagAddAction);
584 tagTree.setIconAction(menuBar.tagIconAction);
585 tagTree.setVisible(Global.isWindowVisible("tagTree"));
586 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
587 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
588 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
589 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
591 if (!Global.isWindowVisible("zoom")) {
592 searchLayout.hideZoom();
593 menuBar.hideZoom.setChecked(false);
596 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
597 notebookTree.setEditAction(menuBar.notebookEditAction);
598 notebookTree.setAddAction(menuBar.notebookAddAction);
599 notebookTree.setIconAction(menuBar.notebookIconAction);
600 notebookTree.setStackAction(menuBar.notebookStackAction);
601 notebookTree.setPublishAction(menuBar.notebookPublishAction);
602 notebookTree.setShareAction(menuBar.notebookShareAction);
603 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
604 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
605 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
606 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
607 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
609 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
610 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
611 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
612 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
613 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
614 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
615 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
617 noteTableView.setAddAction(menuBar.noteAdd);
618 noteTableView.setDeleteAction(menuBar.noteDelete);
619 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
620 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
621 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
622 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
623 noteTableView.noteSignal.notePinned.connect(this, "notePinned()");
624 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
625 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
626 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
627 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
629 quotaBar.setMouseClickAction(menuBar.accountAction);
632 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
633 trashTree.setEmptyAction(menuBar.emptyTrashAction);
634 trashTree.setVisible(Global.isWindowVisible("trashTree"));
635 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
636 trashTree.updateCounts(listManager.getTrashCount());
637 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
638 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
640 noteTableView.setVisible(Global.isWindowVisible("noteList"));
641 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
643 if (!Global.isWindowVisible("editorButtonBar"))
644 toggleEditorButtonBar();
645 if (!Global.isWindowVisible("leftPanel"))
646 menuBar.hideLeftSide.setChecked(true);
647 if (Global.isWindowVisible("noteInformation"))
648 toggleNoteInformation();
649 quotaBar.setVisible(Global.isWindowVisible("quota"));
650 if (!quotaBar.isVisible())
651 menuBar.hideQuota.setChecked(false);
652 searchField.setVisible(Global.isWindowVisible("searchField"));
653 if (!searchField.isVisible())
654 menuBar.hideSearch.setChecked(false);
656 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
661 find = new FindDialog();
662 find.getOkButton().clicked.connect(this, "doFindText()");
664 // Setup the tray icon menu bar
665 trayShowAction = new QAction(tr("Show/Hide"), this);
666 trayExitAction = new QAction(tr("Exit"), this);
667 trayAddNoteAction = new QAction(tr("Add Note"), this);
669 trayExitAction.triggered.connect(this, "closeNeverNote()");
670 trayAddNoteAction.triggered.connect(this, "addNote()");
671 trayShowAction.triggered.connect(this, "trayToggleVisible()");
673 trayMenu = new QMenu(this);
674 trayMenu.addAction(trayAddNoteAction);
675 trayMenu.addAction(trayShowAction);
676 trayMenu.addAction(trayExitAction);
679 trayIcon = new QSystemTrayIcon(this);
680 trayIcon.setToolTip(tr("NixNote"));
681 trayIcon.setContextMenu(trayMenu);
682 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
685 currentNoteGuid = Global.getLastViewedNoteGuid();
686 historyGuids = new ArrayList<String>();
690 if (!currentNoteGuid.trim().equals("")) {
691 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
694 noteIndexUpdated(true);
696 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
697 if (menuBar.showEditorBar.isChecked())
698 showEditorButtons(browserWindow);
699 tagIndexUpdated(true);
700 savedSearchIndexUpdated();
701 notebookIndexUpdated();
703 setupSyncSignalListeners();
704 setupBrowserSignalListeners();
705 setupIndexListeners();
708 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
709 tagTree.showAllTags(true);
711 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
712 setWindowIcon(appIcon);
713 trayIcon.setIcon(appIcon);
714 if (Global.showTrayIcon())
719 scrollToGuid(currentNoteGuid);
720 if (Global.automaticLogin()) {
722 if (Global.isConnected)
725 setupFolderImports();
728 restoreWindowState(true);
730 if (Global.mimicEvernoteInterface) {
731 notebookTree.selectGuid("");
734 threadMonitorTimer = new QTimer();
735 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
736 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
738 historyGuids.add(currentNoteGuid);
741 menuBar.blockSignals(true);
742 menuBar.narrowListView.blockSignals(true);
743 menuBar.wideListView.blockSignals(true);
744 if (Global.getListView() == Global.View_List_Narrow) {
745 menuBar.narrowListView.setChecked(true);
748 menuBar.wideListView.setChecked(true);
750 menuBar.blockSignals(false);
751 menuBar.narrowListView.blockSignals(false);
752 menuBar.wideListView.blockSignals(false);
754 if (Global.getListView() == Global.View_List_Wide) {
755 browserIndexSplitter.addWidget(noteTableView);
756 browserIndexSplitter.addWidget(browserWindow);
758 mainLeftRightSplitter.addWidget(noteTableView);
759 mainLeftRightSplitter.addWidget(browserWindow);
762 messageTimer = new QTimer();
763 messageTimer.timeout.connect(this, "clearMessage()");
764 messageTimer.setInterval(1000*15);
767 int sortCol = Global.getSortColumn();
768 int sortOrder = Global.getSortOrder();
769 noteTableView.proxyModel.blocked = true;
770 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
771 noteTableView.proxyModel.blocked = false;
772 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
774 if (Global.checkVersionUpgrade())
779 public static void main(String[] args) {
780 log.setLevel(Level.FATAL);
781 QApplication.initialize(args);
782 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
783 QSplashScreen splash = new QSplashScreen(pixmap);
786 DatabaseConnection dbConn;
789 initializeGlobalSettings(args);
791 showSplash = Global.isWindowVisible("SplashScreen");
795 dbConn = setupDatabaseConnection();
797 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
798 Global.getFileManager().purgeResDirectory(true);
800 } catch (InitializationException e) {
803 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
807 NeverNote application = new NeverNote(dbConn);
809 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
810 if (Global.startMinimized())
811 application.showMinimized();
813 if (Global.wasWindowMaximized())
814 application.showMaximized();
820 splash.finish(application);
822 System.out.println("Goodbye.");
827 * Open the internal database, or create if not present
829 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
831 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
832 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
834 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
835 File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
836 File fi = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
838 Global.setDatabaseUrl("");
840 Global.setResourceDatabaseUrl("");
842 Global.setIndexDatabaseUrl("");
844 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
845 boolean goodCheck = false;
847 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
849 if (!dialog.okPressed())
851 Global.cipherPassword = dialog.getPassword();
852 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
853 Global.getDatabaseUserPassword(), Global.cipherPassword);
856 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
857 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
858 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
862 // Encrypt the database upon shutdown
863 private void encryptOnShutdown() {
864 String dbPath= Global.getFileManager().getDbDirPath("");
867 Statement st = conn.getConnection().createStatement();
868 st.execute("shutdown");
869 st = conn.getResourceConnection().createStatement();
870 st.execute("shutdown");
871 st = conn.getIndexConnection().createStatement();
872 st.execute("shutdown");
873 if (QMessageBox.question(this, tr("Are you sure"),
874 tr("Are you sure you wish to encrypt the database?"),
875 QMessageBox.StandardButton.Yes,
876 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
877 ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
878 ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
879 ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
880 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
881 Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
882 Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
884 QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
886 } catch (SQLException e) {
891 // Decrypt the database upon shutdown
892 private void decryptOnShutdown() {
893 String dbPath= Global.getFileManager().getDbDirPath("");
894 String dbName = "NeverNote";
896 Statement st = conn.getConnection().createStatement();
897 st.execute("shutdown");
898 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
899 encryptCipher = "AES";
901 encryptCipher = "XTEA";
902 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
903 "Are you sure you wish to decrypt the database?"),
904 QMessageBox.StandardButton.Yes,
905 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
907 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
908 Global.setDatabaseUrl("");
909 Global.setResourceDatabaseUrl("");
910 Global.setIndexDatabaseUrl("");
911 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
913 } catch (SQLException e) {
918 * Encrypt/Decrypt the local database
920 public void doDatabaseEncrypt() {
921 // The database is not currently encrypted
922 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
923 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
924 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
925 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
926 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
927 "Do you wish to proceed?"),
928 QMessageBox.StandardButton.Yes,
929 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
932 DBEncryptDialog dialog = new DBEncryptDialog();
934 if (dialog.okPressed()) {
935 Global.cipherPassword = dialog.getPassword();
936 encryptOnShutdown = true;
937 encryptCipher = dialog.getEncryptionMethod();
940 DBEncryptDialog dialog = new DBEncryptDialog();
941 dialog.setWindowTitle(tr("Database Decryption"));
942 dialog.hideEncryption();
944 if (dialog.okPressed()) {
945 if (!dialog.getPassword().equals(Global.cipherPassword)) {
946 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
949 decryptOnShutdown = true;
956 private static void initializeGlobalSettings(String[] args) throws InitializationException {
957 StartupConfig startupConfig = new StartupConfig();
959 for (String arg : args) {
960 String lower = arg.toLowerCase();
961 if (lower.startsWith("--name="))
962 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
963 if (lower.startsWith("--home="))
964 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
965 if (lower.startsWith("--disable-viewing"))
966 startupConfig.setDisableViewing(true);
968 Global.setup(startupConfig);
973 public void closeEvent(QCloseEvent event) {
974 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
979 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
982 if (currentNote!= null & browserWindow!=null) {
983 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
984 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
987 setMessage(tr("Beginning shutdown."));
989 // Close down external windows
990 Collection<ExternalBrowse> windows = externalWindows.values();
991 Iterator<ExternalBrowse> iterator = windows.iterator();
992 while (iterator.hasNext()) {
993 ExternalBrowse browser = iterator.next();
994 browser.windowClosing.disconnect();
999 externalFileEditedSaver();
1000 if (Global.isConnected && Global.synchronizeOnClose()) {
1001 setMessage(tr("Performing synchronization before closing."));
1002 syncRunner.syncNeeded = true;
1003 syncRunner.addWork("SYNC");
1005 syncRunner.keepRunning = false;
1007 syncRunner.addWork("STOP");
1008 setMessage("Closing Program.");
1009 threadMonitorTimer.stop();
1011 thumbnailRunner.addWork("STOP");
1012 indexRunner.addWork("STOP");
1017 if (tempFiles != null)
1020 browserWindow.noteSignal.tagsChanged.disconnect();
1021 browserWindow.noteSignal.titleChanged.disconnect();
1022 browserWindow.noteSignal.noteChanged.disconnect();
1023 browserWindow.noteSignal.notebookChanged.disconnect();
1024 browserWindow.noteSignal.createdDateChanged.disconnect();
1025 browserWindow.noteSignal.alteredDateChanged.disconnect();
1026 syncRunner.searchSignal.listChanged.disconnect();
1027 syncRunner.tagSignal.listChanged.disconnect();
1028 syncRunner.notebookSignal.listChanged.disconnect();
1029 syncRunner.noteIndexSignal.listChanged.disconnect();
1032 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1033 saveNoteColumnPositions();
1034 saveNoteIndexWidth();
1036 int width = notebookTree.columnWidth(0);
1037 Global.setColumnWidth("notebookTreeName", width);
1038 width = tagTree.columnWidth(0);
1039 Global.setColumnWidth("tagTreeName", width);
1041 Global.saveWindowMaximized(isMaximized());
1042 Global.saveCurrentNoteGuid(currentNoteGuid);
1044 int sortCol = noteTableView.proxyModel.sortColumn();
1045 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1046 Global.setSortColumn(sortCol);
1047 Global.setSortOrder(sortOrder);
1051 Global.keepRunning = false;
1053 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1054 if (indexRunner.thread().isAlive())
1055 indexRunner.thread().join(50);
1056 if (!indexRunner.thread().isAlive())
1057 logger.log(logger.MEDIUM, "Index thread has stopped");
1059 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1060 indexRunner.thread().interrupt();
1062 } catch (InterruptedException e1) {
1063 e1.printStackTrace();
1066 if (!syncRunner.thread().isAlive()) {
1067 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1068 if (syncRunner.thread().isAlive()) {
1069 System.out.println(tr("Synchronizing. Please be patient."));
1070 for(;syncRunner.thread().isAlive();) {
1073 } catch (InterruptedException e) {
1074 e.printStackTrace();
1078 logger.log(logger.MEDIUM, "Sync thread has stopped");
1081 if (encryptOnShutdown) {
1082 encryptOnShutdown();
1084 if (decryptOnShutdown) {
1085 decryptOnShutdown();
1088 Global.getFileManager().purgeResDirectory(false);
1089 } catch (InitializationException e) {
1090 System.out.println(tr("Empty res directory purge failed"));
1091 e.printStackTrace();
1093 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1096 @SuppressWarnings("unused")
1097 private void closeNeverNote() {
1101 public void setMessage(String s) {
1102 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1105 logger.log(logger.HIGH, "Message: " +s);
1106 statusBar.showMessage(s);
1110 messageTimer.stop();
1111 messageTimer.setSingleShot(true);
1112 messageTimer.start();
1115 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1118 private void clearMessage() {
1119 statusBar.clearMessage();
1123 private void waitCursor(boolean wait) {
1125 if (QApplication.overrideCursor() == null)
1126 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1129 while (QApplication.overrideCursor() != null)
1130 QApplication.restoreOverrideCursor();
1132 listManager.refreshCounters();
1135 private void setupIndexListeners() {
1136 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1137 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1138 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1139 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1141 private void setupSyncSignalListeners() {
1142 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1143 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1144 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1145 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1146 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1148 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1149 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1150 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1152 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1153 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1154 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1155 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1156 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1158 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1161 private void setupBrowserSignalListeners() {
1162 setupBrowserWindowListeners(browserWindow, true);
1165 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1166 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1167 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1168 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1169 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1170 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1171 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1172 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1173 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1174 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1175 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1176 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1177 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1178 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1179 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1180 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1181 browser.unblockApplication.connect(this, "unblockApplication()");
1182 if (master) browser.focusLost.connect(this, "saveNote()");
1183 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1184 browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1187 //**************************************************
1189 //**************************************************
1190 private void setupShortcut(QShortcut action, String text) {
1191 if (!Global.shortcutKeys.containsAction(text))
1193 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1196 //***************************************************************
1197 //***************************************************************
1198 //* Settings and look & feel
1199 //***************************************************************
1200 //***************************************************************
1201 @SuppressWarnings("unused")
1202 private void settings() {
1203 logger.log(logger.HIGH, "Entering NeverNote.settings");
1204 saveNoteColumnPositions();
1205 saveNoteIndexWidth();
1207 ConfigDialog settings = new ConfigDialog(this);
1208 String dateFormat = Global.getDateFormat();
1209 String timeFormat = Global.getTimeFormat();
1211 indexTime = 1000*Global.getIndexThreadSleepInterval();
1212 indexTimer.start(indexTime); // reset indexing timer
1215 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1216 indexRunner.indexNoteBody = Global.indexNoteBody();
1217 indexRunner.indexNoteTitle = Global.indexNoteTitle();
1218 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1219 indexRunner.indexImageRecognition = Global.indexImageRecognition();
1220 if (Global.showTrayIcon())
1225 if (menuBar.showEditorBar.isChecked())
1226 showEditorButtons(browserWindow);
1228 // Reset the save timer
1229 if (Global.getAutoSaveInterval() > 0)
1230 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1235 // Set special reloads
1236 if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1237 conn.executeSql("Delete from LinkedNotebook");
1238 conn.executeSql("delete from SharedNotebook");
1239 conn.executeSql("Delete from Notebook where linked=true");
1240 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1241 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1246 readOnlyCache.clear();
1247 inkNoteCache.clear();
1248 noteIndexUpdated(true);
1250 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1252 // Restore things to the way they were
1253 private void restoreWindowState(boolean mainWindow) {
1254 // We need to name things or this doesn't work.
1255 setObjectName("NeverNote");
1256 restoreState(Global.restoreState(objectName()));
1257 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1258 browserIndexSplitter.setObjectName("browserIndexSplitter");
1259 leftSplitter1.setObjectName("leftSplitter1");
1261 // Restore the actual positions.
1263 restoreGeometry(Global.restoreGeometry(objectName()));
1264 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1265 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1266 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1269 // Save window positions for the next start
1270 private void saveWindowState() {
1271 Global.saveGeometry(objectName(), saveGeometry());
1272 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1273 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1274 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1275 Global.saveState(objectName(), saveState());
1277 // Load the style sheet
1278 private void loadStyleSheet() {
1279 String styleSheetName = "default.qss";
1280 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1281 styleSheetName = "default-cleanlooks.qss";
1282 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1283 QFile file = new QFile(fileName);
1285 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1286 if (!file.exists()) {
1287 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1288 file = new QFile(fileName);
1290 file.open(OpenModeFlag.ReadOnly);
1291 String styleSheet = file.readAll().toString();
1293 setStyleSheet(styleSheet);
1295 // Save column positions for the next time
1296 private void saveNoteColumnPositions() {
1297 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1298 Global.setColumnPosition("noteTableCreationPosition", position);
1299 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1300 Global.setColumnPosition("noteTableTagPosition", position);
1301 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1302 Global.setColumnPosition("noteTableNotebookPosition", position);
1303 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1304 Global.setColumnPosition("noteTableChangedPosition", position);
1305 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1306 Global.setColumnPosition("noteTableAuthorPosition", position);
1307 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1308 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1309 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1310 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1311 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1312 Global.setColumnPosition("noteTableTitlePosition", position);
1313 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1314 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1315 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1316 Global.setColumnPosition("noteTableGuidPosition", position);
1317 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1318 Global.setColumnPosition("noteTableThumbnailPosition", position);
1319 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1320 Global.setColumnPosition("noteTablePinnedPosition", position);
1323 // Save column widths for the next time
1324 private void saveNoteIndexWidth() {
1326 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1327 Global.setColumnWidth("noteTableCreationPosition", width);
1328 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1329 Global.setColumnWidth("noteTableChangedPosition", width);
1330 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1331 Global.setColumnWidth("noteTableGuidPosition", width);
1332 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1333 Global.setColumnWidth("noteTableNotebookPosition", width);
1334 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1335 Global.setColumnWidth("noteTableTagPosition", width);
1336 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1337 Global.setColumnWidth("noteTableTitlePosition", width);
1338 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1339 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1340 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1341 Global.setColumnWidth("noteTableAuthorPosition", width);
1342 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1343 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1344 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1345 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1346 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1347 Global.setColumnWidth("noteTableThumbnailPosition", width);
1348 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1349 Global.setColumnWidth("noteTableGuidPosition", width);
1350 width = noteTableView.getColumnWidth(Global.noteTablePinnedPosition);
1351 Global.setColumnWidth("noteTablePinnedPosition", width);
1354 @SuppressWarnings("unused")
1355 private void toggleSearchWindow() {
1356 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1357 searchLayout.toggleSearchField();
1358 menuBar.hideSearch.setChecked(searchField.isVisible());
1359 Global.saveWindowVisible("searchField", searchField.isVisible());
1360 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1362 @SuppressWarnings("unused")
1363 private void toggleQuotaWindow() {
1364 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1365 searchLayout.toggleQuotaBar();
1366 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1367 Global.saveWindowVisible("quota", quotaBar.isVisible());
1368 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1370 @SuppressWarnings("unused")
1371 private void toggleZoomWindow() {
1372 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1373 searchLayout.toggleZoom();
1374 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1375 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1376 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1381 //***************************************************************
1382 //***************************************************************
1383 //** These functions deal with Notebook menu items
1384 //***************************************************************
1385 //***************************************************************
1386 // Setup the tree containing the user's notebooks.
1387 private void initializeNotebookTree() {
1388 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1389 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1390 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1391 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1392 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1394 // Listener when a notebook is selected
1395 private void notebookTreeSelection() {
1396 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1397 noteTableView.proxyModel.blocked = true;
1400 clearAttributeFilter();
1401 clearSavedSearchFilter();
1402 if (Global.mimicEvernoteInterface) {
1404 searchField.clear();
1406 menuBar.noteRestoreAction.setVisible(false);
1407 menuBar.notebookEditAction.setEnabled(true);
1408 menuBar.notebookDeleteAction.setEnabled(true);
1409 menuBar.notebookPublishAction.setEnabled(true);
1410 menuBar.notebookShareAction.setEnabled(true);
1411 menuBar.notebookIconAction.setEnabled(true);
1412 menuBar.notebookStackAction.setEnabled(true);
1413 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1414 selectedNotebookGUIDs.clear();
1416 String stackName = "";
1417 if (selections.size() > 0) {
1418 guid = (selections.get(0).text(2));
1419 stackName = selections.get(0).text(0);
1421 if (!Global.mimicEvernoteInterface) {
1422 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1423 if (selections.size()==0) {
1424 selectedNotebookGUIDs.clear();
1425 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1426 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1428 menuBar.notebookEditAction.setEnabled(false);
1429 menuBar.notebookDeleteAction.setEnabled(false);
1430 menuBar.notebookStackAction.setEnabled(false);
1431 menuBar.notebookIconAction.setEnabled(false);
1434 if (!guid.equals("") && !guid.equals("STACK")) {
1435 selectedNotebookGUIDs.add(guid);
1436 menuBar.notebookIconAction.setEnabled(true);
1438 menuBar.notebookIconAction.setEnabled(true);
1439 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1440 Notebook book = listManager.getNotebookIndex().get(j);
1441 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1442 selectedNotebookGUIDs.add(book.getGuid());
1445 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1446 listManager.loadNotesIndex();
1447 noteIndexUpdated(false);
1448 refreshEvernoteNote(true);
1449 listManager.refreshCounters = true;
1450 listManager.refreshCounters();
1451 if (selectedNotebookGUIDs.size() == 1) {
1452 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1453 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1455 noteTableView.proxyModel.blocked = true;
1457 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1459 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1462 noteTableView.proxyModel.blocked = false;
1463 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1466 private void clearNotebookFilter() {
1467 notebookTree.blockSignals(true);
1468 notebookTree.clearSelection();
1469 menuBar.noteRestoreAction.setVisible(false);
1470 menuBar.notebookEditAction.setEnabled(false);
1471 menuBar.notebookDeleteAction.setEnabled(false);
1472 selectedNotebookGUIDs.clear();
1473 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1474 notebookTree.blockSignals(false);
1476 // Triggered when the notebook DB has been updated
1477 private void notebookIndexUpdated() {
1478 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1480 // Get the possible icons
1481 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1482 notebookTree.setIcons(icons);
1484 if (selectedNotebookGUIDs == null)
1485 selectedNotebookGUIDs = new ArrayList<String>();
1486 List<Notebook> books = conn.getNotebookTable().getAll();
1487 for (int i=books.size()-1; i>=0; i--) {
1488 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1489 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1491 j=listManager.getArchiveNotebookIndex().size();
1497 listManager.countNotebookResults(listManager.getNoteIndex());
1498 notebookTree.blockSignals(true);
1499 notebookTree.load(books, listManager.getLocalNotebooks());
1500 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1501 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1503 selectedNotebookGUIDs.remove(i);
1505 listManager.refreshCounters = true;
1506 listManager.refreshCounters();
1507 notebookTree.blockSignals(false);
1509 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1511 // Show/Hide note information
1512 @SuppressWarnings("unused")
1513 private void toggleNotebookWindow() {
1514 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1515 searchLayout.toggleNotebook();
1516 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1517 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1518 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1520 // Add a new notebook
1521 @SuppressWarnings("unused")
1522 private void addNotebook() {
1523 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1524 NotebookEdit edit = new NotebookEdit();
1525 edit.setNotebooks(listManager.getNotebookIndex());
1528 if (!edit.okPressed())
1531 Calendar currentTime = new GregorianCalendar();
1532 Long l = new Long(currentTime.getTimeInMillis());
1533 String randint = new String(Long.toString(l));
1535 Notebook newBook = new Notebook();
1536 newBook.setUpdateSequenceNum(0);
1537 newBook.setGuid(randint);
1538 newBook.setName(edit.getNotebook());
1539 newBook.setServiceCreated(new Date().getTime());
1540 newBook.setServiceUpdated(new Date().getTime());
1541 newBook.setDefaultNotebook(false);
1542 newBook.setPublished(false);
1544 listManager.getNotebookIndex().add(newBook);
1546 listManager.getLocalNotebooks().add(newBook.getGuid());
1547 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1548 notebookIndexUpdated();
1549 listManager.countNotebookResults(listManager.getNoteIndex());
1550 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1551 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1553 // Edit an existing notebook
1554 @SuppressWarnings("unused")
1555 private void stackNotebook() {
1556 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1557 StackNotebook edit = new StackNotebook();
1559 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1560 QTreeWidgetItem currentSelection;
1561 for (int i=0; i<selections.size(); i++) {
1562 currentSelection = selections.get(0);
1563 String guid = currentSelection.text(2);
1564 if (guid.equalsIgnoreCase("")) {
1565 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1568 if (guid.equalsIgnoreCase("STACK")) {
1569 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1574 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1579 if (!edit.okPressed())
1582 String stack = edit.getStackName();
1584 for (int i=0; i<selections.size(); i++) {
1585 currentSelection = selections.get(i);
1586 String guid = currentSelection.text(2);
1587 listManager.updateNotebookStack(guid, stack);
1589 notebookIndexUpdated();
1590 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1592 // Edit an existing notebook
1593 @SuppressWarnings("unused")
1594 private void editNotebook() {
1595 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1596 NotebookEdit edit = new NotebookEdit();
1598 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1599 QTreeWidgetItem currentSelection;
1600 currentSelection = selections.get(0);
1601 edit.setNotebook(currentSelection.text(0));
1603 String guid = currentSelection.text(2);
1604 if (!guid.equalsIgnoreCase("STACK")) {
1605 edit.setTitle(tr("Edit Notebook"));
1606 edit.setNotebooks(listManager.getNotebookIndex());
1607 edit.setLocalCheckboxEnabled(false);
1608 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1609 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1610 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1611 i=listManager.getNotebookIndex().size();
1615 edit.setTitle(tr("Edit Stack"));
1616 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1617 edit.hideLocalCheckbox();
1618 edit.hideDefaultCheckbox();
1623 if (!edit.okPressed())
1627 if (guid.equalsIgnoreCase("STACK")) {
1628 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1629 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1630 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1631 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1632 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1634 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1635 currentSelection.setText(0, edit.getNotebook());
1639 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1640 currentSelection.setText(0, edit.getNotebook());
1642 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1643 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1644 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1645 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1646 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1647 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1648 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1649 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1651 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1652 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1653 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1654 linkedNotebook.setShareName(edit.getNotebook());
1655 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1657 i=listManager.getNotebookIndex().size();
1661 // Build a list of non-closed notebooks
1662 List<Notebook> nbooks = new ArrayList<Notebook>();
1663 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1664 boolean found=false;
1665 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1666 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1670 nbooks.add(listManager.getNotebookIndex().get(i));
1674 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1675 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1676 browserWindow.setNotebookList(filteredBooks);
1677 Iterator<String> set = externalWindows.keySet().iterator();
1678 while(set.hasNext())
1679 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1680 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1682 // Publish a notebook
1683 @SuppressWarnings("unused")
1684 private void publishNotebook() {
1685 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1686 QTreeWidgetItem currentSelection;
1687 currentSelection = selections.get(0);
1688 String guid = currentSelection.text(2);
1690 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1695 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1696 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1697 n = listManager.getNotebookIndex().get(i);
1699 i = listManager.getNotebookIndex().size();
1705 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1708 if (!publish.okClicked())
1711 Publishing p = publish.getPublishing();
1712 boolean isPublished = !publish.isStopPressed();
1713 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1714 n.setPublished(isPublished);
1716 listManager.getNotebookIndex().set(position, n);
1717 notebookIndexUpdated();
1719 // Publish a notebook
1720 @SuppressWarnings("unused")
1721 private void shareNotebook() {
1722 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1723 QTreeWidgetItem currentSelection;
1724 currentSelection = selections.get(0);
1725 String guid = currentSelection.text(2);
1727 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1731 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1732 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1733 n = listManager.getNotebookIndex().get(i);
1734 i = listManager.getNotebookIndex().size();
1738 String authToken = null;
1739 if (syncRunner.isConnected)
1740 authToken = syncRunner.authToken;
1741 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1746 // Delete an existing notebook
1747 @SuppressWarnings("unused")
1748 private void deleteNotebook() {
1749 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1750 boolean stacksFound = false;
1751 boolean notebooksFound = false;
1752 boolean assigned = false;
1753 // Check if any notes have this notebook
1754 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1755 for (int i=0; i<selections.size(); i++) {
1756 QTreeWidgetItem currentSelection;
1757 currentSelection = selections.get(i);
1758 String guid = currentSelection.text(2);
1759 if (!guid.equalsIgnoreCase("STACK")) {
1760 notebooksFound = true;
1761 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1762 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1763 if (noteGuid.equals(guid)) {
1765 j=listManager.getNoteIndex().size();
1766 i=selections.size();
1774 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1775 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1779 if (conn.getNotebookTable().getAll().size() == 1) {
1780 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1784 // If all notebooks are clear, verify the delete
1785 String msg1 = new String(tr("Delete selected notebooks?"));
1786 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1787 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1788 " not deleted unless selected?"));
1790 if (stacksFound && notebooksFound)
1792 if (!stacksFound && notebooksFound)
1794 if (stacksFound && !notebooksFound)
1796 if (QMessageBox.question(this, tr("Confirmation"), msg,
1797 QMessageBox.StandardButton.Yes,
1798 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1802 // If confirmed, delete the notebook
1803 for (int i=selections.size()-1; i>=0; i--) {
1804 QTreeWidgetItem currentSelection;
1805 currentSelection = selections.get(i);
1806 String guid = currentSelection.text(2);
1807 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1808 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1809 listManager.renameStack(currentSelection.text(0), "");
1811 conn.getNotebookTable().expungeNotebook(guid, true);
1812 listManager.deleteNotebook(guid);
1816 notebookIndexUpdated();
1817 // notebookTreeSelection();
1818 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1819 // listManager.countNotebookResults(listManager.getNoteIndex());
1820 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1822 // A note's notebook has been updated
1823 @SuppressWarnings("unused")
1824 private void updateNoteNotebook(String guid, String notebookGuid) {
1826 // Update the list manager
1827 listManager.updateNoteNotebook(guid, notebookGuid);
1828 listManager.countNotebookResults(listManager.getNoteIndex());
1829 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1831 // Find the name of the notebook
1832 String notebookName = null;
1833 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1834 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1835 notebookName = listManager.getNotebookIndex().get(i).getName();
1840 // If we found the name, update the browser window
1841 if (notebookName != null) {
1842 updateListNoteNotebook(guid, notebookName);
1843 if (guid.equals(currentNoteGuid)) {
1844 int pos = browserWindow.notebookBox.findText(notebookName);
1846 browserWindow.notebookBox.setCurrentIndex(pos);
1850 // If we're dealing with the current note, then we need to be sure and update the notebook there
1851 if (guid.equals(currentNoteGuid)) {
1852 if (currentNote != null) {
1853 currentNote.setNotebookGuid(notebookGuid);
1857 // Open/close notebooks
1858 @SuppressWarnings("unused")
1859 private void closeNotebooks() {
1860 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1862 if (!na.okClicked())
1866 listManager.getArchiveNotebookIndex().clear();
1868 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1869 String text = na.getClosedBookList().takeItem(i).text();
1870 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1871 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1872 Notebook n = listManager.getNotebookIndex().get(j);
1873 conn.getNotebookTable().setArchived(n.getGuid(),true);
1874 listManager.getArchiveNotebookIndex().add(n);
1875 j=listManager.getNotebookIndex().size();
1880 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1881 String text = na.getOpenBookList().takeItem(i).text();
1882 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1883 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1884 Notebook n = listManager.getNotebookIndex().get(j);
1885 conn.getNotebookTable().setArchived(n.getGuid(),false);
1886 j=listManager.getNotebookIndex().size();
1890 notebookTreeSelection();
1891 listManager.loadNotesIndex();
1892 notebookIndexUpdated();
1893 noteIndexUpdated(false);
1894 reloadTagTree(true);
1895 // noteIndexUpdated(false);
1897 // Build a list of non-closed notebooks
1898 List<Notebook> nbooks = new ArrayList<Notebook>();
1899 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1900 boolean found=false;
1901 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1902 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1906 nbooks.add(listManager.getNotebookIndex().get(i));
1909 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1910 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1911 browserWindow.setNotebookList(filteredBooks);
1913 // Update any external windows
1914 Iterator<String> set = externalWindows.keySet().iterator();
1915 while(set.hasNext())
1916 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1920 // Change the notebook's icon
1921 @SuppressWarnings("unused")
1922 private void setNotebookIcon() {
1923 boolean stackSelected = false;
1924 boolean allNotebookSelected = false;
1926 QTreeWidgetItem currentSelection;
1927 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1928 if (selections.size() == 0)
1931 currentSelection = selections.get(0);
1932 String guid = currentSelection.text(2);
1933 if (guid.equalsIgnoreCase(""))
1934 allNotebookSelected = true;
1935 if (guid.equalsIgnoreCase("STACK"))
1936 stackSelected = true;
1938 QIcon currentIcon = currentSelection.icon(0);
1942 if (!stackSelected && !allNotebookSelected) {
1943 icon = conn.getNotebookTable().getIcon(guid);
1945 dialog = new SetIcon(currentIcon, saveLastPath);
1946 dialog.setUseDefaultIcon(true);
1948 dialog = new SetIcon(icon, saveLastPath);
1949 dialog.setUseDefaultIcon(false);
1952 if (stackSelected) {
1953 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1955 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1958 dialog = new SetIcon(currentIcon, saveLastPath);
1959 dialog.setUseDefaultIcon(true);
1961 dialog = new SetIcon(icon, saveLastPath);
1962 dialog.setUseDefaultIcon(false);
1966 if (dialog.okPressed()) {
1967 saveLastPath = dialog.getPath();
1969 QIcon newIcon = dialog.getIcon();
1970 if (stackSelected) {
1971 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1972 if (newIcon == null) {
1973 newIcon = new QIcon(iconPath+"books2.png");
1975 currentSelection.setIcon(0,newIcon);
1978 if (allNotebookSelected) {
1979 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1980 if (newIcon == null) {
1981 newIcon = new QIcon(iconPath+"notebook-green.png");
1983 currentSelection.setIcon(0,newIcon);
1986 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1987 if (newIcon == null) {
1988 boolean isPublished = false;;
1989 boolean found = false;
1990 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1991 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1992 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1996 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1998 currentSelection.setIcon(0, newIcon);
2004 //***************************************************************
2005 //***************************************************************
2006 //** These functions deal with Tag menu items
2007 //***************************************************************
2008 //***************************************************************
2009 // Add a new notebook
2010 @SuppressWarnings("unused")
2011 private void addTag() {
2012 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2013 TagEdit edit = new TagEdit();
2014 edit.setTagList(listManager.getTagIndex());
2016 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2017 QTreeWidgetItem currentSelection = null;
2018 if (selections.size() > 0) {
2019 currentSelection = selections.get(0);
2020 edit.setParentTag(currentSelection.text(0));
2025 if (!edit.okPressed())
2028 Calendar currentTime = new GregorianCalendar();
2029 Long l = new Long(currentTime.getTimeInMillis());
2030 String randint = new String(Long.toString(l));
2032 Tag newTag = new Tag();
2033 newTag.setUpdateSequenceNum(0);
2034 newTag.setGuid(randint);
2035 newTag.setName(edit.getTag());
2036 if (edit.getParentTag().isChecked()) {
2037 newTag.setParentGuid(currentSelection.text(2));
2038 newTag.setParentGuidIsSet(true);
2039 currentSelection.setExpanded(true);
2041 conn.getTagTable().addTag(newTag, true);
2042 listManager.getTagIndex().add(newTag);
2043 reloadTagTree(true);
2045 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2047 @SuppressWarnings("unused")
2048 private void reloadTagTree() {
2049 reloadTagTree(false);
2051 private void reloadTagTree(boolean reload) {
2052 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2053 tagIndexUpdated(reload);
2054 boolean filter = false;
2056 listManager.countTagResults(listManager.getNoteIndex());
2057 if (notebookTree.selectedItems().size() > 0
2058 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2060 if (tagTree.selectedItems().size() > 0)
2062 tagTree.showAllTags(!filter);
2063 tagIndexUpdated(false);
2064 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2066 // Edit an existing tag
2067 @SuppressWarnings("unused")
2068 private void editTag() {
2069 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2070 TagEdit edit = new TagEdit();
2071 edit.setTitle("Edit Tag");
2072 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2073 QTreeWidgetItem currentSelection;
2074 currentSelection = selections.get(0);
2075 edit.setTag(currentSelection.text(0));
2076 edit.setTagList(listManager.getTagIndex());
2079 if (!edit.okPressed())
2082 String guid = currentSelection.text(2);
2083 currentSelection.setText(0,edit.getTag());
2085 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2086 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2087 listManager.getTagIndex().get(i).setName(edit.getTag());
2088 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2089 updateListTagName(guid);
2090 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2091 browserWindow.setTag(getTagNamesForNote(currentNote));
2092 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2096 browserWindow.setTag(getTagNamesForNote(currentNote));
2097 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2099 // Delete an existing tag
2100 @SuppressWarnings("unused")
2101 private void deleteTag() {
2102 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2104 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2105 QMessageBox.StandardButton.Yes,
2106 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2110 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2111 for (int i=selections.size()-1; i>=0; i--) {
2112 QTreeWidgetItem currentSelection;
2113 currentSelection = selections.get(i);
2114 removeTagItem(currentSelection.text(2));
2116 tagIndexUpdated(true);
2118 listManager.countTagResults(listManager.getNoteIndex());
2119 // tagTree.updateCounts(listManager.getTagCounter());
2120 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2122 // Remove a tag tree item. Go recursively down & remove the children too
2123 private void removeTagItem(String guid) {
2124 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2125 String parent = listManager.getTagIndex().get(j).getParentGuid();
2126 if (parent != null && parent.equals(guid)) {
2127 //Remove this tag's children
2128 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2131 //Now, remove this tag
2132 removeListTagName(guid);
2133 conn.getTagTable().expungeTag(guid, true);
2134 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2135 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2136 listManager.getTagIndex().remove(a);
2141 // Setup the tree containing the user's tags
2142 private void initializeTagTree() {
2143 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2144 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2145 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2146 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2147 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2148 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2150 // Listener when a tag is selected
2151 private void tagTreeSelection() {
2152 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2155 clearAttributeFilter();
2156 clearSavedSearchFilter();
2158 menuBar.noteRestoreAction.setVisible(false);
2160 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2161 QTreeWidgetItem currentSelection;
2162 selectedTagGUIDs.clear();
2163 for (int i=0; i<selections.size(); i++) {
2164 currentSelection = selections.get(i);
2165 selectedTagGUIDs.add(currentSelection.text(2));
2167 if (selections.size() > 0) {
2168 menuBar.tagEditAction.setEnabled(true);
2169 menuBar.tagDeleteAction.setEnabled(true);
2170 menuBar.tagIconAction.setEnabled(true);
2173 menuBar.tagEditAction.setEnabled(false);
2174 menuBar.tagDeleteAction.setEnabled(false);
2175 menuBar.tagIconAction.setEnabled(true);
2177 if (selections.size() > 1)
2178 menuBar.tagMergeAction.setEnabled(true);
2180 menuBar.tagMergeAction.setEnabled(false);
2181 listManager.setSelectedTags(selectedTagGUIDs);
2182 listManager.loadNotesIndex();
2183 noteIndexUpdated(false);
2184 refreshEvernoteNote(true);
2185 listManager.refreshCounters = true;
2186 listManager.refreshCounters();
2187 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2189 // trigger the tag index to be refreshed
2190 @SuppressWarnings("unused")
2191 private void tagIndexUpdated() {
2192 tagIndexUpdated(true);
2194 private void tagIndexUpdated(boolean reload) {
2195 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2196 if (selectedTagGUIDs == null)
2197 selectedTagGUIDs = new ArrayList<String>();
2199 listManager.reloadTagIndex();
2201 tagTree.blockSignals(true);
2203 tagTree.setIcons(conn.getTagTable().getAllIcons());
2204 tagTree.load(listManager.getTagIndex());
2207 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2208 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2210 selectedTagGUIDs.remove(i);
2212 tagTree.blockSignals(false);
2214 browserWindow.setTag(getTagNamesForNote(currentNote));
2215 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2217 // Show/Hide note information
2218 @SuppressWarnings("unused")
2219 private void toggleTagWindow() {
2220 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2221 if (tagTree.isVisible())
2225 menuBar.hideTags.setChecked(tagTree.isVisible());
2226 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2227 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2229 // A note's tags have been updated
2230 @SuppressWarnings("unused")
2231 private void updateNoteTags(String guid, List<String> tags) {
2232 // Save any new tags. We'll need them later.
2233 List<String> newTags = new ArrayList<String>();
2234 for (int i=0; i<tags.size(); i++) {
2235 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2236 newTags.add(tags.get(i));
2239 listManager.saveNoteTags(guid, tags);
2240 listManager.countTagResults(listManager.getNoteIndex());
2241 StringBuffer names = new StringBuffer("");
2242 for (int i=0; i<tags.size(); i++) {
2243 names = names.append(tags.get(i));
2244 if (i<tags.size()-1) {
2245 names.append(Global.tagDelimeter + " ");
2248 browserWindow.setTag(names.toString());
2251 // Now, we need to add any new tags to the tag tree
2252 for (int i=0; i<newTags.size(); i++)
2253 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2255 // Get a string containing all tag names for a note
2256 private String getTagNamesForNote(Note n) {
2257 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2258 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2260 StringBuffer buffer = new StringBuffer(100);
2261 Vector<String> v = new Vector<String>();
2262 List<String> guids = n.getTagGuids();
2267 for (int i=0; i<guids.size(); i++) {
2268 v.add(listManager.getTagNameByGuid(guids.get(i)));
2270 Comparator<String> comparator = Collections.reverseOrder();
2271 Collections.sort(v,comparator);
2272 Collections.reverse(v);
2274 for (int i = 0; i<v.size(); i++) {
2276 buffer.append(", ");
2277 buffer.append(v.get(i));
2280 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2281 return buffer.toString();
2283 // Tags were added via dropping notes from the note list
2284 @SuppressWarnings("unused")
2285 private void tagsAdded(String noteGuid, String tagGuid) {
2286 String tagName = null;
2287 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2288 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2289 tagName = listManager.getTagIndex().get(i).getName();
2290 i=listManager.getTagIndex().size();
2293 if (tagName == null)
2296 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2297 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2298 List<String> tagNames = new ArrayList<String>();
2299 tagNames.add(new String(tagName));
2300 Note n = listManager.getMasterNoteIndex().get(i);
2301 for (int j=0; j<n.getTagNames().size(); j++) {
2302 tagNames.add(new String(n.getTagNames().get(j)));
2304 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2305 if (n.getGuid().equals(currentNoteGuid)) {
2306 Collections.sort(tagNames);
2307 String display = "";
2308 for (int j=0; j<tagNames.size(); j++) {
2309 display = display+tagNames.get(j);
2310 if (j+2<tagNames.size())
2311 display = display+Global.tagDelimeter+" ";
2313 browserWindow.setTag(display);
2315 i=listManager.getMasterNoteIndex().size();
2320 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2322 private void clearTagFilter() {
2323 tagTree.blockSignals(true);
2324 tagTree.clearSelection();
2325 menuBar.noteRestoreAction.setVisible(false);
2326 menuBar.tagEditAction.setEnabled(false);
2327 menuBar.tagMergeAction.setEnabled(false);
2328 menuBar.tagDeleteAction.setEnabled(false);
2329 menuBar.tagIconAction.setEnabled(false);
2330 selectedTagGUIDs.clear();
2331 listManager.setSelectedTags(selectedTagGUIDs);
2332 tagTree.blockSignals(false);
2334 // Change the icon for a tag
2335 @SuppressWarnings("unused")
2336 private void setTagIcon() {
2337 QTreeWidgetItem currentSelection;
2338 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2339 if (selections.size() == 0)
2342 currentSelection = selections.get(0);
2343 String guid = currentSelection.text(2);
2345 QIcon currentIcon = currentSelection.icon(0);
2346 QIcon icon = conn.getTagTable().getIcon(guid);
2349 dialog = new SetIcon(currentIcon, saveLastPath);
2350 dialog.setUseDefaultIcon(true);
2352 dialog = new SetIcon(icon, saveLastPath);
2353 dialog.setUseDefaultIcon(false);
2356 if (dialog.okPressed()) {
2357 saveLastPath = dialog.getPath();
2358 QIcon newIcon = dialog.getIcon();
2359 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2360 if (newIcon == null)
2361 newIcon = new QIcon(iconPath+"tag.png");
2362 currentSelection.setIcon(0, newIcon);
2367 @SuppressWarnings("unused")
2368 private void mergeTags() {
2369 List<Tag> tags = new ArrayList<Tag>();
2370 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2371 for (int i=0; i<selections.size(); i++) {
2372 Tag record = new Tag();
2373 record.setGuid(selections.get(i).text(2));
2374 record.setName(selections.get(i).text(0));
2378 TagMerge mergeDialog = new TagMerge(tags);
2380 if (!mergeDialog.okClicked())
2382 String newGuid = mergeDialog.getNewTagGuid();
2384 for (int i=0; i<tags.size(); i++) {
2385 if (!tags.get(i).getGuid().equals(newGuid)) {
2386 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2387 for (int j=0; j<noteGuids.size(); j++) {
2388 String noteGuid = noteGuids.get(j);
2389 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2390 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2391 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2395 listManager.reloadIndexes();
2398 //***************************************************************
2399 //***************************************************************
2400 //** These functions deal with Saved Search menu items
2401 //***************************************************************
2402 //***************************************************************
2403 // Add a new notebook
2404 @SuppressWarnings("unused")
2405 private void addSavedSearch() {
2406 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2407 SavedSearchEdit edit = new SavedSearchEdit();
2408 edit.setSearchList(listManager.getSavedSearchIndex());
2411 if (!edit.okPressed())
2414 Calendar currentTime = new GregorianCalendar();
2415 Long l = new Long(currentTime.getTimeInMillis());
2416 String randint = new String(Long.toString(l));
2418 SavedSearch search = new SavedSearch();
2419 search.setUpdateSequenceNum(0);
2420 search.setGuid(randint);
2421 search.setName(edit.getName());
2422 search.setQuery(edit.getQuery());
2423 search.setFormat(QueryFormat.USER);
2424 listManager.getSavedSearchIndex().add(search);
2425 conn.getSavedSearchTable().addSavedSearch(search, true);
2426 savedSearchIndexUpdated();
2427 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2429 // Edit an existing tag
2430 @SuppressWarnings("unused")
2431 private void editSavedSearch() {
2432 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2433 SavedSearchEdit edit = new SavedSearchEdit();
2434 edit.setTitle(tr("Edit Search"));
2435 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2436 QTreeWidgetItem currentSelection;
2437 currentSelection = selections.get(0);
2438 String guid = currentSelection.text(1);
2439 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2440 edit.setName(currentSelection.text(0));
2441 edit.setQuery(s.getQuery());
2442 edit.setSearchList(listManager.getSavedSearchIndex());
2445 if (!edit.okPressed())
2448 List<SavedSearch> list = listManager.getSavedSearchIndex();
2449 SavedSearch search = null;
2450 boolean found = false;
2451 for (int i=0; i<list.size(); i++) {
2452 search = list.get(i);
2453 if (search.getGuid().equals(guid)) {
2460 search.setName(edit.getName());
2461 search.setQuery(edit.getQuery());
2462 conn.getSavedSearchTable().updateSavedSearch(search, true);
2463 savedSearchIndexUpdated();
2464 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2466 // Delete an existing tag
2467 @SuppressWarnings("unused")
2468 private void deleteSavedSearch() {
2469 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2471 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2472 QMessageBox.StandardButton.Yes,
2473 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2477 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2478 for (int i=selections.size()-1; i>=0; i--) {
2479 QTreeWidgetItem currentSelection;
2480 currentSelection = selections.get(i);
2481 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2482 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2483 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2484 listManager.getSavedSearchIndex().remove(j);
2485 j=listManager.getSavedSearchIndex().size()+1;
2488 selections.remove(i);
2490 savedSearchIndexUpdated();
2491 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2493 // Setup the tree containing the user's tags
2494 private void initializeSavedSearchTree() {
2495 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2496 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2497 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2499 // Listener when a tag is selected
2500 @SuppressWarnings("unused")
2501 private void savedSearchTreeSelection() {
2502 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2504 clearNotebookFilter();
2507 clearAttributeFilter();
2509 String currentGuid = selectedSavedSearchGUID;
2510 menuBar.savedSearchEditAction.setEnabled(true);
2511 menuBar.savedSearchDeleteAction.setEnabled(true);
2512 menuBar.savedSearchIconAction.setEnabled(true);
2513 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2514 QTreeWidgetItem currentSelection;
2515 selectedSavedSearchGUID = "";
2516 for (int i=0; i<selections.size(); i++) {
2517 currentSelection = selections.get(i);
2518 if (currentSelection.text(1).equals(currentGuid)) {
2519 currentSelection.setSelected(false);
2521 selectedSavedSearchGUID = currentSelection.text(1);
2523 // i = selections.size() +1;
2526 // There is the potential for no notebooks to be selected if this
2527 // happens then we make it look like all notebooks were selecetd.
2528 // If that happens, just select the "all notebooks"
2529 if (selections.size()==0) {
2530 clearSavedSearchFilter();
2532 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2534 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2536 private void clearSavedSearchFilter() {
2537 menuBar.savedSearchEditAction.setEnabled(false);
2538 menuBar.savedSearchDeleteAction.setEnabled(false);
2539 menuBar.savedSearchIconAction.setEnabled(false);
2540 savedSearchTree.blockSignals(true);
2541 savedSearchTree.clearSelection();
2542 savedSearchTree.blockSignals(false);
2543 selectedSavedSearchGUID = "";
2544 searchField.setEditText("");
2545 searchPerformed = false;
2546 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2548 // trigger the tag index to be refreshed
2549 private void savedSearchIndexUpdated() {
2550 if (selectedSavedSearchGUID == null)
2551 selectedSavedSearchGUID = new String();
2552 savedSearchTree.blockSignals(true);
2553 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2554 savedSearchTree.load(listManager.getSavedSearchIndex());
2555 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2556 savedSearchTree.blockSignals(false);
2558 // trigger when the saved search selection changes
2559 @SuppressWarnings("unused")
2560 private void updateSavedSearchSelection() {
2561 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2563 menuBar.savedSearchEditAction.setEnabled(true);
2564 menuBar.savedSearchDeleteAction.setEnabled(true);
2565 menuBar.savedSearchIconAction.setEnabled(true);
2566 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2568 if (selections.size() > 0) {
2569 menuBar.savedSearchEditAction.setEnabled(true);
2570 menuBar.savedSearchDeleteAction.setEnabled(true);
2571 menuBar.savedSearchIconAction.setEnabled(true);
2572 selectedSavedSearchGUID = selections.get(0).text(1);
2573 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2574 searchField.setEditText(s.getQuery());
2576 menuBar.savedSearchEditAction.setEnabled(false);
2577 menuBar.savedSearchDeleteAction.setEnabled(false);
2578 menuBar.savedSearchIconAction.setEnabled(false);
2579 selectedSavedSearchGUID = "";
2580 searchField.setEditText("");
2582 searchFieldChanged();
2584 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2588 // Show/Hide note information
2589 @SuppressWarnings("unused")
2590 private void toggleSavedSearchWindow() {
2591 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2592 if (savedSearchTree.isVisible())
2593 savedSearchTree.hide();
2595 savedSearchTree.show();
2596 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2598 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2599 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2601 // Change the icon for a saved search
2602 @SuppressWarnings("unused")
2603 private void setSavedSearchIcon() {
2604 QTreeWidgetItem currentSelection;
2605 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2606 if (selections.size() == 0)
2609 currentSelection = selections.get(0);
2610 String guid = currentSelection.text(1);
2612 QIcon currentIcon = currentSelection.icon(0);
2613 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2616 dialog = new SetIcon(currentIcon, saveLastPath);
2617 dialog.setUseDefaultIcon(true);
2619 dialog = new SetIcon(icon, saveLastPath);
2620 dialog.setUseDefaultIcon(false);
2623 if (dialog.okPressed()) {
2624 saveLastPath = dialog.getPath();
2625 QIcon newIcon = dialog.getIcon();
2626 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2627 if (newIcon == null)
2628 newIcon = new QIcon(iconPath+"search.png");
2629 currentSelection.setIcon(0, newIcon);
2637 //***************************************************************
2638 //***************************************************************
2639 //** These functions deal with Help menu & tool menu items
2640 //***************************************************************
2641 //***************************************************************
2642 // Show database status
2643 @SuppressWarnings("unused")
2644 private void databaseStatus() {
2646 indexRunner.interrupt = true;
2647 int dirty = conn.getNoteTable().getDirtyCount();
2648 int unindexed = conn.getNoteTable().getUnindexedCount();
2649 DatabaseStatus status = new DatabaseStatus();
2650 status.setUnsynchronized(dirty);
2651 status.setUnindexed(unindexed);
2652 status.setNoteCount(conn.getNoteTable().getNoteCount());
2653 status.setNotebookCount(listManager.getNotebookIndex().size());
2654 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2655 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2656 status.setTagCount(listManager.getTagIndex().size());
2657 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2658 status.setWordCount(conn.getWordsTable().getWordCount());
2662 // Compact the database
2663 @SuppressWarnings("unused")
2664 private void compactDatabase() {
2665 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2666 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2667 "but please be aware that depending upon the size of your database this can be time consuming " +
2668 "and NixNote will be unresponsive until it is complete. Do you wish to continue?"),
2669 QMessageBox.StandardButton.Yes,
2670 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2673 setMessage("Compacting database.");
2675 listManager.compactDatabase();
2677 setMessage("Database compact is complete.");
2678 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2680 @SuppressWarnings("unused")
2681 private void accountInformation() {
2682 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2683 AccountDialog dialog = new AccountDialog();
2685 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2687 @SuppressWarnings("unused")
2688 private void releaseNotes() {
2689 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2690 QDialog dialog = new QDialog(this);
2691 QHBoxLayout layout = new QHBoxLayout();
2692 QTextEdit textBox = new QTextEdit();
2693 layout.addWidget(textBox);
2694 textBox.setReadOnly(true);
2695 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2696 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2697 QIODevice.OpenModeFlag.Text)))
2699 textBox.setText(file.readAll().toString());
2701 dialog.setWindowTitle(tr("Release Notes"));
2702 dialog.setLayout(layout);
2704 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2706 // Called when user picks Log from the help menu
2707 @SuppressWarnings("unused")
2708 private void logger() {
2709 logger.log(logger.HIGH, "Entering NeverNote.logger");
2710 LogFileDialog dialog = new LogFileDialog(emitLog);
2712 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2714 // Menu option "help/about" was selected
2715 @SuppressWarnings("unused")
2716 private void about() {
2717 logger.log(logger.HIGH, "Entering NeverNote.about");
2718 QMessageBox.about(this,
2719 tr("About NixNote"),
2720 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2723 +"Open Source Evernote Client.<br><br>"
2724 +"Licensed under GPL v2. <br><hr><br>"
2725 +"</center>Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2726 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2727 +"PDFRenderer is licened under the LGPL<br>"
2728 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2729 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2730 +"Jazzy is licened under the LGPL<br>"
2731 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2732 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2733 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2734 logger.log(logger.HIGH, "Leaving NeverNote.about");
2736 // Hide the entire left hand side
2737 @SuppressWarnings("unused")
2738 private void toggleLeftSide() {
2741 hidden = !menuBar.hideLeftSide.isChecked();
2742 menuBar.hideLeftSide.setChecked(!hidden);
2745 leftSplitter1.setHidden(true);
2747 leftSplitter1.setHidden(false);
2749 Global.saveWindowVisible("leftPanel", hidden);
2752 public void checkForUpdates() {
2753 // Send off thread to check for a new version
2754 versionChecker = new QNetworkAccessManager(this);
2755 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2756 QNetworkRequest request = new QNetworkRequest();
2757 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2758 versionChecker.get(request);
2760 @SuppressWarnings("unused")
2761 private void upgradeFileRead(QNetworkReply reply) {
2762 if (!reply.isReadable())
2765 String winVersion = Global.version;
2766 String osxVersion = Global.version;
2767 String linuxVersion = Global.version;
2768 String linux64Version = Global.version;
2769 String version = Global.version;
2771 // Determine the versions available
2772 QByteArray data = reply.readLine();
2773 while (data != null && !reply.atEnd()) {
2774 String line = data.toString();
2776 if (line.contains(":"))
2777 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2780 if (line.toLowerCase().contains("windows"))
2781 winVersion = lineVersion;
2782 else if (line.toLowerCase().contains("os-x"))
2783 osxVersion = lineVersion;
2784 else if (line.toLowerCase().contains("linux amd64"))
2785 linux64Version = lineVersion;
2786 else if (line.toLowerCase().contains("linux i386"))
2787 linuxVersion = lineVersion;
2788 else if (line.toLowerCase().contains("default"))
2789 version = lineVersion;
2791 // Read the next line
2792 data = reply.readLine();
2795 // Now we need to determine what system we are on.
2796 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2797 version = winVersion;
2798 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2799 version = osxVersion;
2800 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2801 if (System.getProperty("os.arch").contains("amd64") ||
2802 System.getProperty("os.arch").contains("x86_64"))
2803 version = linux64Version;
2805 version = linuxVersion;
2809 for (String validVersion : Global.validVersions) {
2810 if (version.equals(validVersion))
2814 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2816 if (dialog.remindMe())
2817 Global.setCheckVersionUpgrade(true);
2819 Global.setCheckVersionUpgrade(false);
2823 //***************************************************************
2824 //***************************************************************
2825 //** These functions deal with the Toolbar
2826 //***************************************************************
2827 //***************************************************************
2828 @SuppressWarnings("unused")
2829 private void focusSearch() {
2830 searchField.setFocus();
2833 // Text in the search bar has been cleared
2834 private void searchFieldCleared() {
2837 // This is done because we want to force a reload of
2838 // images. Some images we may want to highlight the text.
2839 readOnlyCache.clear();
2840 inkNoteCache.clear();
2842 QWebSettings.setMaximumPagesInCache(0);
2843 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2845 searchField.setEditText("");
2846 saveNoteColumnPositions();
2847 saveNoteIndexWidth();
2848 noteIndexUpdated(true);
2849 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2850 currentNote = listManager.getNoteIndex().get(0);
2851 currentNoteGuid = currentNote.getGuid();
2853 refreshEvernoteNote(true);
2854 if (currentNote != null)
2855 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2857 // text in the search bar changed. We only use this to tell if it was cleared,
2858 // otherwise we trigger off searchFieldChanged.
2859 @SuppressWarnings("unused")
2860 private void searchFieldTextChanged(String text) {
2861 QWebSettings.setMaximumPagesInCache(0);
2862 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2864 if (text.trim().equals("")) {
2865 searchFieldCleared();
2866 if (searchPerformed) {
2868 // This is done because we want to force a reload of
2869 // images. Some images we may want to highlight the text.
2871 readOnlyCache.clear();
2872 inkNoteCache.clear();
2874 listManager.setEnSearch("");
2875 listManager.loadNotesIndex();
2876 refreshEvernoteNote(true);
2877 noteIndexUpdated(false);
2878 refreshEvernoteNote(true);
2880 searchPerformed = false;
2883 // Text in the toolbar has changed
2884 private void searchFieldChanged() {
2885 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2887 readOnlyCache.clear();
2888 inkNoteCache.clear();
2889 saveNoteColumnPositions();
2890 saveNoteIndexWidth();
2891 String text = searchField.currentText();
2892 listManager.setEnSearch(text.trim());
2893 listManager.loadNotesIndex();
2894 noteIndexUpdated(false);
2895 refreshEvernoteNote(true);
2896 searchPerformed = true;
2897 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2900 // Build the window tool bar
2901 private void setupToolBar() {
2902 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2903 toolBar = addToolBar(tr("Tool Bar"));
2904 toolBar.setObjectName("toolBar");
2905 menuBar.setupToolBarVisible();
2906 if (!Global.isWindowVisible("toolBar"))
2907 toolBar.setVisible(false);
2909 toolBar.setVisible(true);
2911 // toolBar.addWidget(menuBar);
2912 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2913 // toolBar.addSeparator();
2914 prevButton = toolBar.addAction(tr("Previous"));
2915 QIcon prevIcon = new QIcon(iconPath+"back.png");
2916 prevButton.setIcon(prevIcon);
2917 prevButton.triggered.connect(this, "previousViewedAction()");
2918 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2920 nextButton = toolBar.addAction(tr("Next"));
2921 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2922 nextButton.setIcon(nextIcon);
2923 nextButton.triggered.connect(this, "nextViewedAction()");
2924 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2926 upButton = toolBar.addAction(tr("Up"));
2927 QIcon upIcon = new QIcon(iconPath+"up.png");
2928 upButton.setIcon(upIcon);
2929 upButton.triggered.connect(this, "upAction()");
2930 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2933 downButton = toolBar.addAction(tr("Down"));
2934 QIcon downIcon = new QIcon(iconPath+"down.png");
2935 downButton.setIcon(downIcon);
2936 downButton.triggered.connect(this, "downAction()");
2937 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2939 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2940 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2941 synchronizeIconAngle = 0;
2942 synchronizeButton.triggered.connect(this, "evernoteSync()");
2943 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2945 printButton = toolBar.addAction(tr("Print"));
2946 QIcon printIcon = new QIcon(iconPath+"print.png");
2947 printButton.setIcon(printIcon);
2948 printButton.triggered.connect(this, "printNote()");
2949 togglePrintButton(Global.isToolbarButtonVisible("print"));
2951 tagButton = toolBar.addAction(tr("Tag"));
2952 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2953 tagButton.setIcon(tagIcon);
2954 tagButton.triggered.connect(browserWindow, "modifyTags()");
2955 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2957 attributeButton = toolBar.addAction(tr("Attributes"));
2958 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2959 attributeButton.setIcon(attributeIcon);
2960 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2961 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2963 emailButton = toolBar.addAction(tr("Email"));
2964 QIcon emailIcon = new QIcon(iconPath+"email.png");
2965 emailButton.setIcon(emailIcon);
2966 emailButton.triggered.connect(this, "emailNote()");
2967 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2969 deleteButton = toolBar.addAction(tr("Delete"));
2970 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2971 deleteButton.setIcon(deleteIcon);
2972 deleteButton.triggered.connect(this, "deleteNote()");
2973 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2975 newButton = toolBar.addAction(tr("New"));
2976 QIcon newIcon = new QIcon(iconPath+"new.png");
2977 newButton.triggered.connect(this, "addNote()");
2978 newButton.setIcon(newIcon);
2979 toggleNewButton(Global.isToolbarButtonVisible("new"));
2981 allNotesButton = toolBar.addAction(tr("All Notes"));
2982 QIcon allIcon = new QIcon(iconPath+"books.png");
2983 allNotesButton.triggered.connect(this, "allNotes()");
2984 allNotesButton.setIcon(allIcon);
2985 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2987 //toolBar.addSeparator();
2988 //toolBar.addWidget(new QLabel(tr("Quota:")));
2989 //toolBar.addWidget(quotaBar);
2990 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2992 //toolBar.addSeparator();
2994 //toolBar.addWidget(new QLabel(tr("Zoom")));
2995 //toolBar.addWidget(zoomSpinner);
2997 //toolBar.addWidget(new QLabel(" "));
2998 //toolBar.addSeparator();
2999 //toolBar.addWidget(new QLabel(tr(" Search:")));
3000 //toolBar.addWidget(searchField);
3001 QSizePolicy sizePolicy = new QSizePolicy();
3002 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
3003 QLabel spacer = new QLabel("");
3004 spacer.setSizePolicy(sizePolicy);
3005 toolBar.addWidget(spacer);
3006 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3008 //searchClearButton = toolBar.addAction("Search Clear");
3009 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3010 //searchClearButton.setIcon(searchClearIcon);
3011 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3012 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3014 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3016 // Update the sychronize button picture
3018 public QMenu createPopupMenu() {
3019 QMenu contextMenu = super.createPopupMenu();
3021 contextMenu.addSeparator();
3022 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3023 contextMenu.addAction(prevAction);
3024 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3026 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3027 contextMenu.addAction(nextAction);
3028 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3030 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3031 contextMenu.addAction(upAction);
3032 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3034 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3035 contextMenu.addAction(downAction);
3036 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3038 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3039 contextMenu.addAction(synchronizeAction);
3040 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3042 QAction printAction = addContextAction("print", tr("Print"));
3043 contextMenu.addAction(printAction);
3044 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3046 QAction tagAction = addContextAction("tag", tr("Tag"));
3047 contextMenu.addAction(tagAction);
3048 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3050 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3051 contextMenu.addAction(attributeAction);
3052 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3054 QAction emailAction = addContextAction("email", tr("Email"));
3055 contextMenu.addAction(emailAction);
3056 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3058 QAction deleteAction = addContextAction("delete", tr("Delete"));
3059 contextMenu.addAction(deleteAction);
3060 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3062 QAction newAction = addContextAction("new", tr("Add"));
3063 contextMenu.addAction(newAction);
3064 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3066 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3067 contextMenu.addAction(allNotesAction);
3068 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3070 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3071 contextMenu.addAction(searchClearAction);
3072 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3077 private QAction addContextAction(String config, String name) {
3078 QAction newAction = new QAction(this);
3079 newAction.setText(name);
3080 newAction.setCheckable(true);
3081 newAction.setChecked(Global.isToolbarButtonVisible(config));
3084 private void togglePrevArrowButton(Boolean toggle) {
3085 prevButton.setVisible(toggle);
3086 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3088 private void toggleNextArrowButton(Boolean toggle) {
3089 nextButton.setVisible(toggle);
3090 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3092 private void toggleUpArrowButton(Boolean toggle) {
3093 upButton.setVisible(toggle);
3094 Global.saveToolbarButtonsVisible("upArrow", toggle);
3096 private void toggleDownArrowButton(Boolean toggle) {
3097 downButton.setVisible(toggle);
3098 Global.saveToolbarButtonsVisible("downArrow", toggle);
3100 private void toggleSynchronizeButton(Boolean toggle) {
3101 synchronizeButton.setVisible(toggle);
3102 Global.saveToolbarButtonsVisible("synchronize", toggle);
3104 private void togglePrintButton(Boolean toggle) {
3105 printButton.setVisible(toggle);
3106 Global.saveToolbarButtonsVisible("print", toggle);
3108 private void toggleTagButton(Boolean toggle) {
3109 tagButton.setVisible(toggle);
3110 Global.saveToolbarButtonsVisible("tag", toggle);
3112 private void toggleAttributeButton(Boolean toggle) {
3113 attributeButton.setVisible(toggle);
3114 Global.saveToolbarButtonsVisible("attribute", toggle);
3116 private void toggleEmailButton(Boolean toggle) {
3117 emailButton.setVisible(toggle);
3118 Global.saveToolbarButtonsVisible("email", toggle);
3120 private void toggleDeleteButton(Boolean toggle) {
3121 deleteButton.setVisible(toggle);
3122 Global.saveToolbarButtonsVisible("delete", toggle);
3124 private void toggleNewButton(Boolean toggle) {
3125 newButton.setVisible(toggle);
3126 Global.saveToolbarButtonsVisible("new", toggle);
3128 private void toggleAllNotesButton(Boolean toggle) {
3129 allNotesButton.setVisible(toggle);
3130 Global.saveToolbarButtonsVisible("allNotes", toggle);
3132 @SuppressWarnings("unused")
3133 private void toggleSearchClearButton(Boolean toggle) {
3134 searchClearButton.setVisible(toggle);
3135 Global.saveToolbarButtonsVisible("searchClear", toggle);
3142 @SuppressWarnings("unused")
3143 private void updateSyncButton() {
3145 if (syncIcons == null) {
3146 syncIcons = new ArrayList<QPixmap>();
3148 synchronizeIconAngle = 0;
3149 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3151 for (int i=0; i<=360; i++) {
3152 QPixmap rotatedPix = new QPixmap(pix.size());
3153 QPainter p = new QPainter(rotatedPix);
3154 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3155 QSize size = pix.size();
3156 p.translate(size.width()/2, size.height()/2);
3159 p.setBackgroundMode(BGMode.OpaqueMode);
3160 p.translate(-size.width()/2, -size.height()/2);
3161 p.drawPixmap(0,0, pix);
3163 syncIcons.add(rotatedPix);
3167 synchronizeIconAngle++;
3168 if (synchronizeIconAngle > 359)
3169 synchronizeIconAngle=0;
3170 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3173 // Synchronize with Evernote
3175 private void evernoteSync() {
3176 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3177 if (!Global.isConnected)
3179 if (Global.isConnected)
3180 synchronizeAnimationTimer.start(5);
3181 // synchronizeAnimationTimer.start(200);
3183 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3185 private void updateQuotaBar() {
3186 long limit = Global.getUploadLimit();
3187 long amount = Global.getUploadAmount();
3188 if (amount>0 && limit>0) {
3189 int percent =(int)(amount*100/limit);
3190 quotaBar.setValue(percent);
3192 quotaBar.setValue(0);
3195 @SuppressWarnings("unused")
3196 private void zoomChanged() {
3197 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3200 //****************************************************************
3201 //****************************************************************
3202 //* System Tray functions
3203 //****************************************************************
3204 //****************************************************************
3205 private void trayToggleVisible() {
3210 if (windowMaximized)
3217 @SuppressWarnings("unused")
3218 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3219 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3220 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3221 trayToggleVisible();
3226 //***************************************************************
3227 //***************************************************************
3228 //** These functions deal with the trash tree
3229 //***************************************************************
3230 //***************************************************************
3231 // Setup the tree containing the trash.
3232 @SuppressWarnings("unused")
3233 private void trashTreeSelection() {
3234 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3236 clearNotebookFilter();
3238 clearAttributeFilter();
3239 clearSavedSearchFilter();
3241 String tempGuid = currentNoteGuid;
3243 // currentNoteGuid = "";
3244 currentNote = new Note();
3245 selectedNoteGUIDs.clear();
3246 listManager.getSelectedNotebooks().clear();
3247 listManager.getSelectedTags().clear();
3248 listManager.setSelectedSavedSearch("");
3249 browserWindow.clear();
3251 // toggle the add buttons
3252 newButton.setEnabled(!newButton.isEnabled());
3253 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3254 menuBar.noteAdd.setVisible(true);
3256 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3257 if (selections.size() == 0) {
3258 currentNoteGuid = trashNoteGuid;
3259 trashNoteGuid = tempGuid;
3260 Global.showDeleted = false;
3261 menuBar.noteRestoreAction.setEnabled(false);
3262 menuBar.noteRestoreAction.setVisible(false);
3265 currentNoteGuid = trashNoteGuid;
3266 trashNoteGuid = tempGuid;
3267 menuBar.noteRestoreAction.setEnabled(true);
3268 menuBar.noteRestoreAction.setVisible(true);
3269 Global.showDeleted = true;
3271 listManager.loadNotesIndex();
3272 noteIndexUpdated(false);
3273 //// browserWindow.setEnabled(newButton.isEnabled());
3274 browserWindow.setReadOnly(!newButton.isEnabled());
3275 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3277 // Empty the trash file
3278 @SuppressWarnings("unused")
3279 private void emptyTrash() {
3280 // browserWindow.clear();
3281 logger.log(logger.EXTREME, "Emptying Trash");
3282 listManager.emptyTrash();
3283 logger.log(logger.EXTREME, "Resetting view after trash empty");
3284 if (trashTree.selectedItems().size() > 0) {
3285 listManager.getSelectedNotebooks().clear();
3286 listManager.getSelectedTags().clear();
3287 listManager.setSelectedSavedSearch("");
3288 newButton.setEnabled(!newButton.isEnabled());
3289 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3290 menuBar.noteAdd.setVisible(true);
3291 browserWindow.clear();
3294 clearNotebookFilter();
3295 clearSavedSearchFilter();
3296 clearAttributeFilter();
3298 Global.showDeleted = false;
3299 menuBar.noteRestoreAction.setEnabled(false);
3300 menuBar.noteRestoreAction.setVisible(false);
3302 listManager.loadNotesIndex();
3303 noteIndexUpdated(false);
3306 // Show/Hide trash window
3307 @SuppressWarnings("unused")
3308 private void toggleTrashWindow() {
3309 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3310 if (trashTree.isVisible())
3314 menuBar.hideTrash.setChecked(trashTree.isVisible());
3316 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3317 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3319 private void clearTrashFilter() {
3320 Global.showDeleted = false;
3321 newButton.setEnabled(true);
3322 menuBar.noteAdd.setEnabled(true);
3323 menuBar.noteAdd.setVisible(true);
3324 trashTree.blockSignals(true);
3325 trashTree.clearSelection();
3326 trashTree.blockSignals(false);
3331 //***************************************************************
3332 //***************************************************************
3333 //** These functions deal with connection settings
3334 //***************************************************************
3335 //***************************************************************
3336 // SyncRunner had a problem and things are disconnected
3337 @SuppressWarnings("unused")
3338 private void remoteErrorDisconnect() {
3339 menuBar.connectAction.setText(tr("Connect"));
3340 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3341 menuBar.synchronizeAction.setEnabled(false);
3342 Global.isConnected = false;
3343 synchronizeAnimationTimer.stop();
3346 // Do a manual connect/disconnect
3347 private void remoteConnect() {
3348 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3350 if (Global.isConnected) {
3351 Global.isConnected = false;
3352 syncRunner.enDisconnect();
3353 setupConnectMenuOptions();
3358 AESEncrypter aes = new AESEncrypter();
3360 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3361 } catch (FileNotFoundException e) {
3362 // File not found, so we'll just get empty strings anyway.
3365 if (Global.getProxyValue("url").equals("")) {
3366 System.setProperty("http.proxyHost","") ;
3367 System.setProperty("http.proxyPort", "") ;
3368 System.setProperty("https.proxyHost","") ;
3369 System.setProperty("https.proxyPort", "") ;
3372 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3373 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3374 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3375 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3377 if (Global.getProxyValue("userid").equals("")) {
3378 Authenticator.setDefault(new Authenticator() {
3380 protected PasswordAuthentication getPasswordAuthentication() {
3382 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3388 syncRunner.userStoreUrl = Global.userStoreUrl;
3389 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3390 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3392 String userid = aes.getUserid();
3393 String password = aes.getPassword();
3394 if (!userid.equals("") && !password.equals("")) {
3395 Global.username = userid;
3396 Global.password = password;
3397 syncRunner.username = Global.username;
3398 syncRunner.password = Global.password;
3399 syncRunner.enConnect();
3402 Global.isConnected = syncRunner.isConnected;
3404 if (!Global.isConnected) {
3405 // Show the login dialog box
3406 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3407 LoginDialog login = new LoginDialog();
3410 if (!login.okPressed()) {
3414 Global.username = login.getUserid();
3415 Global.password = login.getPassword();
3417 syncRunner.username = Global.username;
3418 syncRunner.password = Global.password;
3419 syncRunner.enConnect();
3420 Global.isConnected = syncRunner.isConnected;
3423 if (!Global.isConnected)
3426 setupConnectMenuOptions();
3427 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3429 private void setupConnectMenuOptions() {
3430 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3431 if (!Global.isConnected) {
3432 menuBar.connectAction.setText(tr("Connect"));
3433 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3434 menuBar.synchronizeAction.setEnabled(false);
3436 menuBar.connectAction.setText(tr("Disconnect"));
3437 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3438 menuBar.synchronizeAction.setEnabled(true);
3440 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3445 //***************************************************************
3446 //***************************************************************
3447 //** These functions deal with the GUI Attribute tree
3448 //***************************************************************
3449 //***************************************************************
3450 @SuppressWarnings("unused")
3451 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3453 // clearTagFilter();
3454 // clearNotebookFilter();
3456 // clearSavedSearchFilter();
3458 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3459 if (item.childCount() > 0) {
3460 item.setSelected(false);
3462 Global.createdBeforeFilter.reset();
3463 Global.createdSinceFilter.reset();
3464 Global.changedBeforeFilter.reset();
3465 Global.changedSinceFilter.reset();
3466 Global.containsFilter.reset();
3467 attributeTreeSelected = item;
3468 DateAttributeFilterTable f = null;
3469 f = findDateAttributeFilterTable(item.parent());
3471 f.select(item.parent().indexOfChild(item));
3473 Global.containsFilter.select(item.parent().indexOfChild(item));
3476 listManager.loadNotesIndex();
3477 noteIndexUpdated(false);
3480 attributeTreeSelected = null;
3481 item.setSelected(false);
3482 Global.createdBeforeFilter.reset();
3483 Global.createdSinceFilter.reset();
3484 Global.changedBeforeFilter.reset();
3485 Global.changedSinceFilter.reset();
3486 Global.containsFilter.reset();
3487 listManager.loadNotesIndex();
3488 noteIndexUpdated(false);
3490 // This determines what attribute filter we need, depending upon the selection
3491 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3492 if (w.parent() != null && w.childCount() > 0) {
3493 QTreeWidgetItem parent = w.parent();
3494 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3495 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3496 return Global.createdSinceFilter;
3497 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3498 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3499 return Global.createdBeforeFilter;
3500 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3501 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3502 return Global.changedSinceFilter;
3503 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3504 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3505 return Global.changedBeforeFilter;
3510 // Show/Hide attribute search window
3511 @SuppressWarnings("unused")
3512 private void toggleAttributesWindow() {
3513 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3514 if (attributeTree.isVisible())
3515 attributeTree.hide();
3517 attributeTree.show();
3518 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3520 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3521 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3523 private void clearAttributeFilter() {
3524 Global.createdBeforeFilter.reset();
3525 Global.createdSinceFilter.reset();
3526 Global.changedBeforeFilter.reset();
3527 Global.changedSinceFilter.reset();
3528 Global.containsFilter.reset();
3529 attributeTreeSelected = null;
3530 attributeTree.blockSignals(true);
3531 attributeTree.clearSelection();
3532 attributeTree.blockSignals(false);
3536 //***************************************************************
3537 //***************************************************************
3538 //** These functions deal with the GUI Note index table
3539 //***************************************************************
3540 //***************************************************************
3541 // Initialize the note list table
3542 private void initializeNoteTable() {
3543 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3544 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3545 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3546 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3548 // Show/Hide trash window
3549 @SuppressWarnings("unused")
3550 private void toggleNoteListWindow() {
3551 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3552 if (noteTableView.isVisible())
3553 noteTableView.hide();
3555 noteTableView.show();
3556 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3558 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3559 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3561 // Handle the event that a user selects a note from the table
3562 @SuppressWarnings("unused")
3563 private void noteTableSelection() {
3564 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3568 // If we have more than one selection, then set the merge note action to true.
3569 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3570 if (selections.size() > 1)
3571 menuBar.noteMergeAction.setEnabled(true);
3573 menuBar.noteMergeAction.setEnabled(false);
3575 // If the ctrl key is pressed, then they are selecting multiple
3576 // entries and we don't want to change the currently viewed note.
3577 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3578 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3581 if (historyGuids.size() == 0) {
3582 historyGuids.add(currentNoteGuid);
3583 historyPosition = 1;
3585 noteTableView.showColumn(Global.noteTableGuidPosition);
3587 if (!Global.isColumnVisible("guid"))
3588 noteTableView.hideColumn(Global.noteTableGuidPosition);
3590 if (selections.size() > 0) {
3592 menuBar.noteDuplicateAction.setEnabled(true);
3593 menuBar.noteOnlineHistoryAction.setEnabled(true);
3594 menuBar.noteMergeAction.setEnabled(true);
3595 selectedNoteGUIDs.clear();
3596 if (selections.size() != 1 || Global.showDeleted) {
3597 menuBar.noteDuplicateAction.setEnabled(false);
3599 if (selections.size() != 1 || !Global.isConnected) {
3600 menuBar.noteOnlineHistoryAction.setEnabled(false);
3602 if (selections.size() == 1) {
3603 menuBar.noteMergeAction.setEnabled(false);
3605 for (int i=0; i<selections.size(); i++) {
3606 int row = selections.get(i).row();
3608 upButton.setEnabled(false);
3610 upButton.setEnabled(true);
3611 if (row < listManager.getNoteTableModel().rowCount()-1)
3612 downButton.setEnabled(true);
3614 downButton.setEnabled(false);
3615 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3616 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3617 currentNoteGuid = (String)ix.values().toArray()[0];
3618 selectedNoteGUIDs.add(currentNoteGuid);
3622 nextButton.setEnabled(true);
3623 prevButton.setEnabled(true);
3625 int endPosition = historyGuids.size()-1;
3626 for (int j=historyPosition; j<=endPosition; j++) {
3627 historyGuids.remove(historyGuids.size()-1);
3629 historyGuids.add(currentNoteGuid);
3630 historyPosition = historyGuids.size();
3632 if (historyPosition <= 1)
3633 prevButton.setEnabled(false);
3634 if (historyPosition == historyGuids.size())
3635 nextButton.setEnabled(false);
3637 fromHistory = false;
3638 scrollToGuid(currentNoteGuid);
3639 refreshEvernoteNote(true);
3640 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3642 // Trigger a refresh when the note db has been updated
3643 private void noteIndexUpdated(boolean reload) {
3644 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3646 refreshEvernoteNoteList();
3647 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3648 noteTableView.load(reload);
3649 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3651 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3652 pos = noteTableView.proxyModel.rowCount();
3655 if (noteTableView.proxyModel.rowCount() == 0)
3658 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3660 currentNoteGuid = (String)i.data();
3664 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3666 scrollToGuid(currentNoteGuid);
3667 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3669 // Called when the list of notes is updated
3670 private void refreshEvernoteNoteList() {
3671 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3672 browserWindow.setDisabled(false);
3673 if (selectedNoteGUIDs == null)
3674 selectedNoteGUIDs = new ArrayList<String>();
3675 selectedNoteGUIDs.clear(); // clear out old entries
3677 String saveCurrentNoteGuid = new String();
3678 String tempNoteGuid = new String();
3680 historyGuids.clear();
3681 historyPosition = 0;
3682 prevButton.setEnabled(false);
3683 nextButton.setEnabled(false);
3685 if (currentNoteGuid == null)
3686 currentNoteGuid = new String();
3688 //determine current note guid
3689 for (Note note : listManager.getNoteIndex()) {
3690 tempNoteGuid = note.getGuid();
3691 if (currentNoteGuid.equals(tempNoteGuid)) {
3692 saveCurrentNoteGuid = tempNoteGuid;
3696 if (listManager.getNoteIndex().size() == 0) {
3697 currentNoteGuid = "";
3699 browserWindow.clear();
3700 browserWindow.setDisabled(true);
3703 if (!saveCurrentNoteGuid.equals("")) {
3704 refreshEvernoteNote(false);
3706 currentNoteGuid = "";
3708 reloadTagTree(false);
3710 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3712 // Called when the previous arrow button is clicked
3713 @SuppressWarnings("unused")
3714 private void previousViewedAction() {
3715 if (!prevButton.isEnabled())
3717 if (historyPosition == 0)
3720 if (historyPosition <= 0)
3722 String historyGuid = historyGuids.get(historyPosition-1);
3724 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3725 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3726 if (modelIndex != null) {
3727 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3728 String tableGuid = (String)ix.values().toArray()[0];
3729 if (tableGuid.equals(historyGuid)) {
3730 noteTableView.selectRow(i);
3736 @SuppressWarnings("unused")
3737 private void nextViewedAction() {
3738 if (!nextButton.isEnabled())
3740 String historyGuid = historyGuids.get(historyPosition);
3743 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3744 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3745 if (modelIndex != null) {
3746 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3747 String tableGuid = (String)ix.values().toArray()[0];
3748 if (tableGuid.equals(historyGuid)) {
3749 noteTableView.selectRow(i);
3755 // Called when the up arrow is clicked
3756 @SuppressWarnings("unused")
3757 private void upAction() {
3758 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3759 int row = selections.get(0).row();
3761 noteTableView.selectRow(row-1);
3764 // Called when the down arrow is clicked
3765 @SuppressWarnings("unused")
3766 private void downAction() {
3767 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3768 int row = selections.get(0).row();
3769 int max = listManager.getNoteTableModel().rowCount();
3771 noteTableView.selectRow(row+1);
3774 // Update a tag string for a specific note in the list
3775 @SuppressWarnings("unused")
3776 private void updateListTags(String guid, List<String> tags) {
3777 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3778 StringBuffer tagBuffer = new StringBuffer();
3779 for (int i=0; i<tags.size(); i++) {
3780 tagBuffer.append(tags.get(i));
3781 if (i<tags.size()-1)
3782 tagBuffer.append(", ");
3785 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3786 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3787 if (modelIndex != null) {
3788 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3789 String tableGuid = (String)ix.values().toArray()[0];
3790 if (tableGuid.equals(guid)) {
3791 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3792 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3793 noteTableView.proxyModel.invalidate();
3798 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3800 // Update a title for a specific note in the list
3801 @SuppressWarnings("unused")
3802 private void updateListAuthor(String guid, String author) {
3803 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3805 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3806 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3807 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3808 if (modelIndex != null) {
3809 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3810 String tableGuid = (String)ix.values().toArray()[0];
3811 if (tableGuid.equals(guid)) {
3812 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3813 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3814 noteTableView.proxyModel.invalidate();
3820 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3822 private void updateListNoteNotebook(String guid, String notebook) {
3823 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3824 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3825 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3827 // Update a title for a specific note in the list
3828 @SuppressWarnings("unused")
3829 private void updateListSourceUrl(String guid, String url) {
3830 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3832 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3833 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3834 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3835 if (modelIndex != null) {
3836 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3837 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3838 String tableGuid = (String)ix.values().toArray()[0];
3839 if (tableGuid.equals(guid)) {
3840 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3841 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3842 noteTableView.proxyModel.invalidate();
3847 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3849 @SuppressWarnings("unused")
3850 private void updateListGuid(String oldGuid, String newGuid) {
3851 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3853 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3854 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3855 if (modelIndex != null) {
3856 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3857 String tableGuid = (String)ix.values().toArray()[0];
3858 if (tableGuid.equals(oldGuid)) {
3859 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3860 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3865 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3867 private void updateListTagName(String guid) {
3868 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3870 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3871 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3872 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3874 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3875 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3876 if (modelIndex != null) {
3877 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3878 String noteGuid = (String)ix.values().toArray()[0];
3879 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3880 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3881 i=listManager.getNoteTableModel().rowCount();
3887 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3889 private void removeListTagName(String guid) {
3890 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3892 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3893 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3894 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3895 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3896 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3899 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3900 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3901 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3902 if (modelIndex != null) {
3903 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3904 String noteGuid = (String)ix.values().toArray()[0];
3905 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3906 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3907 i=listManager.getNoteTableModel().rowCount();
3913 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3915 private void updateListNotebookName(String oldName, String newName) {
3916 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3918 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3919 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3920 if (modelIndex != null) {
3921 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3922 String tableName = (String)ix.values().toArray()[0];
3923 if (tableName.equalsIgnoreCase(oldName)) {
3924 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3928 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3930 @SuppressWarnings("unused")
3931 private void updateListDateCreated(String guid, QDateTime date) {
3932 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3934 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3935 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3936 if (modelIndex != null) {
3937 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3938 String tableGuid = (String)ix.values().toArray()[0];
3939 if (tableGuid.equals(guid)) {
3940 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3941 noteTableView.proxyModel.invalidate();
3946 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3948 @SuppressWarnings("unused")
3949 private void updateListDateSubject(String guid, QDateTime date) {
3950 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3952 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3953 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3954 if (modelIndex != null) {
3955 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3956 String tableGuid = (String)ix.values().toArray()[0];
3957 if (tableGuid.equals(guid)) {
3958 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3959 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3960 noteTableView.proxyModel.invalidate();
3965 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3967 private void updateListDateChanged(String guid, QDateTime date) {
3968 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3970 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3971 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3972 if (modelIndex != null) {
3973 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3974 String tableGuid = (String)ix.values().toArray()[0];
3975 if (tableGuid.equals(guid)) {
3976 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3977 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3982 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3984 private void updateListDateChanged() {
3985 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3986 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3987 updateListDateChanged(currentNoteGuid, date);
3988 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3991 private void scrollToCurrentGuid() {
3992 //scrollToGuid(currentNoteGuid);
3993 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3994 if (selections.size() == 0)
3996 QModelIndex index = selections.get(0);
3997 int row = selections.get(0).row();
3998 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
4001 // Scroll to the current GUID in tthe list.
4002 // Scroll to a particular index item
4003 private void scrollToGuid(String guid) {
4004 if (currentNote == null || guid == null)
4006 if (currentNote.isActive() && Global.showDeleted) {
4007 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4008 if (!listManager.getNoteIndex().get(i).isActive()) {
4009 currentNote = listManager.getNoteIndex().get(i);
4010 currentNoteGuid = currentNote.getGuid();
4011 i = listManager.getNoteIndex().size();
4015 if (!currentNote.isActive() && !Global.showDeleted) {
4016 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4017 if (listManager.getNoteIndex().get(i).isActive()) {
4018 currentNote = listManager.getNoteIndex().get(i);
4019 currentNoteGuid = currentNote.getGuid();
4020 i = listManager.getNoteIndex().size();
4025 for (int i=0; i<noteTableView.model().rowCount(); i++) {
4026 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4027 if (currentNoteGuid.equals(index.data())) {
4028 // noteTableView.selectionModel().blockSignals(true);
4029 noteTableView.selectRow(i);
4030 // noteTableView.selectionModel().blockSignals(false);
4031 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
4032 i=listManager.getNoteTableModel().rowCount();
4035 noteTableView.repaint();
4037 // Show/Hide columns
4038 private void showColumns() {
4039 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4040 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4041 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4042 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4043 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4044 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4045 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4046 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4047 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4048 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4049 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4050 noteTableView.setColumnHidden(Global.noteTablePinnedPosition, !Global.isColumnVisible("pinned"));
4052 // Title color has changed
4053 @SuppressWarnings("unused")
4054 private void titleColorChanged(Integer color) {
4055 logger.log(logger.HIGH, "Entering NeverNote.titleColorChanged");
4058 QColor backgroundColor = new QColor();
4059 QColor foregroundColor = new QColor(QColor.black);
4060 backgroundColor.setRgb(color);
4062 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4063 foregroundColor.setRgb(QColor.white.rgb());
4065 if (selectedNoteGUIDs.size() == 0)
4066 selectedNoteGUIDs.add(currentNoteGuid);
4068 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4069 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4070 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4071 if (modelIndex != null) {
4072 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4073 String tableGuid = (String)ix.values().toArray()[0];
4074 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4075 for (int k=0; k<Global.noteTableColumnCount; k++) {
4076 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4077 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4078 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4080 i=listManager.getNoteTableModel().rowCount();
4085 logger.log(logger.HIGH, "Leaving NeverNote.titleColorChanged");
4087 // A note has been pinned or unpinned
4088 @SuppressWarnings("unused")
4089 private void notePinned() {
4090 logger.log(logger.EXTREME, "Entering NeverNote.notePinned()");
4093 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4094 NoteMetadata meta = listManager.getNoteMetadata().get(selectedNoteGUIDs.get(j));
4095 boolean pinned = !meta.isPinned();
4096 meta.setPinned(pinned); // Toggle the pinned/unpinned
4098 // Update the list & table
4099 listManager.updateNoteMetadata(meta);
4100 noteTableView.proxyModel.addGuid(selectedNoteGUIDs.get(j), meta);
4103 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4105 // Wide list was chosen
4106 public void narrowListView() {
4107 saveNoteColumnPositions();
4108 saveNoteIndexWidth();
4110 int sortCol = noteTableView.proxyModel.sortColumn();
4111 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4112 Global.setSortColumn(sortCol);
4113 Global.setSortOrder(sortOrder);
4115 Global.setListView(Global.View_List_Narrow);
4117 menuBar.wideListView.blockSignals(true);
4118 menuBar.narrowListView.blockSignals(true);
4120 menuBar.wideListView.setChecked(false);
4121 menuBar.narrowListView.setChecked(true);
4123 menuBar.wideListView.blockSignals(false);
4124 menuBar.narrowListView.blockSignals(false);
4126 mainLeftRightSplitter.addWidget(noteTableView);
4127 mainLeftRightSplitter.addWidget(browserWindow);
4128 restoreWindowState(false);
4129 noteTableView.repositionColumns();
4130 noteTableView.resizeColumnWidths();
4131 noteTableView.resizeRowHeights();
4133 sortCol = Global.getSortColumn();
4134 sortOrder = Global.getSortOrder();
4135 noteTableView.proxyModel.blocked = true;
4136 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4137 noteTableView.proxyModel.blocked = false;
4141 noteTableView.load(false);
4142 refreshEvernoteNote(true);
4143 scrollToCurrentGuid();
4145 public void wideListView() {
4146 int sortCol = noteTableView.proxyModel.sortColumn();
4147 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4148 Global.setSortColumn(sortCol);
4149 Global.setSortOrder(sortOrder);
4152 saveNoteColumnPositions();
4153 saveNoteIndexWidth();
4154 Global.setListView(Global.View_List_Wide);
4156 menuBar.wideListView.blockSignals(true);
4157 menuBar.narrowListView.blockSignals(true);
4159 menuBar.wideListView.setChecked(true);
4160 menuBar.narrowListView.setChecked(false);
4162 menuBar.wideListView.blockSignals(false);
4163 menuBar.narrowListView.blockSignals(false);
4164 browserIndexSplitter.setVisible(true);
4165 browserIndexSplitter.addWidget(noteTableView);
4166 browserIndexSplitter.addWidget(browserWindow);
4167 restoreWindowState(false);
4168 noteTableView.repositionColumns();
4169 noteTableView.resizeColumnWidths();
4170 noteTableView.resizeRowHeights();
4172 sortCol = Global.getSortColumn();
4173 sortOrder = Global.getSortOrder();
4174 noteTableView.proxyModel.blocked = true;
4175 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4176 noteTableView.proxyModel.blocked = false;
4179 noteTableView.load(false);
4180 scrollToCurrentGuid();
4182 // Sort order for the notebook has changed
4183 public void tableSortOrderChanged(Integer column, Integer order) {
4185 // Find what notebook (if any) is selected. We ignore stacks & the "All Notebooks".
4186 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4187 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4188 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4190 notebook = currentSelectedNotebook.text(2);
4191 conn.getNotebookTable().setSortOrder(notebook, column, order);
4195 //***************************************************************
4196 @SuppressWarnings("unused")
4197 private void evernoteLinkClick(String syncGuid, String locGuid) {
4199 if (conn.getNoteTable().guidExists(syncGuid)) {
4202 // If we didn't find it via the synchronized guid, look under the local guid
4203 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4204 // later synchronized (that causes the guid to change so we need to find the new one).
4205 if (conn.getNoteTable().guidExists(locGuid))
4208 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4211 openExternalEditor(guid);
4215 //If we've gotten this far, we can't find the note
4216 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4217 " seem to find that note."));
4219 //***************************************************************
4220 //***************************************************************
4221 //** External editor window functions
4222 //***************************************************************
4223 //***************************************************************
4224 private void listDoubleClick() {
4226 openExternalEditor(currentNoteGuid);
4228 private void openExternalEditor(String guid) {
4230 if (externalWindows.containsKey(guid)) {
4231 externalWindows.get(guid).raise();
4234 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4235 // We have a new external editor to create
4236 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4237 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4238 newBrowser.setWindowIcon(appIcon);
4239 externalWindows.put(guid, newBrowser);
4240 showEditorButtons(newBrowser.getBrowserWindow());
4241 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4242 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4243 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4244 //newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4245 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4246 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4247 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4248 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4250 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4251 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4252 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4256 @SuppressWarnings({ "rawtypes", "unused" })
4257 private void externalWindowTagsEdited(String guid, List values) {
4258 StringBuffer line = new StringBuffer(100);
4259 for (int i=0; i<values.size(); i++) {
4261 line.append(Global.tagDelimeter+" ");
4262 line.append(values.get(i));
4264 if (guid.equals(currentNoteGuid)) {
4265 browserWindow.setTag(line.toString());
4268 @SuppressWarnings("unused")
4269 private void externalWindowClosing(String guid) {
4270 externalWindows.remove(guid);
4275 //***************************************************************
4276 //***************************************************************
4277 //** These functions deal with Note specific things
4278 //***************************************************************
4279 //***************************************************************
4280 private void setNoteDirty() {
4281 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4283 // Find if the note is being edited externally. If it is, update it.
4284 if (externalWindows.containsKey(currentNoteGuid)) {
4285 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4286 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4287 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4288 window.getBrowserWindow().setContent(unicode);
4291 // If the note is dirty, then it is unsynchronized by default.
4295 // Set the note as dirty and check if its status is synchronized in the display table
4297 if (listManager.getNoteMetadata().containsKey(currentNoteGuid) &&
4298 listManager.getNoteMetadata().get(currentNoteGuid).isDirty()) {
4302 // If this wasn't already marked as unsynchronized, then we need to update the table
4303 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4304 // listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4305 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4306 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4307 if (modelIndex != null) {
4308 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4309 String tableGuid = (String)ix.values().toArray()[0];
4310 if (tableGuid.equals(currentNoteGuid)) {
4311 listManager.getNoteTableModel().proxyModel.setData(i, Global.noteTableSynchronizedPosition, "false");
4317 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4319 @SuppressWarnings("unused")
4320 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4321 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4322 QByteArray unicode = codec.fromUnicode(content);
4323 noteCache.remove(guid);
4324 noteCache.put(guid, unicode.toString());
4325 if (guid.equals(currentNoteGuid)) {
4327 browserWindow.setContent(unicode);
4330 thumbnailRunner.addWork("GENERATE "+ guid);
4331 saveNote(guid, browser);
4335 private void saveNote() {
4337 saveNote(currentNoteGuid, browserWindow);
4338 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4342 private void saveNote(String guid, BrowserWindow window) {
4343 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4346 logger.log(logger.EXTREME, "Saving to cache");
4347 QTextCodec codec = QTextCodec.codecForLocale();
4348 // QTextDecoder decoder = codec.makeDecoder();
4349 codec = QTextCodec.codecForName("UTF-8");
4350 QByteArray unicode = codec.fromUnicode(window.getContent());
4351 noteCache.put(guid, unicode.toString());
4353 logger.log(logger.EXTREME, "updating list manager");
4354 listManager.updateNoteContent(guid, window.getContent());
4355 logger.log(logger.EXTREME, "Updating title");
4356 listManager.updateNoteTitle(guid, window.getTitle());
4357 updateListDateChanged();
4359 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4360 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4361 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4362 currentNote = listManager.getNoteIndex().get(i);
4363 i = listManager.getNoteIndex().size();
4368 // Get a note from Evernote (and put it in the browser)
4369 private void refreshEvernoteNote(boolean reload) {
4370 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4372 if (Global.disableViewing) {
4373 browserWindow.setEnabled(false);
4378 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4380 Global.cryptCounter =0;
4382 browserWindow.setReadOnly(true);
4390 browserWindow.loadingData(true);
4392 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4393 if (currentNote == null)
4395 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4398 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4399 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4400 formatter.setNote(note, Global.pdfPreview());
4401 formatter.setHighlight(listManager.getEnSearch());
4403 if (!noteCache.containsKey(guid)) {
4404 js = new QByteArray();
4405 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4406 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4407 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>");
4408 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4409 js.append("<style> img { max-width:100%; }</style>");
4410 if (Global.displayRightToLeft())
4411 js.append("<style> body { direction:rtl; }</style>");
4412 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4413 js.append("</head>");
4414 formatter.setNote(note, Global.pdfPreview());
4415 js.append(formatter.rebuildNoteHTML());
4416 js.append("</HTML>");
4417 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4418 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4419 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4420 // if (Global.enableHTMLEntitiesFix) {
4421 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4423 browser.setContent(js);
4424 noteCache.put(guid, js.toString());
4426 if (formatter.resourceError)
4427 resourceErrorMessage();
4428 if (formatter.formatError) {
4430 QMessageBox.information(this, tr("Error"),
4431 tr("NixNote had issues formatting this note." +
4432 " To protect your data this note is being marked as read-only."));
4435 readOnly = formatter.readOnly;
4436 inkNote = formatter.inkNote;
4438 readOnlyCache.put(guid, true);
4440 inkNoteCache.put(guid, true);
4442 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4443 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4444 js = new QByteArray(cachedContent);
4445 browser.setContent(js);
4446 if (readOnlyCache.containsKey(guid))
4448 if (inkNoteCache.containsKey(guid))
4451 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4452 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4454 if (readOnly || inkNote)
4455 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4457 browser.getBrowser().page().setContentEditable(true);
4458 browser.setReadOnly(readOnly);
4459 deleteButton.setEnabled(!readOnly);
4460 tagButton.setEnabled(!readOnly);
4461 menuBar.noteDelete.setEnabled(!readOnly);
4462 menuBar.noteTags.setEnabled(!readOnly);
4463 browser.setNote(note);
4465 if (note != null && note.getNotebookGuid() != null &&
4466 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4467 deleteButton.setEnabled(false);
4468 menuBar.notebookDeleteAction.setEnabled(false);
4470 deleteButton.setEnabled(true);
4471 menuBar.notebookDeleteAction.setEnabled(true);
4474 // Build a list of non-closed notebooks
4475 List<Notebook> nbooks = new ArrayList<Notebook>();
4476 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4477 boolean found=false;
4478 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4479 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4483 nbooks.add(listManager.getNotebookIndex().get(i));
4486 browser.setTitle(note.getTitle());
4487 browser.setTag(getTagNamesForNote(note));
4488 browser.setAuthor(note.getAttributes().getAuthor());
4490 browser.setAltered(note.getUpdated());
4491 browser.setCreation(note.getCreated());
4492 if (note.getAttributes().getSubjectDate() > 0)
4493 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4495 browser.setSubjectDate(note.getCreated());
4496 browser.setUrl(note.getAttributes().getSourceURL());
4498 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4499 List<Tag> tagList = tagFilter.getValidTags(note);
4500 browser.setAllTags(tagList);
4502 browser.setCurrentTags(note.getTagNames());
4506 browser.loadingData(false);
4507 if (thumbnailViewer.isActiveWindow())
4510 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4511 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4514 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4516 // Save a generated thumbnail
4517 private void toggleNoteInformation() {
4518 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4519 browserWindow.toggleInformation();
4520 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4521 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4522 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4524 // Listener triggered when a print button is pressed
4525 @SuppressWarnings("unused")
4526 private void printNote() {
4527 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4529 QPrintDialog dialog = new QPrintDialog();
4530 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4531 QPrinter printer = dialog.printer();
4532 browserWindow.getBrowser().print(printer);
4534 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4537 // Listener triggered when the email button is pressed
4538 @SuppressWarnings("unused")
4539 private void emailNote() {
4540 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4542 if (Desktop.isDesktopSupported()) {
4543 Desktop desktop = Desktop.getDesktop();
4545 String text2 = browserWindow.getContentsToEmail();
4546 QUrl url = new QUrl("mailto:");
4547 url.addQueryItem("subject", currentNote.getTitle());
4548 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4549 url.addQueryItem("body", text2);
4550 QDesktopServices.openUrl(url);
4554 if (desktop.isSupported(Desktop.Action.MAIL)) {
4555 URI uriMailTo = null;
4557 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4558 String text = browserWindow.getContentsToEmail();
4559 //text = "<b>" +text +"</b>";
4560 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4561 +"&BODY=" +text, null);
4562 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4563 +"&ATTACHMENT=d:/test.pdf", null);
4564 desktop.mail(uriMailTo);
4565 } catch (URISyntaxException e) {
4566 e.printStackTrace();
4567 } catch (IOException e) {
4568 e.printStackTrace();
4575 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4577 // Reindex all notes
4578 @SuppressWarnings("unused")
4579 private void fullReindex() {
4580 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4581 indexRunner.addWork("REINDEXALL");
4582 setMessage(tr("Database will be reindexed."));
4583 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4585 // Listener when a user wants to reindex a specific note
4586 @SuppressWarnings("unused")
4587 private void reindexNote() {
4588 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4589 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4590 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4592 if (selectedNotebookGUIDs.size() > 1)
4593 setMessage(tr("Notes will be reindexed."));
4595 setMessage(tr("Note will be reindexed."));
4596 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4599 @SuppressWarnings("unused")
4600 private void deleteNote() {
4601 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4602 if (currentNote == null)
4604 if (currentNoteGuid.equals(""))
4606 String title = null;
4607 if (selectedNoteGUIDs.size() == 1)
4608 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4610 // If we are deleting non-trash notes
4611 if (currentNote.isActive()) {
4612 if (Global.verifyDelete()) {
4614 if (selectedNoteGUIDs.size() > 1) {
4615 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4618 msg = new String(tr("Delete note \"") +title +"\"?");
4620 msg = new String(tr("Delete note selected note?"));
4622 if (QMessageBox.question(this, tr("Confirmation"), msg,
4623 QMessageBox.StandardButton.Yes,
4624 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4628 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4629 selectedNoteGUIDs.add(currentNoteGuid);
4630 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4631 listManager.deleteNote(selectedNoteGUIDs.get(i));
4634 // If we are deleting from the trash.
4635 if (Global.verifyDelete()) {
4637 if (selectedNoteGUIDs.size() > 1) {
4638 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4641 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4643 msg = new String(tr("Permanently delete note selected note?"));
4645 if (QMessageBox.question(this, "Confirmation", msg,
4646 QMessageBox.StandardButton.Yes,
4647 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4651 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4652 selectedNoteGUIDs.add(currentNoteGuid);
4653 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4654 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4655 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4656 if (modelIndex != null) {
4657 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4658 String tableGuid = (String)ix.values().toArray()[0];
4659 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4660 listManager.getNoteTableModel().removeRow(j);
4665 listManager.expungeNote(selectedNoteGUIDs.get(i));
4668 currentNoteGuid = "";
4669 listManager.loadNotesIndex();
4670 noteIndexUpdated(false);
4671 refreshEvernoteNote(true);
4672 scrollToGuid(currentNoteGuid);
4673 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4676 @SuppressWarnings("unused")
4677 private void addNote() {
4678 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4679 // browserWindow.setEnabled(true);
4680 browserWindow.setReadOnly(false);
4682 Calendar currentTime = new GregorianCalendar();
4683 StringBuffer noteString = new StringBuffer(100);
4684 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4685 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4688 if (Global.overrideDefaultFont()) {
4689 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4690 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4691 noteString.append("<br clear=\"none\" />\n");
4692 noteString.append("</span>\n</font>\n");
4694 noteString.append("<br clear=\"none\" />\n");
4695 noteString.append("</en-note>");
4697 Long l = new Long(currentTime.getTimeInMillis());
4698 String randint = new String(Long.toString(l));
4700 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4702 // for the first non-archived notebook. Finally, if nothing else we
4703 // pick the first notebook in the list.
4704 String notebook = null;
4705 listManager.getNotebookIndex().get(0).getGuid();
4706 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4707 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4708 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4709 notebook = currentSelectedNotebook.text(2);
4711 boolean found = false;
4712 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4713 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4714 boolean match = false;
4715 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4716 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4718 j = listManager.getArchiveNotebookIndex().size();
4722 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4723 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4725 // Now we have a list of good notebooks, so we can look for the default
4727 for (int i=0; i<goodNotebooks.size(); i++) {
4728 if (goodNotebooks.get(i).isDefaultNotebook()) {
4729 notebook = goodNotebooks.get(i).getGuid();
4731 i = goodNotebooks.size();
4735 if (goodNotebooks.size() > 0 && !found)
4736 notebook = goodNotebooks.get(0).getGuid();
4739 notebook = listManager.getNotebookIndex().get(0).getGuid();
4742 Note newNote = new Note();
4743 newNote.setUpdateSequenceNum(0);
4744 newNote.setGuid(randint);
4745 newNote.setNotebookGuid(notebook);
4746 newNote.setTitle("Untitled Note");
4747 newNote.setContent(noteString.toString());
4748 newNote.setDeleted(0);
4749 newNote.setCreated(System.currentTimeMillis());
4750 newNote.setUpdated(System.currentTimeMillis());
4751 newNote.setActive(true);
4752 NoteAttributes na = new NoteAttributes();
4753 na.setLatitude(0.0);
4754 na.setLongitude(0.0);
4755 na.setAltitude(0.0);
4756 newNote.setAttributes(new NoteAttributes());
4757 newNote.setTagGuids(new ArrayList<String>());
4758 newNote.setTagNames(new ArrayList<String>());
4760 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4761 if (Global.newNoteWithSelectedTags()) {
4762 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4763 QTreeWidgetItem currentSelection;
4764 for (int i=0; i<selections.size(); i++) {
4765 currentSelection = selections.get(i);
4766 newNote.getTagGuids().add(currentSelection.text(2));
4767 newNote.getTagNames().add(currentSelection.text(0));
4771 conn.getNoteTable().addNote(newNote, true);
4772 NoteMetadata metadata = new NoteMetadata();
4773 metadata.setGuid(newNote.getGuid());
4774 metadata.setDirty(true);
4775 listManager.addNote(newNote, metadata);
4776 // noteTableView.insertRow(newNote, true, -1);
4778 currentNote = newNote;
4779 currentNoteGuid = currentNote.getGuid();
4780 noteTableView.clearSelection();
4781 refreshEvernoteNote(true);
4782 listManager.countNotebookResults(listManager.getNoteIndex());
4783 browserWindow.titleLabel.setFocus();
4784 browserWindow.titleLabel.selectAll();
4785 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4787 // If the window is hidden, then we want to popup this in an external window &
4791 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4793 // Restore a note from the trash;
4794 @SuppressWarnings("unused")
4795 private void restoreNote() {
4797 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4798 selectedNoteGUIDs.add(currentNoteGuid);
4799 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4800 listManager.restoreNote(selectedNoteGUIDs.get(i));
4802 currentNoteGuid = "";
4803 listManager.loadNotesIndex();
4804 noteIndexUpdated(false);
4807 // Search a note for specific txt
4808 @SuppressWarnings("unused")
4809 private void findText() {
4811 find.setFocusOnTextField();
4813 @SuppressWarnings("unused")
4814 private void doFindText() {
4815 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4818 @SuppressWarnings("unused")
4819 private void updateNoteTitle(String guid, String title) {
4820 listManager.setNoteSynchronized(guid, false);
4822 // Signal received that note content has changed. Normally we just need the guid to remove
4823 // it from the cache.
4824 @SuppressWarnings("unused")
4825 private void invalidateNoteCache(String guid, String content) {
4826 noteCache.remove(guid);
4827 refreshEvernoteNote(true);
4829 // Signal received that a note guid has changed
4830 @SuppressWarnings("unused")
4831 private void noteGuidChanged(String oldGuid, String newGuid) {
4832 if (noteCache.containsKey(oldGuid)) {
4833 if (!oldGuid.equals(currentNoteGuid)) {
4834 String cache = noteCache.get(oldGuid);
4835 noteCache.put(newGuid, cache);
4836 noteCache.remove(oldGuid);
4838 noteCache.remove(oldGuid);
4839 noteCache.put(newGuid, browserWindow.getContent());
4843 listManager.updateNoteGuid(oldGuid, newGuid, false);
4844 if (currentNoteGuid.equals(oldGuid)) {
4845 if (currentNote != null)
4846 currentNote.setGuid(newGuid);
4847 currentNoteGuid = newGuid;
4850 if (externalWindows.containsKey(oldGuid)) {
4851 ExternalBrowse b = externalWindows.get(oldGuid);
4852 externalWindows.remove(oldGuid);
4853 b.getBrowserWindow().getNote().setGuid(newGuid);
4854 externalWindows.put(newGuid, b);
4857 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4858 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4859 noteTableView.proxyModel.addGuid(newGuid, listManager.getNoteMetadata().get(newGuid));
4860 i=listManager.getNoteIndex().size();
4864 if (listManager.getNoteTableModel().metaData.containsKey(oldGuid)) {
4865 NoteMetadata meta = listManager.getNoteTableModel().metaData.get(oldGuid);
4866 listManager.getNoteTableModel().metaData.put(newGuid, meta);
4867 listManager.getNoteTableModel().metaData.remove(oldGuid);
4871 // Toggle the note editor button bar
4872 private void toggleEditorButtonBar() {
4873 if (browserWindow.buttonsVisible) {
4874 browserWindow.hideButtons();
4875 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4876 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4878 browserWindow.buttonsVisible = true;
4879 showEditorButtons(browserWindow);
4881 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4883 // Show editor buttons
4884 private void showEditorButtons(BrowserWindow browser) {
4885 browser.buttonLayout.setVisible(true);
4886 browser.undoAction.setVisible(false);
4888 browser.undoButton.setVisible(false);
4890 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4891 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4892 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4893 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4894 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4895 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4896 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4897 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4898 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4899 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4900 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4901 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4902 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4903 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4904 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4905 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4906 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4907 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4908 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4909 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4910 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4911 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4912 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4914 private void duplicateNote(String guid) {
4916 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4917 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4918 oldNote.setContent(conn.getNoteTable().getNoteContentNoUTFConversion(guid));
4919 oldNote.setResources(resList);
4920 duplicateNote(oldNote);
4922 private void duplicateNote(Note oldNote) {
4924 // Now that we have a good notebook guid, we need to move the conflicting note
4925 // to the local notebook
4926 Calendar currentTime = new GregorianCalendar();
4927 Long l = new Long(currentTime.getTimeInMillis());
4928 String newGuid = new String(Long.toString(l));
4930 // Note newNote = oldNote.deepCopy();
4931 Note newNote = (Note)Global.deepCopy(oldNote);
4932 newNote.setUpdateSequenceNum(0);
4933 newNote.setGuid(newGuid);
4934 newNote.setDeleted(0);
4935 newNote.setActive(true);
4938 List<String> tagNames = new ArrayList<String>();
4939 List<String> tagGuids = new ArrayList<String>();;
4940 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4941 tagNames.add(oldNote.getTagNames().get(i));
4942 tagGuids.add(oldNote.getTagGuids().get(i));
4945 // Sort note Tags to make them look nice
4946 for (int i=0; i<tagNames.size()-1; i++) {
4947 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4948 String n1 = tagNames.get(i);
4949 String n2 = tagNames.get(i+1);
4950 tagNames.set(i, n2);
4951 tagNames.set(i+1, n1);
4954 newNote.setTagGuids(tagGuids);
4955 newNote.setTagNames(tagNames);
4957 // Add tag guids to note
4960 // Duplicate resources
4961 List<Resource> resList = oldNote.getResources();
4962 if (resList == null)
4963 resList = new ArrayList<Resource>();
4965 for (int i=0; i<resList.size(); i++) {
4967 while (l == prevGuid) {
4968 currentTime = new GregorianCalendar();
4969 l = new Long(currentTime.getTimeInMillis());
4972 String newResGuid = new String(Long.toString(l));
4973 resList.get(i).setNoteGuid(newGuid);
4974 resList.get(i).setGuid(newResGuid);
4975 resList.get(i).setUpdateSequenceNum(0);
4976 resList.get(i).setActive(true);
4977 conn.getNoteTable().noteResourceTable.saveNoteResource(
4978 (Resource)Global.deepCopy(resList.get(i)), true);
4980 newNote.setResources(resList);
4982 // Add note to the database
4983 conn.getNoteTable().addNote(newNote, true);
4984 NoteMetadata metaData = new NoteMetadata();
4985 NoteMetadata oldMeta = listManager.getNoteMetadata().get(oldNote.getGuid());
4986 metaData.copy(oldMeta);
4987 metaData.setGuid(newNote.getGuid());
4988 listManager.addNote(newNote, metaData);
4989 noteTableView.insertRow(newNote, metaData, true, -1);
4990 currentNoteGuid = newNote.getGuid();
4991 currentNote = newNote;
4992 refreshEvernoteNote(true);
4993 listManager.countNotebookResults(listManager.getNoteIndex());
4997 @SuppressWarnings("unused")
4998 private void allNotes() {
4999 clearAttributeFilter();
5000 clearNotebookFilter();
5001 clearSavedSearchFilter();
5004 searchField.clear();
5005 if (Global.mimicEvernoteInterface) {
5006 notebookTree.selectGuid("");
5008 notebookTreeSelection();
5009 refreshEvernoteNote(true);
5012 @SuppressWarnings("unused")
5013 private void mergeNotes() {
5014 logger.log(logger.HIGH, "Merging notes");
5017 String masterGuid = null;
5018 List<String> sources = new ArrayList<String>();
5020 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
5021 int r = noteTableView.selectionModel().selectedRows().get(i).row();
5022 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
5023 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5025 masterGuid = (String)ix.values().toArray()[0];
5027 sources.add((String)ix.values().toArray()[0]);
5030 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
5031 logger.log(logger.EXTREME, "Children count: "+sources.size());
5032 mergeNoteContents(masterGuid, sources);
5033 currentNoteGuid = masterGuid;
5034 noteIndexUpdated(false);
5035 refreshEvernoteNote(true);
5038 private void mergeNoteContents(String targetGuid, List<String> sources) {
5039 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
5040 String newContent = target.getContent();
5041 newContent = newContent.replace("</en-note>", "<br></br>");
5043 for (int i=0; i<sources.size(); i++) {
5044 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
5045 if (source.isSetTitle()) {
5046 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
5048 String sourceContent = source.getContent();
5049 logger.log(logger.EXTREME, "Merging contents into note");
5050 logger.log(logger.EXTREME, sourceContent);
5051 logger.log(logger.EXTREME, "End of content");
5052 int startOfNote = sourceContent.indexOf("<en-note>");
5053 sourceContent = sourceContent.substring(startOfNote+9);
5054 int endOfNote = sourceContent.indexOf("</en-note>");
5055 sourceContent = sourceContent.substring(0,endOfNote);
5056 newContent = newContent + sourceContent;
5057 logger.log(logger.EXTREME, "New note content");
5058 logger.log(logger.EXTREME, newContent);
5059 logger.log(logger.EXTREME, "End of content");
5060 for (int j=0; j<source.getResourcesSize(); j++) {
5061 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
5062 Resource r = source.getResources().get(j);
5063 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
5065 Calendar currentTime = new GregorianCalendar();
5066 Long l = new Long(currentTime.getTimeInMillis());
5070 while (l == prevGuid) {
5071 currentTime = new GregorianCalendar();
5072 l = new Long(currentTime.getTimeInMillis());
5074 String newResGuid = new String(Long.toString(l));
5075 newRes.setNoteGuid(targetGuid);
5076 newRes.setGuid(newResGuid);
5077 newRes.setUpdateSequenceNum(0);
5078 newRes.setActive(true);
5079 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5082 logger.log(logger.EXTREME, "Updating note");
5083 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5084 for (int i=0; i<sources.size(); i++) {
5085 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5086 listManager.deleteNote(sources.get(i));
5088 logger.log(logger.EXTREME, "Exiting merge note");
5090 // A resource within a note has had a guid change
5091 @SuppressWarnings("unused")
5092 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5093 if (oldGuid != null && !oldGuid.equals(newGuid))
5094 Global.resourceMap.put(oldGuid, newGuid);
5096 // View a thumbnail of the note
5097 public void thumbnailView() {
5099 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5100 QFile thumbnail = new QFile(thumbnailName);
5101 if (!thumbnail.exists()) {
5103 QImage img = new QImage();
5104 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5105 thumbnailViewer.setThumbnail(img);
5107 thumbnailViewer.setThumbnail(thumbnailName);
5108 if (!thumbnailViewer.isVisible())
5109 thumbnailViewer.showFullScreen();
5111 // An error happened while saving a note. Inform the user
5112 @SuppressWarnings("unused")
5113 private void saveRunnerError(String guid, String msg) {
5115 String title = "*Unknown*";
5116 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5117 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5118 title = listManager.getMasterNoteIndex().get(i).getTitle();
5119 i=listManager.getMasterNoteIndex().size();
5122 msg = tr("An error has happened while saving the note \"") +title+
5123 tr("\".\n\nThis is probably due to a document that is too complex for NixNote to process. "+
5124 "As a result, changes to the note may not be saved properly in the database."+
5125 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5126 "\nbe lost. Please review the note to recover any critical data before restarting.");
5128 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5131 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5132 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5133 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5134 // Find an idle preview object
5135 for (int i=0; i<thumbGenerators.size(); i++) {
5136 if (thumbGenerators.get(i).mutex.tryLock()) {
5137 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5138 thumbGenerators.get(i).loadContent(guid, html, zoom);
5142 if (thumbGenerators.size() >= 1) {
5143 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5147 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5148 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5149 thumbGenerators.add(preview);
5151 if (preview.mutex.tryLock()) {
5152 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5153 preview.loadContent(guid, html, zoom);
5155 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5160 //**********************************************************
5161 //**********************************************************
5162 //* Online user actions
5163 //**********************************************************
5164 //**********************************************************
5165 private void setupOnlineMenu() {
5166 if (!Global.isConnected) {
5167 menuBar.noteOnlineHistoryAction.setEnabled(false);
5168 menuBar.selectiveSyncAction.setEnabled(false);
5171 menuBar.noteOnlineHistoryAction.setEnabled(true);
5172 menuBar.selectiveSyncAction.setEnabled(true);
5175 @SuppressWarnings("unused")
5176 private void viewNoteHistory() {
5177 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5179 if (currentNote.getUpdateSequenceNum() == 0) {
5180 setMessage(tr("Note has never been synchronized."));
5181 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5185 setMessage(tr("Getting Note History"));
5187 Note currentOnlineNote = null;
5190 if (Global.isPremium())
5191 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5193 versions = new ArrayList<NoteVersionId>();
5194 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5195 } catch (EDAMUserException e) {
5196 setMessage("EDAMUserException: " +e.getMessage());
5198 } catch (EDAMSystemException e) {
5199 setMessage("EDAMSystemException: " +e.getMessage());
5201 } catch (EDAMNotFoundException e) {
5202 setMessage(tr("Note not found on server."));
5203 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5205 } catch (TException e) {
5206 setMessage("EDAMTransactionException: " +e.getMessage());
5210 // If we've gotten this far, we have a good note.
5211 if (historyWindow == null) {
5212 historyWindow = new OnlineNoteHistory(logger, conn);
5213 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5214 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5215 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5217 historyWindow.historyCombo.clear();
5219 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5220 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5222 historyWindow.setCurrent(isDirty);
5224 loadHistoryWindowContent(currentOnlineNote);
5225 historyWindow.load(versions);
5226 setMessage(tr("History retrieved"));
5228 historyWindow.exec();
5230 private Note reloadHistoryWindow(String selection) {
5232 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5233 String dateTimeFormat = new String(fmt);
5234 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5238 for (int i=0; i<versions.size(); i++) {
5239 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5240 if (versionDate.toString().equals(selection))
5244 if (index > -1 || selection.indexOf("Current") > -1) {
5245 Note historyNote = null;
5248 usn = versions.get(index).getUpdateSequenceNum();
5249 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5251 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5252 } catch (EDAMUserException e) {
5253 setMessage("EDAMUserException: " +e.getMessage());
5256 } catch (EDAMSystemException e) {
5257 setMessage("EDAMSystemException: " +e.getMessage());
5260 } catch (EDAMNotFoundException e) {
5261 setMessage("EDAMNotFoundException: " +e.getMessage());
5264 } catch (TException e) {
5265 setMessage("EDAMTransactionException: " +e.getMessage());
5271 if (historyNote != null)
5272 historyWindow.setContent(historyNote);
5278 private void loadHistoryWindowContent(Note note) {
5279 note.setUpdateSequenceNum(0);
5280 historyWindow.setContent(note);
5282 @SuppressWarnings("unused")
5283 private void restoreHistoryNoteAsNew() {
5284 setMessage(tr("Restoring as new note."));
5285 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5286 setMessage(tr("Note has been restored as a new note."));
5288 @SuppressWarnings("unused")
5289 private void restoreHistoryNote() {
5290 setMessage(tr("Restoring note."));
5291 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5292 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5295 for (int i=0; i<n.getResourcesSize(); i++) {
5296 n.getResources().get(i).setActive(true);
5297 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5299 NoteMetadata metadata = new NoteMetadata();
5300 metadata.setGuid(n.getGuid());
5301 listManager.addNote(n, metadata);
5302 conn.getNoteTable().addNote(n, true);
5303 refreshEvernoteNote(true);
5304 setMessage(tr("Note has been restored."));
5306 @SuppressWarnings("unused")
5307 private void setupSelectiveSync() {
5309 // Get a list of valid notebooks
5310 List<Notebook> notebooks = null;
5311 List<Tag> tags = null;
5312 List<LinkedNotebook> linkedNotebooks = null;
5314 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5315 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5316 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5317 } catch (EDAMUserException e) {
5318 setMessage("EDAMUserException: " +e.getMessage());
5320 } catch (EDAMSystemException e) {
5321 setMessage("EDAMSystemException: " +e.getMessage());
5323 } catch (TException e) {
5324 setMessage("EDAMTransactionException: " +e.getMessage());
5326 } catch (EDAMNotFoundException e) {
5327 setMessage("EDAMNotFoundException: " +e.getMessage());
5331 // Split up notebooks into synchronized & non-synchronized
5332 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5333 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5335 for (int i=notebooks.size()-1; i>=0; i--) {
5336 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5337 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5338 ignoredBooks.add(notebooks.get(i));
5339 j=dbIgnoredNotebooks.size();
5344 // split up tags into synchronized & non-synchronized
5345 List<Tag> ignoredTags = new ArrayList<Tag>();
5346 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5348 for (int i=tags.size()-1; i>=0; i--) {
5349 for (int j=0; j<dbIgnoredTags.size(); j++) {
5350 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5351 ignoredTags.add(tags.get(i));
5352 j=dbIgnoredTags.size();
5357 // split up linked notebooks into synchronized & non-synchronized
5358 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5359 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5360 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5361 String notebookGuid = linkedNotebooks.get(i).getGuid();
5362 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5363 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5364 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5365 j=dbIgnoredLinkedNotebooks.size();
5370 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5372 if (!ignore.okClicked())
5377 // Clear out old notebooks & add the new ones
5378 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5379 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5380 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5383 List<String> newNotebooks = new ArrayList<String>();
5384 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5385 String text = ignore.getIgnoredBookList().takeItem(i).text();
5386 for (int j=0; j<notebooks.size(); j++) {
5387 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5388 Notebook n = notebooks.get(j);
5389 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5391 newNotebooks.add(n.getGuid());
5396 // Clear out old tags & add new ones
5397 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5398 for (int i=0; i<oldIgnoreTags.size(); i++) {
5399 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5402 List<String> newTags = new ArrayList<String>();
5403 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5404 String text = ignore.getIgnoredTagList().takeItem(i).text();
5405 for (int j=0; j<tags.size(); j++) {
5406 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5407 Tag t = tags.get(j);
5408 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5409 newTags.add(t.getGuid());
5415 // Clear out old tags & add new ones
5416 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5417 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5418 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5421 List<String> newLinked = new ArrayList<String>();
5422 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5423 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5424 for (int j=0; j<linkedNotebooks.size(); j++) {
5425 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5426 LinkedNotebook t = linkedNotebooks.get(j);
5427 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5428 newLinked.add(t.getGuid());
5429 j=linkedNotebooks.size();
5434 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5440 //**********************************************************
5441 //**********************************************************
5442 //* XML Modifying methods
5443 //**********************************************************
5444 //**********************************************************
5445 // An error has happended fetching a resource. let the user know
5446 private void resourceErrorMessage() {
5450 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5451 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5452 "In a perfect world this wouldn't happen, but it has.\n" +
5453 "It is embarasing when a program like me, designed to save all your\n"+
5454 "precious data, has a problem finding data.\n\n" +
5455 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5456 "In the mean time, I'm not going to let you make changes to this note.\n" +
5457 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5458 "this note on the Evernote servers. Sorry."+
5459 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5461 browserWindow.setReadOnly(true);
5468 //**********************************************************
5469 //**********************************************************
5471 //**********************************************************
5472 //**********************************************************
5473 // We should now do a sync with Evernote
5474 private void syncTimer() {
5475 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5476 syncRunner.syncNeeded = true;
5477 syncRunner.disableUploads = Global.disableUploads;
5479 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5481 private void syncStart() {
5482 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5484 if (!syncRunning && Global.isConnected) {
5485 syncRunner.setConnected(true);
5486 syncRunner.setKeepRunning(Global.keepRunning);
5487 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5489 if (syncThreadsReady > 0) {
5490 thumbnailRunner.interrupt = true;
5491 saveNoteIndexWidth();
5492 saveNoteColumnPositions();
5493 if (syncRunner.addWork("SYNC")) {
5495 syncRunner.syncNeeded = true;
5500 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5502 @SuppressWarnings("unused")
5503 private void syncThreadComplete(Boolean refreshNeeded) {
5504 setMessage(tr("Finalizing Synchronization"));
5506 syncRunning = false;
5507 syncRunner.syncNeeded = false;
5508 synchronizeAnimationTimer.stop();
5509 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5511 if (currentNote == null) {
5512 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5514 listManager.refreshNoteMetadata();
5515 noteIndexUpdated(true);
5516 noteTableView.selectionModel().blockSignals(true);
5517 scrollToGuid(currentNoteGuid);
5518 noteTableView.selectionModel().blockSignals(false);
5519 refreshEvernoteNote(false);
5520 scrollToGuid(currentNoteGuid);
5523 // Check to see if there were any shared notebook errors
5524 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5525 String guid = syncRunner.errorSharedNotebooks.get(0);
5526 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5527 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5528 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5530 if (syncDialog.okPressed()) {
5531 if (syncDialog.doNothing.isChecked()) {
5532 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5535 if (syncDialog.deleteNotebook.isChecked()) {
5536 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5537 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5538 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5539 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5547 // Finalize the synchronization
5548 if (!syncRunner.error)
5549 setMessage(tr("Synchronization Complete"));
5551 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5552 logger.log(logger.MEDIUM, "Sync complete.");
5554 public void saveUploadAmount(long t) {
5555 Global.saveUploadAmount(t);
5557 public void saveUserInformation(User user) {
5558 Global.saveUserInformation(user);
5560 public void saveEvernoteUpdateCount(int i) {
5561 Global.saveEvernoteUpdateCount(i);
5563 public void refreshLists() {
5564 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5566 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5567 tagIndexUpdated(true);
5568 notebookIndexUpdated();
5569 savedSearchIndexUpdated();
5570 listManager.loadNotesIndex();
5572 noteTableView.selectionModel().blockSignals(true);
5573 noteIndexUpdated(true);
5574 noteTableView.selectionModel().blockSignals(false);
5575 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5579 @SuppressWarnings("unused")
5580 private void authTimer() {
5581 Calendar cal = Calendar.getInstance();
5583 // If we are not connected let's get out of here
5584 if (!Global.isConnected)
5587 // If this is the first time through, then we need to set this
5588 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5589 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5591 // long now = new Date().getTime();
5592 // if (now > Global.authRefreshTime && Global.isConnected) {
5593 syncRunner.authRefreshNeeded = true;
5597 @SuppressWarnings("unused")
5598 private void authRefreshComplete(boolean goodSync) {
5599 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5600 Global.isConnected = syncRunner.isConnected;
5602 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5603 authTimer.start(1000*60*15);
5604 logger.log(logger.LOW, "Authentication token has been renewed");
5605 // setMessage("Authentication token has been renewed.");
5607 authTimer.start(1000*60*5);
5608 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5609 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5611 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5615 @SuppressWarnings("unused")
5616 private synchronized void indexTimer() {
5617 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5620 if (!indexDisabled && indexRunner.idle) {
5621 thumbnailRunner.interrupt = true;
5622 indexRunner.addWork("SCAN");
5624 logger.log(logger.EXTREME, "Leaving NixNote index timer");
5627 @SuppressWarnings("unused")
5628 private void indexStarted() {
5629 setMessage(tr("Indexing notes"));
5631 @SuppressWarnings("unused")
5632 private void indexComplete() {
5633 setMessage(tr("Index complete"));
5635 @SuppressWarnings("unused")
5636 private synchronized void toggleNoteIndexing() {
5637 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5638 indexDisabled = !indexDisabled;
5640 setMessage(tr("Indexing is now enabled."));
5642 setMessage(tr("Indexing is now disabled."));
5643 menuBar.disableIndexing.setChecked(indexDisabled);
5644 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5647 @SuppressWarnings("unused")
5648 private void threadMonitorCheck() {
5653 alive = listManager.threadCheck(Global.tagCounterThreadId);
5656 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5657 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died. I recommend "+
5658 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5659 disableTagThreadCheck = true;
5664 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5666 notebookThreadDeadCount++;
5667 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5668 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died. I recommend "+
5669 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5670 disableNotebookThreadCheck=true;
5673 notebookThreadDeadCount=0;
5675 alive = listManager.threadCheck(Global.trashCounterThreadId);
5678 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5679 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died. I recommend "+
5680 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5681 disableTrashThreadCheck = true;
5686 alive = listManager.threadCheck(Global.saveThreadId);
5688 saveThreadDeadCount++;
5689 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5690 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died. I recommend "+
5691 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5692 disableSaveThreadCheck = true;
5695 saveThreadDeadCount=0;
5697 if (!syncThread.isAlive()) {
5698 syncThreadDeadCount++;
5699 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5700 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died. I recommend "+
5701 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5702 disableSyncThreadCheck = true;
5705 syncThreadDeadCount=0;
5707 if (!indexThread.isAlive()) {
5708 indexThreadDeadCount++;
5709 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5710 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died. I recommend "+
5711 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5712 disableIndexThreadCheck = true;
5715 indexThreadDeadCount=0;
5720 private void thumbnailTimer() {
5721 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5722 thumbnailRunner.addWork("SCAN");
5726 //**************************************************
5727 //* Backup & Restore
5728 //**************************************************
5729 @SuppressWarnings("unused")
5730 private void databaseBackup() {
5731 QFileDialog fd = new QFileDialog(this);
5732 fd.setFileMode(FileMode.AnyFile);
5733 fd.setConfirmOverwrite(true);
5734 fd.setWindowTitle(tr("Backup Database"));
5735 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5736 fd.setAcceptMode(AcceptMode.AcceptSave);
5737 if (saveLastPath == null || saveLastPath.equals(""))
5738 fd.setDirectory(System.getProperty("user.home"));
5740 fd.setDirectory(saveLastPath);
5741 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5747 saveLastPath = fd.selectedFiles().get(0);
5748 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5749 setMessage(tr("Backing up database"));
5751 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5753 ExportData noteWriter = new ExportData(conn, true);
5754 String fileName = fd.selectedFiles().get(0);
5756 if (!fileName.endsWith(".nnex"))
5757 fileName = fileName +".nnex";
5758 noteWriter.exportData(fileName);
5759 setMessage(tr("Database backup completed."));
5764 @SuppressWarnings("unused")
5765 private void databaseRestore() {
5766 if (QMessageBox.question(this, tr("Confirmation"),
5767 tr("This is used to restore a database from backups.\n" +
5768 "It is HIGHLY recommened that this only be used to populate\n" +
5769 "an empty database. Restoring into a database that\n already has data" +
5770 " can cause problems.\n\nAre you sure you want to continue?"),
5771 QMessageBox.StandardButton.Yes,
5772 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5777 QFileDialog fd = new QFileDialog(this);
5778 fd.setFileMode(FileMode.ExistingFile);
5779 fd.setConfirmOverwrite(true);
5780 fd.setWindowTitle(tr("Restore Database"));
5781 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5782 fd.setAcceptMode(AcceptMode.AcceptOpen);
5783 if (saveLastPath == null || saveLastPath.equals(""))
5784 fd.setDirectory(System.getProperty("user.home"));
5786 fd.setDirectory(saveLastPath);
5787 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5793 saveLastPath = fd.selectedFiles().get(0);
5794 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5796 setMessage(tr("Restoring database"));
5797 ImportData noteReader = new ImportData(conn, true);
5798 noteReader.importData(fd.selectedFiles().get(0));
5800 if (noteReader.lastError != 0) {
5801 setMessage(noteReader.getErrorMessage());
5802 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5807 listManager.loadNoteTitleColors();
5809 refreshEvernoteNote(true);
5810 setMessage(tr("Database has been restored."));
5813 @SuppressWarnings("unused")
5814 private void exportNotes() {
5815 QFileDialog fd = new QFileDialog(this);
5816 fd.setFileMode(FileMode.AnyFile);
5817 fd.setConfirmOverwrite(true);
5818 fd.setWindowTitle(tr("Backup Database"));
5819 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5820 fd.setAcceptMode(AcceptMode.AcceptSave);
5821 fd.setDirectory(System.getProperty("user.home"));
5822 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5828 setMessage(tr("Exporting Notes"));
5831 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5832 selectedNoteGUIDs.add(currentNoteGuid);
5834 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5835 String fileName = fd.selectedFiles().get(0);
5837 if (!fileName.endsWith(".nnex"))
5838 fileName = fileName +".nnex";
5839 noteWriter.exportData(fileName);
5840 setMessage(tr("Export completed."));
5846 @SuppressWarnings("unused")
5847 private void importNotes() {
5848 QFileDialog fd = new QFileDialog(this);
5849 fd.setFileMode(FileMode.ExistingFile);
5850 fd.setConfirmOverwrite(true);
5851 fd.setWindowTitle(tr("Import Notes"));
5852 fd.setFilter(tr("NixNote Export (*.nnex);;Evernote Export (*.enex);;All Files (*.*)"));
5853 fd.setAcceptMode(AcceptMode.AcceptOpen);
5854 if (saveLastPath == null || saveLastPath.equals(""))
5855 fd.setDirectory(System.getProperty("user.home"));
5857 fd.setDirectory(saveLastPath);
5858 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5864 setMessage(tr("Importing Notes"));
5867 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5868 selectedNoteGUIDs.add(currentNoteGuid);
5870 String fileName = fd.selectedFiles().get(0);
5871 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5873 if (fileName.endsWith(".nnex")) {
5874 ImportData noteReader = new ImportData(conn, false);
5875 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5876 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5878 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5880 noteReader.importData(fileName);
5882 if (noteReader.lastError != 0) {
5883 setMessage(noteReader.getErrorMessage());
5884 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5889 if (fileName.endsWith(".enex")) {
5890 ImportEnex noteReader = new ImportEnex(conn, false);
5891 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5892 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5894 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5896 noteReader.importData(fileName);
5898 if (noteReader.lastError != 0) {
5899 setMessage(noteReader.getErrorMessage());
5900 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5907 listManager.loadNoteTitleColors();
5909 refreshEvernoteNote(false);
5910 setMessage(tr("Notes have been imported."));
5913 setMessage(tr("Import completed."));
5920 //**************************************************
5921 //* Duplicate a note
5922 //**************************************************
5923 @SuppressWarnings("unused")
5924 private void duplicateNote() {
5926 duplicateNote(currentNoteGuid);
5929 //**************************************************
5930 //* Action from when a user clicks Copy As URL
5931 //**************************************************
5932 @SuppressWarnings("unused")
5933 private void copyAsUrlClicked() {
5934 QClipboard clipboard = QApplication.clipboard();
5935 QMimeData mime = new QMimeData();
5937 mime.setText(currentNoteGuid);
5938 List<QUrl> urls = new ArrayList<QUrl>();
5940 // Start building the URL
5941 User user = Global.getUserInformation();
5943 // Check that we have everything we need
5944 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
5945 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
5947 if (!warning.neverSynchronize())
5950 Global.setBypassSynchronizationWarning(true);
5951 user.setShardId("s0");
5957 // Start building a list of URLs based upon the selected notes
5958 noteTableView.showColumn(Global.noteTableGuidPosition);
5960 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
5961 if (!Global.isColumnVisible("guid"))
5962 noteTableView.hideColumn(Global.noteTableGuidPosition);
5964 // Check that the note is either synchronized, or in a local notebook
5965 for (int i=0; i<selections.size(); i++) {
5967 int row = selections.get(i).row();
5968 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5969 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5970 String selectedGuid = (String)ix.values().toArray()[0];
5972 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5973 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
5974 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
5975 "new notes to a local notebook."));
5980 // Start building the URLs
5981 for (int i=0; i<selections.size(); i++) {
5983 int row = selections.get(i).row();
5984 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5985 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5986 String selectedGuid = (String)ix.values().toArray()[0];
5987 mime.setText(selectedGuid);
5991 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5992 if (selectedNote.getUpdateSequenceNum() > 0) {
5996 gid = "00000000-0000-0000-0000-000000000000";
5999 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
6001 urls.add(new QUrl(url));
6004 clipboard.setMimeData(mime);
6008 //**************************************************
6010 //**************************************************
6011 public void setupFolderImports() {
6012 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
6014 if (importKeepWatcher == null)
6015 importKeepWatcher = new QFileSystemWatcher();
6016 if (importDeleteWatcher == null) {
6017 importDeleteWatcher = new QFileSystemWatcher();
6018 for (int i=0; i<records.size(); i++) {
6019 if (!records.get(i).keep)
6020 folderImportDelete(records.get(i).folder);
6026 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
6027 for (int i=0; i<records.size(); i++) {
6028 if (records.get(i).keep)
6029 importKeepWatcher.addPath(records.get(i).folder);
6031 importDeleteWatcher.addPath(records.get(i).folder);
6034 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
6035 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
6037 // Look at the files already there so we don't import them again if a new file is created
6038 if (importedFiles == null) {
6039 importedFiles = new ArrayList<String>();
6040 for (int j=0; j<records.size(); j++) {
6041 QDir dir = new QDir(records.get(j).folder);
6042 List<QFileInfo> list = dir.entryInfoList();
6043 for (int k=0; k<list.size(); k++) {
6044 if (list.get(k).isFile())
6045 importedFiles.add(list.get(k).absoluteFilePath());
6050 public void folderImport() {
6051 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
6052 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
6054 if (!dialog.okClicked())
6057 // We have some sort of update.
6058 if (importKeepWatcher.directories().size() > 0)
6059 importKeepWatcher.removePaths(importKeepWatcher.directories());
6060 if (importDeleteWatcher.directories().size() > 0)
6061 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
6063 conn.getWatchFolderTable().expungeAll();
6064 // Start building from the table
6065 for (int i=0; i<dialog.table.rowCount(); i++) {
6066 QTableWidgetItem item = dialog.table.item(i, 0);
6067 String dir = item.text();
6068 item = dialog.table.item(i, 1);
6069 String notebook = item.text();
6070 item = dialog.table.item(i, 2);
6072 if (item.text().equalsIgnoreCase("Keep"))
6077 String guid = conn.getNotebookTable().findNotebookByName(notebook);
6078 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
6080 setupFolderImports();
6083 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
6085 String whichOS = System.getProperty("os.name");
6086 if (whichOS.contains("Windows"))
6087 dirName = dirName.replace('/','\\');
6089 FileImporter importer = new FileImporter(logger, conn);
6091 QDir dir = new QDir(dirName);
6092 List<QFileInfo> list = dir.entryInfoList();
6093 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6095 for (int i=0; i<list.size(); i++){
6097 boolean redundant = false;
6098 // Check if we've already imported this one or if it existed before
6099 for (int j=0; j<importedFiles.size(); j++) {
6100 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6105 importer.setFileInfo(list.get(i));
6106 importer.setFileName(list.get(i).absoluteFilePath());
6109 if (list.get(i).isFile() && importer.isValidType()) {
6111 if (!importer.importFile()) {
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 importFilesKeep.add(list.get(i).absoluteFilePath());
6118 Note newNote = importer.getNote();
6119 newNote.setNotebookGuid(notebook);
6120 newNote.setTitle(dir.at(i));
6121 NoteMetadata metadata = new NoteMetadata();
6122 metadata.setDirty(true);
6123 metadata.setGuid(newNote.getGuid());
6124 listManager.addNote(newNote, metadata);
6125 conn.getNoteTable().addNote(newNote, true);
6126 noteTableView.insertRow(newNote, metadata, true, -1);
6127 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6128 listManager.countNotebookResults(listManager.getNoteIndex());
6129 importedFiles.add(list.get(i).absoluteFilePath());
6137 public void folderImportDelete(String dirName) {
6139 String whichOS = System.getProperty("os.name");
6140 if (whichOS.contains("Windows"))
6141 dirName = dirName.replace('/','\\');
6143 FileImporter importer = new FileImporter(logger, conn);
6144 QDir dir = new QDir(dirName);
6145 List<QFileInfo> list = dir.entryInfoList();
6146 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6148 for (int i=0; i<list.size(); i++){
6149 importer.setFileInfo(list.get(i));
6150 importer.setFileName(list.get(i).absoluteFilePath());
6152 if (list.get(i).isFile() && importer.isValidType()) {
6154 if (!importer.importFile()) {
6155 // If we can't get to the file, it is probably locked. We'll try again later.
6156 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6157 importFilesKeep.add(list.get(i).absoluteFilePath());
6161 Note newNote = importer.getNote();
6162 newNote.setNotebookGuid(notebook);
6163 newNote.setTitle(dir.at(i));
6164 NoteMetadata metadata = new NoteMetadata();
6165 metadata.setDirty(true);
6166 metadata.setGuid(newNote.getGuid());
6167 listManager.addNote(newNote, metadata);
6168 conn.getNoteTable().addNote(newNote, true);
6169 noteTableView.insertRow(newNote, metadata, true, -1);
6170 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6171 listManager.countNotebookResults(listManager.getNoteIndex());
6172 dir.remove(dir.at(i));
6178 //**************************************************
6180 //**************************************************
6181 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6182 logger.log(logger.HIGH, "Entering exernalFileEdited");
6184 // Strip URL prefix and base dir path
6185 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6186 String name = fileName.replace(dPath, "");
6187 int pos = name.lastIndexOf('.');
6190 guid = guid.substring(0,pos);
6192 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6194 guid = name.substring(0, pos);
6197 QFile file = new QFile(fileName);
6198 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6199 // If we can't get to the file, it is probably locked. We'll try again later.
6200 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6201 externalFiles.add(fileName);
6204 QByteArray binData = file.readAll();
6206 if (binData.size() == 0) {
6207 // If we can't get to the file, it is probably locked. We'll try again later.
6208 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6209 externalFiles.add(fileName);
6213 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6215 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6216 if (r == null || r.getData() == null || r.getData().getBody() == null)
6218 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6219 MessageDigest md = MessageDigest.getInstance("MD5");
6220 md.update(binData.toByteArray());
6221 byte[] hash = md.digest();
6222 String newHash = Global.byteArrayToHexString(hash);
6223 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6224 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6226 if (externalWindows.containsKey(r.getNoteGuid())) {
6227 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6228 r.getGuid(), oldHash, newHash);
6230 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6231 Data data = r.getData();
6232 data.setBody(binData.toByteArray());
6233 data.setBodyHash(hash);
6234 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6236 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6238 if (r.getNoteGuid().equals(currentNoteGuid)) {
6239 QWebSettings.setMaximumPagesInCache(0);
6240 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6241 refreshEvernoteNote(true);
6242 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6245 if (externalWindows.containsKey(r.getNoteGuid())) {
6246 QWebSettings.setMaximumPagesInCache(0);
6247 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6248 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6252 logger.log(logger.HIGH, "Exiting externalFielEdited");
6254 // This is a timer event that tries to save any external files that were edited. This
6255 // is only needed if we couldn't save a file earlier.
6256 public void externalFileEditedSaver() {
6257 for (int i=externalFiles.size()-1; i>=0; i--) {
6259 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6260 externalFileEdited(externalFiles.get(i));
6261 externalFiles.remove(i);
6262 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6264 for (int i=0; i<importFilesKeep.size(); i++) {
6266 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6267 folderImportKeep(importFilesKeep.get(i));
6268 importFilesKeep.remove(i);
6269 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6271 for (int i=0; i<importFilesDelete.size(); i++) {
6272 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6273 folderImportDelete(importFilesDelete.get(i));
6274 importFilesDelete.remove(i);
6281 // If an attachment on the current note was edited, we need to update the current notes's hash
6282 // Update a note content's hash. This happens if a resource is edited outside of NN
6283 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6284 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6286 for (;position>-1;) {
6287 endPos = browser.getContent().indexOf(">", position+1);
6288 String oldSegment = browser.getContent().substring(position,endPos);
6289 int hashPos = oldSegment.indexOf("hash=\"");
6290 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6291 String hash = oldSegment.substring(hashPos+6, hashEnd);
6292 if (hash.equalsIgnoreCase(oldHash)) {
6293 String newSegment = oldSegment.replace(oldHash, newHash);
6294 String content = browser.getContent().substring(0,position) +
6296 browser.getContent().substring(endPos);
6297 browser.setContent(new QByteArray(content));;
6300 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6305 //*************************************************
6306 //* Minimize to tray
6307 //*************************************************
6309 public void changeEvent(QEvent e) {
6310 if (e.type() == QEvent.Type.WindowStateChange) {
6311 if (isMinimized() && Global.showTrayIcon()) {
6313 QTimer.singleShot(10, this, "hide()");
6317 windowMaximized = true;
6319 windowMaximized = false;
6323 //*************************************************
6324 //* Check database userid & passwords
6325 //*************************************************
6326 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6327 Connection connection;
6330 Class.forName("org.h2.Driver");
6331 } catch (ClassNotFoundException e1) {
6332 e1.printStackTrace();
6337 String passwordString = null;
6338 if (cypherPassword==null || cypherPassword.trim().equals(""))
6339 passwordString = userPassword;
6341 passwordString = cypherPassword+" "+userPassword;
6342 connection = DriverManager.getConnection(url,userid,passwordString);
6343 } catch (SQLException e) {
6348 } catch (SQLException e) {
6349 e.printStackTrace();
6354 //*************************************************
6355 //* View / Hide source HTML for a note
6356 //*************************************************
6357 public void viewSource() {
6358 browserWindow.showSource(menuBar.viewSource.isChecked());
6360 //*************************************************
6361 // Block the program. This is used for things
6362 // like async web calls.
6363 //*************************************************
6364 @SuppressWarnings("unused")
6365 private void blockApplication(BrowserWindow b) {
6366 // Block all signals
6370 blockTimer = new QTimer();
6371 blockTimer.setSingleShot(true);
6372 blockTimer.setInterval(15000);
6373 blockTimer.timeout.connect(this, "unblockApplication()");
6378 @SuppressWarnings("unused")
6379 private void unblockApplication() {
6381 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6382 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6383 blockingWindow.unblockTime = -1;
6384 blockingWindow.awaitingHttpResponse = false;
6386 blockingWindow = null;
6387 blockSignals(false);