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.io.FileOutputStream;
25 import java.net.Authenticator;
26 import java.net.PasswordAuthentication;
27 import java.security.MessageDigest;
28 import java.security.NoSuchAlgorithmException;
29 import java.sql.Connection;
30 import java.sql.DriverManager;
31 import java.sql.SQLException;
32 import java.sql.Statement;
33 import java.text.SimpleDateFormat;
34 import java.util.ArrayList;
35 import java.util.Calendar;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.Comparator;
39 import java.util.Date;
40 import java.util.GregorianCalendar;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.SortedMap;
45 import java.util.Vector;
47 import org.apache.log4j.Level;
48 import org.apache.log4j.Logger;
49 import org.apache.thrift.TException;
50 import org.h2.tools.ChangeFileEncryption;
52 import com.evernote.edam.error.EDAMNotFoundException;
53 import com.evernote.edam.error.EDAMSystemException;
54 import com.evernote.edam.error.EDAMUserException;
55 import com.evernote.edam.notestore.NoteFilter;
56 import com.evernote.edam.notestore.NoteVersionId;
57 import com.evernote.edam.type.Data;
58 import com.evernote.edam.type.LinkedNotebook;
59 import com.evernote.edam.type.Note;
60 import com.evernote.edam.type.NoteAttributes;
61 import com.evernote.edam.type.Notebook;
62 import com.evernote.edam.type.Publishing;
63 import com.evernote.edam.type.QueryFormat;
64 import com.evernote.edam.type.Resource;
65 import com.evernote.edam.type.SavedSearch;
66 import com.evernote.edam.type.Tag;
67 import com.evernote.edam.type.User;
68 import com.trolltech.qt.QThread;
69 import com.trolltech.qt.core.QByteArray;
70 import com.trolltech.qt.core.QDateTime;
71 import com.trolltech.qt.core.QDir;
72 import com.trolltech.qt.core.QEvent;
73 import com.trolltech.qt.core.QFile;
74 import com.trolltech.qt.core.QFileInfo;
75 import com.trolltech.qt.core.QFileSystemWatcher;
76 import com.trolltech.qt.core.QIODevice;
77 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
78 import com.trolltech.qt.core.QLocale;
79 import com.trolltech.qt.core.QMimeData;
80 import com.trolltech.qt.core.QModelIndex;
81 import com.trolltech.qt.core.QSize;
82 import com.trolltech.qt.core.QTemporaryFile;
83 import com.trolltech.qt.core.QTextCodec;
84 import com.trolltech.qt.core.QThreadPool;
85 import com.trolltech.qt.core.QTimer;
86 import com.trolltech.qt.core.QTranslator;
87 import com.trolltech.qt.core.QUrl;
88 import com.trolltech.qt.core.Qt;
89 import com.trolltech.qt.core.Qt.BGMode;
90 import com.trolltech.qt.core.Qt.ItemDataRole;
91 import com.trolltech.qt.core.Qt.KeyboardModifier;
92 import com.trolltech.qt.core.Qt.MouseButton;
93 import com.trolltech.qt.core.Qt.SortOrder;
94 import com.trolltech.qt.core.Qt.WidgetAttribute;
95 import com.trolltech.qt.gui.QAbstractItemView;
96 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
97 import com.trolltech.qt.gui.QAction;
98 import com.trolltech.qt.gui.QApplication;
99 import com.trolltech.qt.gui.QClipboard;
100 import com.trolltech.qt.gui.QCloseEvent;
101 import com.trolltech.qt.gui.QColor;
102 import com.trolltech.qt.gui.QComboBox;
103 import com.trolltech.qt.gui.QCursor;
104 import com.trolltech.qt.gui.QDesktopServices;
105 import com.trolltech.qt.gui.QDialog;
106 import com.trolltech.qt.gui.QFileDialog;
107 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
108 import com.trolltech.qt.gui.QFileDialog.FileMode;
109 import com.trolltech.qt.gui.QGridLayout;
110 import com.trolltech.qt.gui.QHBoxLayout;
111 import com.trolltech.qt.gui.QIcon;
112 import com.trolltech.qt.gui.QImage;
113 import com.trolltech.qt.gui.QKeySequence;
114 import com.trolltech.qt.gui.QLabel;
115 import com.trolltech.qt.gui.QMainWindow;
116 import com.trolltech.qt.gui.QMenu;
117 import com.trolltech.qt.gui.QMessageBox;
118 import com.trolltech.qt.gui.QMessageBox.StandardButton;
119 import com.trolltech.qt.gui.QPainter;
120 import com.trolltech.qt.gui.QPalette.ColorRole;
121 import com.trolltech.qt.gui.QPixmap;
122 import com.trolltech.qt.gui.QPrintDialog;
123 import com.trolltech.qt.gui.QPrinter;
124 import com.trolltech.qt.gui.QShortcut;
125 import com.trolltech.qt.gui.QSizePolicy;
126 import com.trolltech.qt.gui.QSizePolicy.Policy;
127 import com.trolltech.qt.gui.QSpinBox;
128 import com.trolltech.qt.gui.QSplashScreen;
129 import com.trolltech.qt.gui.QSplitter;
130 import com.trolltech.qt.gui.QStatusBar;
131 import com.trolltech.qt.gui.QSystemTrayIcon;
132 import com.trolltech.qt.gui.QTableWidgetItem;
133 import com.trolltech.qt.gui.QTextEdit;
134 import com.trolltech.qt.gui.QToolBar;
135 import com.trolltech.qt.gui.QTreeWidgetItem;
136 import com.trolltech.qt.network.QNetworkAccessManager;
137 import com.trolltech.qt.network.QNetworkReply;
138 import com.trolltech.qt.network.QNetworkRequest;
139 import com.trolltech.qt.webkit.QWebPage.WebAction;
140 import com.trolltech.qt.webkit.QWebSettings;
142 import cx.fbn.nevernote.config.InitializationException;
143 import cx.fbn.nevernote.config.StartupConfig;
144 import cx.fbn.nevernote.dialog.AccountDialog;
145 import cx.fbn.nevernote.dialog.ConfigDialog;
146 import cx.fbn.nevernote.dialog.DBEncryptDialog;
147 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
148 import cx.fbn.nevernote.dialog.DatabaseStatus;
149 import cx.fbn.nevernote.dialog.FindDialog;
150 import cx.fbn.nevernote.dialog.IgnoreSync;
151 import cx.fbn.nevernote.dialog.LogFileDialog;
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.oauth.OAuthTokenizer;
184 import cx.fbn.nevernote.oauth.OAuthWindow;
185 import cx.fbn.nevernote.sql.DatabaseConnection;
186 import cx.fbn.nevernote.sql.WatchFolderRecord;
187 import cx.fbn.nevernote.threads.IndexRunner;
188 import cx.fbn.nevernote.threads.SyncRunner;
189 import cx.fbn.nevernote.threads.ThumbnailRunner;
190 import cx.fbn.nevernote.utilities.AESEncrypter;
191 import cx.fbn.nevernote.utilities.ApplicationLogger;
192 import cx.fbn.nevernote.utilities.FileImporter;
193 import cx.fbn.nevernote.utilities.FileUtils;
194 import cx.fbn.nevernote.utilities.ListManager;
195 import cx.fbn.nevernote.utilities.SyncTimes;
196 import cx.fbn.nevernote.xml.ExportData;
197 import cx.fbn.nevernote.xml.ImportData;
198 import cx.fbn.nevernote.xml.ImportEnex;
199 import cx.fbn.nevernote.xml.NoteFormatter;
202 public class NeverNote extends QMainWindow{
204 QStatusBar statusBar; // Application status bar
206 DatabaseConnection conn;
208 MainMenuBar menuBar; // Main menu bar
209 FindDialog find; // Text search in note dialog
210 List<String> emitLog; // Messages displayed in the status bar;
211 QSystemTrayIcon trayIcon; // little tray icon
212 QMenu trayMenu; // System tray menu
213 QAction trayExitAction; // Exit the application
214 QAction trayShowAction; // toggle the show/hide action
215 QAction trayAddNoteAction; // Add a note from the system tray
216 QNetworkAccessManager versionChecker; // Used when checking for new versions
218 NotebookTreeWidget notebookTree; // List of notebooks
219 AttributeTreeWidget attributeTree; // List of note attributes
220 TagTreeWidget tagTree; // list of user created tags
221 SavedSearchTreeWidget savedSearchTree; // list of saved searches
222 TrashTreeWidget trashTree; // Trashcan
223 TableView noteTableView; // List of notes (the widget).
225 public BrowserWindow browserWindow; // Window containing browser & labels
226 public QToolBar toolBar; // The tool bar under the menu
227 QComboBox searchField; // search filter bar on the toolbar;
228 QShortcut searchShortcut; // Shortcut to search bar
229 boolean searchPerformed = false; // Search was done?
230 QuotaProgressBar quotaBar; // The current quota usage
232 ApplicationLogger logger;
233 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
234 List<String> selectedTagGUIDs; // List of selected tag GUIDs
235 List<String> selectedNoteGUIDs; // List of selected notes
236 String selectedSavedSearchGUID; // Currently selected saved searches
237 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
239 NoteFilter filter; // Note filter
240 String currentNoteGuid; // GUID of the current note
241 Note currentNote; // The currently viewed note
242 boolean noteDirty; // Has the note been changed?
243 boolean inkNote; // if this is an ink note, it is read only
244 boolean readOnly; // Is this note read-only?
247 ListManager listManager; // DB runnable task
249 List<QTemporaryFile> tempFiles; // Array of temporary files;
251 QTimer indexTimer; // timer to start the index thread
252 IndexRunner indexRunner; // thread to index notes
255 QTimer syncTimer; // Sync on an interval
256 QTimer syncDelayTimer; // Sync delay to free up database
257 SyncRunner syncRunner; // thread to do a sync.
258 QThread syncThread; // Thread which talks to evernote
259 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
260 QThread thumbnailThread; // Thread that generates pretty pictures
261 QTimer saveTimer; // Timer to save note contents
263 QTimer authTimer; // Refresh authentication
264 QTimer externalFileSaveTimer; // Save files altered externally
265 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
266 List<String> externalFiles; // External files to save later
267 List<String> importFilesKeep; // Auto-import files to save later
268 List<String> importFilesDelete; // Auto-import files to save later
270 int indexTime; // how often to try and index
271 boolean indexRunning; // Is indexing running?
272 boolean indexDisabled; // Is indexing disabled?
274 int syncThreadsReady; // number of sync threads that are free
275 int syncTime; // Sync interval
276 boolean syncRunning; // Is sync running?
277 boolean automaticSync; // do sync automatically?
278 QTreeWidgetItem attributeTreeSelected;
280 QAction prevButton; // Go to the previous item viewed
281 QAction nextButton; // Go to the next item in the history
282 QAction downButton; // Go to the next item in the list
283 QAction upButton; // Go to the prev. item in the list;
284 QAction synchronizeButton; // Synchronize with Evernote
285 QAction allNotesButton; // Reset & view all notes
286 QTimer synchronizeAnimationTimer; // Timer to change animation button
287 int synchronizeIconAngle; // Used to rotate sync icon
288 QAction printButton; // Print Button
289 QAction tagButton; // Tag edit button
290 QAction attributeButton; // Attribute information button
291 QAction emailButton; // Email button
292 QAction deleteButton; // Delete button
293 QAction newButton; // new Note Button;
294 QSpinBox zoomSpinner; // Zoom zoom
295 QAction searchClearButton; // Clear the search field
297 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
299 QSplitter mainLeftRightSplitter; // main splitter for left/right side
300 QSplitter leftSplitter1; // first left hand splitter
301 QSplitter browserIndexSplitter; // splitter between note index & note text
303 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
304 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
305 List<String> importedFiles; // History of imported files (so we don't import twice)
307 OnlineNoteHistory historyWindow; // online history window
308 List<NoteVersionId> versions; // history versions
310 QTimer threadMonitorTimer; // Timer to watch threads.
311 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
312 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
313 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
314 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
315 int tagDeadCount=0; // number of consecutive dead times for the tag thread
316 int trashDeadCount=0; // number of consecutive dead times for the trash thread
317 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
318 boolean disableTagThreadCheck=false;
319 boolean disableNotebookThreadCheck=false;
320 boolean disableTrashThreadCheck=false;
321 boolean disableSaveThreadCheck=false;
322 boolean disableSyncThreadCheck=false;
323 boolean disableIndexThreadCheck=false;
325 HashMap<String, String> noteCache; // Cash of note content
326 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
327 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
328 List<String> historyGuids; // GUIDs of previously viewed items
329 int historyPosition; // Position within the viewed items
330 boolean fromHistory; // Is this from the history queue?
331 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
332 List<Thumbnailer> thumbGenerators; // generate preview image
333 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
334 boolean encryptOnShutdown; // should I encrypt when I close?
335 boolean decryptOnShutdown; // should I decrypt on shutdown;
336 String encryptCipher; // What cipher should I use?
337 //Signal0 minimizeToTray;
338 boolean windowMaximized = false; // Keep track of the window state for restores
339 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
340 List<QPixmap> syncIcons; // Array of icons used in sync animation
341 private boolean closeAction = false; // Used to say when to close or when to minimize
342 private static Logger log = Logger.getLogger(NeverNote.class);
343 private String saveLastPath; // last path we used
344 private final QTimer messageTimer; // Timer to clear the status message.
345 private QTimer blockTimer;
346 BrowserWindow blockingWindow;
348 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
351 //***************************************************************
352 //***************************************************************
353 //** Constructor & main entry point
354 //***************************************************************
355 //***************************************************************
356 // Application Constructor
357 @SuppressWarnings("static-access")
358 public NeverNote(DatabaseConnection dbConn) {
360 if (conn.getConnection() == null) {
361 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
362 "is accessing the database or NixNote is already running.\n\n" +
363 "Please end any other process or shutdown the other NixNote before starting.\n\nExiting program."));
365 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
368 setObjectName("mainWindow");
369 // thread().setPriority(Thread.MAX_PRIORITY);
371 logger = new ApplicationLogger("nevernote.log");
372 logger.log(logger.HIGH, "Starting Application");
374 decryptOnShutdown = false;
375 encryptOnShutdown = false;
376 conn.checkDatabaseVersion();
380 // Start building the invalid XML tables
381 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
382 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
384 for (int i=0; i<elements.size(); i++) {
385 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
388 logger.log(logger.EXTREME, "Starting GUI build");
390 QTranslator nevernoteTranslator = new QTranslator();
391 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
392 QApplication.instance().installTranslator(nevernoteTranslator);
394 Global.originalPalette = QApplication.palette();
395 QApplication.setStyle(Global.getStyle());
396 if (Global.useStandardPalette())
397 QApplication.setPalette(QApplication.style().standardPalette());
398 setWindowTitle(tr("NixNote"));
400 mainLeftRightSplitter = new QSplitter();
401 setCentralWidget(mainLeftRightSplitter);
402 leftSplitter1 = new QSplitter();
403 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
405 browserIndexSplitter = new QSplitter();
406 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
408 //* Setup threads & thread timers
409 // int indexRunnerCount = Global.getIndexThreads();
410 // indexRunnerCount = 1;
411 QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount); // increase max thread count
413 logger.log(logger.EXTREME, "Building list manager");
414 listManager = new ListManager(conn, logger);
416 logger.log(logger.EXTREME, "Building index runners & timers");
417 indexRunner = new IndexRunner("indexRunner.log",
418 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
419 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
420 indexThread = new QThread(indexRunner, "Index Thread");
421 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
422 indexRunner.indexImageRecognition = Global.indexImageRecognition();
423 indexRunner.indexNoteBody = Global.indexNoteBody();
424 indexRunner.indexNoteTitle = Global.indexNoteTitle();
425 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
428 synchronizeAnimationTimer = new QTimer();
429 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
431 indexTimer = new QTimer();
432 indexTime = 1000*Global.getIndexThreadSleepInterval();
433 indexTimer.start(indexTime); // Start indexing timer
434 indexTimer.timeout.connect(this, "indexTimer()");
435 indexDisabled = false;
436 indexRunning = false;
438 logger.log(logger.EXTREME, "Setting sync thread & timers");
440 syncRunner = new SyncRunner("syncRunner.log",
441 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
442 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
443 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
444 syncTimer = new QTimer();
445 syncTimer.timeout.connect(this, "syncTimer()");
446 syncRunner.status.message.connect(this, "setMessage(String)");
447 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
448 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
451 automaticSync = true;
452 syncTimer.start(syncTime*60*1000);
454 automaticSync = false;
457 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
458 syncThread = new QThread(syncRunner, "Synchronization Thread");
462 logger.log(logger.EXTREME, "Starting thumnail thread");
463 pdfReadyQueue = new ArrayList<String>();
464 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
465 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
466 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
467 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
468 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
469 thumbnailThread.start();
470 thumbGenerators = new ArrayList<Thumbnailer>();
471 thumbnailTimer = new QTimer();
472 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
474 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
475 thumbnailTimer.start();
477 logger.log(logger.EXTREME, "Starting authentication timer");
478 authTimer = new QTimer();
479 authTimer.timeout.connect(this, "authTimer()");
480 authTimer.start(1000*60*15);
481 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
483 logger.log(logger.EXTREME, "Setting save note timer");
484 saveTimer = new QTimer();
485 saveTimer.timeout.connect(this, "saveNote()");
486 if (Global.getAutoSaveInterval() > 0) {
487 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
490 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
492 logger.log(logger.EXTREME, "Starting external file monitor timer");
493 externalFileSaveTimer = new QTimer();
494 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
495 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
496 externalFiles = new ArrayList<String>();
497 importFilesDelete = new ArrayList<String>();
498 importFilesKeep = new ArrayList<String>();
499 externalFileSaveTimer.start();
501 notebookTree = new NotebookTreeWidget(conn);
502 attributeTree = new AttributeTreeWidget();
503 tagTree = new TagTreeWidget(conn);
504 savedSearchTree = new SavedSearchTreeWidget();
505 trashTree = new TrashTreeWidget();
506 noteTableView = new TableView(logger, listManager);
508 searchField = new QComboBox();
509 searchField.setObjectName("searchField");
510 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
511 searchField.setEditable(true);
512 searchField.activatedIndex.connect(this, "searchFieldChanged()");
513 searchField.setDuplicatesEnabled(false);
514 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
515 searchShortcut = new QShortcut(this);
516 setupShortcut(searchShortcut, "Focus_Search");
517 searchShortcut.activated.connect(this, "focusSearch()");
519 quotaBar = new QuotaProgressBar();
521 zoomSpinner = new QSpinBox();
522 zoomSpinner.setMinimum(10);
523 zoomSpinner.setMaximum(1000);
524 zoomSpinner.setAccelerated(true);
525 zoomSpinner.setSingleStep(10);
526 zoomSpinner.setValue(100);
527 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
529 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
532 QGridLayout leftGrid = new QGridLayout();
533 leftSplitter1.setContentsMargins(5, 0, 0, 7);
534 leftSplitter1.setLayout(leftGrid);
535 leftGrid.addWidget(searchLayout,1,1);
536 leftGrid.addWidget(tagTree,2,1);
537 leftGrid.addWidget(attributeTree,3,1);
538 leftGrid.addWidget(savedSearchTree,4,1);
539 leftGrid.addWidget(trashTree,5, 1);
541 // Setup the browser window
542 noteCache = new HashMap<String,String>();
543 readOnlyCache = new HashMap<String, Boolean>();
544 inkNoteCache = new HashMap<String, Boolean>();
545 browserWindow = new BrowserWindow(conn);
547 mainLeftRightSplitter.addWidget(leftSplitter1);
548 mainLeftRightSplitter.addWidget(browserIndexSplitter);
550 if (Global.getListView() == Global.View_List_Wide) {
551 browserIndexSplitter.addWidget(noteTableView);
552 browserIndexSplitter.addWidget(browserWindow);
554 mainLeftRightSplitter.addWidget(noteTableView);
555 mainLeftRightSplitter.addWidget(browserWindow);
558 // Setup the thumbnail viewer
559 thumbnailViewer = new ThumbnailViewer();
560 thumbnailViewer.upArrow.connect(this, "upAction()");
561 thumbnailViewer.downArrow.connect(this, "downAction()");
562 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
563 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
565 //Setup external browser manager
566 externalWindows = new HashMap<String, ExternalBrowse>();
568 listManager.loadNotesIndex();
569 initializeNotebookTree();
571 initializeSavedSearchTree();
572 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
573 attributeTreeSelected = null;
574 initializeNoteTable();
576 selectedNoteGUIDs = new ArrayList<String>();
577 statusBar = new QStatusBar();
578 setStatusBar(statusBar);
579 menuBar = new MainMenuBar(this);
580 emitLog = new ArrayList<String>();
582 tagTree.setDeleteAction(menuBar.tagDeleteAction);
583 tagTree.setMergeAction(menuBar.tagMergeAction);
584 tagTree.setEditAction(menuBar.tagEditAction);
585 tagTree.setAddAction(menuBar.tagAddAction);
586 tagTree.setIconAction(menuBar.tagIconAction);
587 tagTree.setVisible(Global.isWindowVisible("tagTree"));
588 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
589 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
590 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
591 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
593 if (!Global.isWindowVisible("zoom")) {
594 searchLayout.hideZoom();
595 menuBar.hideZoom.setChecked(false);
598 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
599 notebookTree.setEditAction(menuBar.notebookEditAction);
600 notebookTree.setAddAction(menuBar.notebookAddAction);
601 notebookTree.setIconAction(menuBar.notebookIconAction);
602 notebookTree.setStackAction(menuBar.notebookStackAction);
603 notebookTree.setPublishAction(menuBar.notebookPublishAction);
604 notebookTree.setShareAction(menuBar.notebookShareAction);
605 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
606 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
607 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
608 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
609 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
611 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
612 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
613 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
614 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
615 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
616 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
617 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
619 noteTableView.setAddAction(menuBar.noteAdd);
620 noteTableView.setDeleteAction(menuBar.noteDelete);
621 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
622 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
623 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
624 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
625 noteTableView.noteSignal.notePinned.connect(this, "notePinned()");
626 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
627 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
628 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
629 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
631 quotaBar.setMouseClickAction(menuBar.accountAction);
634 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
635 trashTree.setEmptyAction(menuBar.emptyTrashAction);
636 trashTree.setVisible(Global.isWindowVisible("trashTree"));
637 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
638 trashTree.updateCounts(listManager.getTrashCount());
639 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
640 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
642 noteTableView.setVisible(Global.isWindowVisible("noteList"));
643 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
645 if (!Global.isWindowVisible("editorButtonBar"))
646 toggleEditorButtonBar();
647 if (!Global.isWindowVisible("leftPanel"))
648 menuBar.hideLeftSide.setChecked(true);
649 if (Global.isWindowVisible("noteInformation"))
650 toggleNoteInformation();
651 quotaBar.setVisible(Global.isWindowVisible("quota"));
652 if (!quotaBar.isVisible())
653 menuBar.hideQuota.setChecked(false);
654 searchField.setVisible(Global.isWindowVisible("searchField"));
655 if (!searchField.isVisible())
656 menuBar.hideSearch.setChecked(false);
658 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
663 find = new FindDialog();
664 find.getOkButton().clicked.connect(this, "doFindText()");
666 // Setup the tray icon menu bar
667 trayShowAction = new QAction(tr("Show/Hide"), this);
668 trayExitAction = new QAction(tr("Exit"), this);
669 trayAddNoteAction = new QAction(tr("Add Note"), this);
671 trayExitAction.triggered.connect(this, "closeNeverNote()");
672 trayAddNoteAction.triggered.connect(this, "addNote()");
673 trayShowAction.triggered.connect(this, "trayToggleVisible()");
675 trayMenu = new QMenu(this);
676 trayMenu.addAction(trayAddNoteAction);
677 trayMenu.addAction(trayShowAction);
678 trayMenu.addAction(trayExitAction);
681 trayIcon = new QSystemTrayIcon(this);
682 trayIcon.setToolTip(tr("NixNote"));
683 trayIcon.setContextMenu(trayMenu);
684 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
687 currentNoteGuid = Global.getLastViewedNoteGuid();
688 historyGuids = new ArrayList<String>();
692 if (!currentNoteGuid.trim().equals("")) {
693 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
696 noteIndexUpdated(true);
698 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
699 if (menuBar.showEditorBar.isChecked())
700 showEditorButtons(browserWindow);
701 tagIndexUpdated(true);
702 savedSearchIndexUpdated();
703 notebookIndexUpdated();
705 setupSyncSignalListeners();
706 setupBrowserSignalListeners();
707 setupIndexListeners();
710 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
711 tagTree.showAllTags(true);
713 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
714 if (QSystemTrayIcon.isSystemTrayAvailable()) {
715 setWindowIcon(appIcon);
716 trayIcon.setIcon(appIcon);
717 if (Global.showTrayIcon() || Global.minimizeOnClose())
723 scrollToGuid(currentNoteGuid);
724 if (Global.automaticLogin()) {
726 if (Global.isConnected)
729 setupFolderImports();
732 restoreWindowState(true);
734 if (Global.mimicEvernoteInterface) {
735 notebookTree.selectGuid("");
738 threadMonitorTimer = new QTimer();
739 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
740 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
742 historyGuids.add(currentNoteGuid);
745 menuBar.blockSignals(true);
746 menuBar.narrowListView.blockSignals(true);
747 menuBar.wideListView.blockSignals(true);
748 if (Global.getListView() == Global.View_List_Narrow) {
749 menuBar.narrowListView.setChecked(true);
752 menuBar.wideListView.setChecked(true);
754 menuBar.blockSignals(false);
755 menuBar.narrowListView.blockSignals(false);
756 menuBar.wideListView.blockSignals(false);
758 if (Global.getListView() == Global.View_List_Wide) {
759 browserIndexSplitter.addWidget(noteTableView);
760 browserIndexSplitter.addWidget(browserWindow);
762 mainLeftRightSplitter.addWidget(noteTableView);
763 mainLeftRightSplitter.addWidget(browserWindow);
766 messageTimer = new QTimer();
767 messageTimer.timeout.connect(this, "clearMessage()");
768 messageTimer.setInterval(1000*15);
771 int sortCol = Global.getSortColumn();
772 int sortOrder = Global.getSortOrder();
773 noteTableView.proxyModel.blocked = true;
774 // We sort the table twice to fix a bug. For some reaosn the table won't sort properly if it is in narrow
775 // list view and sorted descending on the date created. By sorting it twice it forces the proper sort. Ugly.
776 if (sortCol == 0 && sortOrder == 1 && Global.getListView() == Global.View_List_Narrow)
777 noteTableView.sortByColumn(sortCol, SortOrder.resolve(0));
778 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
779 noteTableView.proxyModel.blocked = false;
780 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
782 // Set the startup notebook
783 String defaultNotebook = Global.getStartupNotebook();
784 if (!defaultNotebook.equals("AllNotebooks") && !defaultNotebook.equals("")) {
785 for (int k=0; k<listManager.getNotebookIndex().size(); k++) {
786 if (listManager.getNotebookIndex().get(k).isDefaultNotebook()) {
787 notebookTree.clearSelection();
788 notebookTree.selectGuid(listManager.getNotebookIndex().get(k).getGuid());
789 notebookTree.selectionSignal.emit();
794 if (Global.checkVersionUpgrade())
799 public static void main(String[] args) {
800 log.setLevel(Level.FATAL);
801 QApplication.initialize(args);
802 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
803 QSplashScreen splash = new QSplashScreen(pixmap);
806 DatabaseConnection dbConn;
809 initializeGlobalSettings(args);
811 showSplash = Global.isWindowVisible("SplashScreen");
815 dbConn = setupDatabaseConnection();
817 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
818 Global.getFileManager().purgeResDirectory(true);
820 } catch (InitializationException e) {
823 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
827 NeverNote application = new NeverNote(dbConn);
828 if (Global.syncOnly) {
829 System.out.println("Performing synchronization only.");
830 application.remoteConnect();
831 if (Global.isConnected) {
832 application.syncRunner.syncNeeded = true;
833 application.syncRunner.addWork("SYNC");
834 application.syncRunner.addWork("STOP");
835 while(!application.syncRunner.isIdle());
836 application.closeNeverNote();
841 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
842 if (Global.startMinimized())
843 application.showMinimized();
845 if (Global.wasWindowMaximized())
846 application.showMaximized();
852 splash.finish(application);
854 System.out.println("Goodbye.");
859 * Open the internal database, or create if not present
861 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
863 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
864 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
866 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
867 File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
868 File fi = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
870 Global.setDatabaseUrl("");
872 Global.setResourceDatabaseUrl("");
874 Global.setIndexDatabaseUrl("");
876 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
877 boolean goodCheck = false;
879 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
881 if (!dialog.okPressed())
883 Global.cipherPassword = dialog.getPassword();
884 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
885 Global.getDatabaseUserPassword(), Global.cipherPassword);
888 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
889 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
890 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
894 // Encrypt the database upon shutdown
895 private void encryptOnShutdown() {
896 String dbPath= Global.getFileManager().getDbDirPath("");
899 Statement st = conn.getConnection().createStatement();
900 st.execute("shutdown");
901 st = conn.getResourceConnection().createStatement();
902 st.execute("shutdown");
903 st = conn.getIndexConnection().createStatement();
904 st.execute("shutdown");
905 if (QMessageBox.question(this, tr("Are you sure"),
906 tr("Are you sure you wish to encrypt the database?"),
907 QMessageBox.StandardButton.Yes,
908 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
909 ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
910 ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
911 ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
912 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
913 Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
914 Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
916 QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
918 } catch (SQLException e) {
923 // Decrypt the database upon shutdown
924 private void decryptOnShutdown() {
925 String dbPath= Global.getFileManager().getDbDirPath("");
926 String dbName = "NeverNote";
928 Statement st = conn.getConnection().createStatement();
929 st.execute("shutdown");
930 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
931 encryptCipher = "AES";
933 encryptCipher = "XTEA";
934 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
935 "Are you sure you wish to decrypt the database?"),
936 QMessageBox.StandardButton.Yes,
937 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
939 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
940 Global.setDatabaseUrl("");
941 Global.setResourceDatabaseUrl("");
942 Global.setIndexDatabaseUrl("");
943 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
945 } catch (SQLException e) {
950 * Encrypt/Decrypt the local database
952 public void doDatabaseEncrypt() {
953 // The database is not currently encrypted
954 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
955 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
956 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
957 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
958 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
959 "Do you wish to proceed?"),
960 QMessageBox.StandardButton.Yes,
961 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
964 DBEncryptDialog dialog = new DBEncryptDialog();
966 if (dialog.okPressed()) {
967 Global.cipherPassword = dialog.getPassword();
968 encryptOnShutdown = true;
969 encryptCipher = dialog.getEncryptionMethod();
972 DBEncryptDialog dialog = new DBEncryptDialog();
973 dialog.setWindowTitle(tr("Database Decryption"));
974 dialog.hideEncryption();
976 if (dialog.okPressed()) {
977 if (!dialog.getPassword().equals(Global.cipherPassword)) {
978 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
981 decryptOnShutdown = true;
988 private static void initializeGlobalSettings(String[] args) throws InitializationException {
989 StartupConfig startupConfig = new StartupConfig();
991 for (String arg : args) {
992 String lower = arg.toLowerCase();
993 if (lower.startsWith("--name="))
994 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
995 if (lower.startsWith("--home="))
996 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
997 if (lower.startsWith("--disable-viewing"))
998 startupConfig.setDisableViewing(true);
999 if (lower.startsWith("--sync-only=true"))
1000 startupConfig.setSyncOnly(true);
1002 Global.setup(startupConfig);
1008 public void closeEvent(QCloseEvent event) {
1009 if (Global.minimizeOnClose() && !closeAction) {
1014 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
1017 if (currentNote!= null & browserWindow!=null) {
1018 if (currentNote.getTitle() != null && browserWindow != null
1019 && !currentNote.getTitle().equals(browserWindow.getTitle()))
1020 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
1023 setMessage(tr("Beginning shutdown."));
1025 // Close down external windows
1026 Collection<ExternalBrowse> windows = externalWindows.values();
1027 Iterator<ExternalBrowse> iterator = windows.iterator();
1028 while (iterator.hasNext()) {
1029 ExternalBrowse browser = iterator.next();
1030 browser.windowClosing.disconnect();
1035 externalFileEditedSaver();
1036 if (Global.isConnected && Global.synchronizeOnClose()) {
1037 setMessage(tr("Performing synchronization before closing."));
1038 syncRunner.syncNeeded = true;
1039 syncRunner.addWork("SYNC");
1041 syncRunner.keepRunning = false;
1043 syncRunner.addWork("STOP");
1044 setMessage("Closing Program.");
1045 threadMonitorTimer.stop();
1047 thumbnailRunner.addWork("STOP");
1048 indexRunner.addWork("STOP");
1053 if (tempFiles != null)
1056 browserWindow.noteSignal.tagsChanged.disconnect();
1057 browserWindow.noteSignal.titleChanged.disconnect();
1058 browserWindow.noteSignal.noteChanged.disconnect();
1059 browserWindow.noteSignal.notebookChanged.disconnect();
1060 browserWindow.noteSignal.createdDateChanged.disconnect();
1061 browserWindow.noteSignal.alteredDateChanged.disconnect();
1062 syncRunner.searchSignal.listChanged.disconnect();
1063 syncRunner.tagSignal.listChanged.disconnect();
1064 syncRunner.notebookSignal.listChanged.disconnect();
1065 syncRunner.noteIndexSignal.listChanged.disconnect();
1068 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1069 saveNoteColumnPositions();
1070 saveNoteIndexWidth();
1072 int width = notebookTree.columnWidth(0);
1073 Global.setColumnWidth("notebookTreeName", width);
1074 width = tagTree.columnWidth(0);
1075 Global.setColumnWidth("tagTreeName", width);
1077 Global.saveWindowMaximized(isMaximized());
1078 Global.saveCurrentNoteGuid(currentNoteGuid);
1080 int sortCol = noteTableView.proxyModel.sortColumn();
1081 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1082 Global.setSortColumn(sortCol);
1083 Global.setSortOrder(sortOrder);
1087 Global.keepRunning = false;
1089 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1090 if (indexRunner.thread().isAlive())
1091 indexRunner.thread().join(50);
1092 if (!indexRunner.thread().isAlive())
1093 logger.log(logger.MEDIUM, "Index thread has stopped");
1095 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1096 indexRunner.thread().interrupt();
1098 } catch (InterruptedException e1) {
1099 e1.printStackTrace();
1102 if (!syncRunner.thread().isAlive()) {
1103 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1104 if (syncRunner.thread().isAlive()) {
1105 System.out.println(tr("Synchronizing. Please be patient."));
1106 for(;syncRunner.thread().isAlive();) {
1109 } catch (InterruptedException e) {
1110 e.printStackTrace();
1114 logger.log(logger.MEDIUM, "Sync thread has stopped");
1117 if (encryptOnShutdown) {
1118 encryptOnShutdown();
1120 if (decryptOnShutdown) {
1121 decryptOnShutdown();
1124 Global.getFileManager().purgeResDirectory(false);
1125 } catch (InitializationException e) {
1126 System.out.println(tr("Empty res directory purge failed"));
1127 e.printStackTrace();
1129 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1133 private void closeNeverNote() {
1137 public void setMessage(String s) {
1138 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1141 logger.log(logger.HIGH, "Message: " +s);
1142 statusBar.showMessage(s);
1146 messageTimer.stop();
1147 messageTimer.setSingleShot(true);
1148 messageTimer.start();
1151 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1154 private void clearMessage() {
1155 statusBar.clearMessage();
1159 private void waitCursor(boolean wait) {
1161 if (QApplication.overrideCursor() == null)
1162 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1165 while (QApplication.overrideCursor() != null)
1166 QApplication.restoreOverrideCursor();
1168 listManager.refreshCounters();
1171 private void setupIndexListeners() {
1172 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1173 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1174 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1175 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1177 private void setupSyncSignalListeners() {
1178 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1179 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1180 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1181 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1182 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1184 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1185 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1186 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1188 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1189 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1190 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1191 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1192 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1194 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1197 private void setupBrowserSignalListeners() {
1198 setupBrowserWindowListeners(browserWindow, true);
1201 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1202 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1203 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1204 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1205 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1206 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1207 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1208 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1209 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1210 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1211 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1212 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1213 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1214 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1215 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1216 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1217 browser.unblockApplication.connect(this, "unblockApplication()");
1218 if (master) browser.focusLost.connect(this, "saveNote()");
1219 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1220 browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1223 //**************************************************
1225 //**************************************************
1226 private void setupShortcut(QShortcut action, String text) {
1227 if (!Global.shortcutKeys.containsAction(text))
1229 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1232 //***************************************************************
1233 //***************************************************************
1234 //* Settings and look & feel
1235 //***************************************************************
1236 //***************************************************************
1237 @SuppressWarnings("unused")
1238 private void settings() {
1239 logger.log(logger.HIGH, "Entering NeverNote.settings");
1240 saveNoteColumnPositions();
1241 saveNoteIndexWidth();
1243 ConfigDialog settings = new ConfigDialog(this);
1244 String dateFormat = Global.getDateFormat();
1245 String timeFormat = Global.getTimeFormat();
1247 indexTime = 1000*Global.getIndexThreadSleepInterval();
1248 indexTimer.start(indexTime); // reset indexing timer
1251 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1252 indexRunner.indexNoteBody = Global.indexNoteBody();
1253 indexRunner.indexNoteTitle = Global.indexNoteTitle();
1254 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1255 indexRunner.indexImageRecognition = Global.indexImageRecognition();
1256 if (Global.showTrayIcon() || Global.minimizeOnClose())
1261 if (menuBar.showEditorBar.isChecked())
1262 showEditorButtons(browserWindow);
1264 // Reset the save timer
1265 if (Global.getAutoSaveInterval() > 0)
1266 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1271 // Set special reloads
1272 if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1273 conn.executeSql("Delete from LinkedNotebook");
1274 conn.executeSql("delete from SharedNotebook");
1275 conn.executeSql("Delete from Notebook where linked=true");
1276 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1277 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1282 readOnlyCache.clear();
1283 inkNoteCache.clear();
1284 noteIndexUpdated(true);
1286 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1288 // Restore things to the way they were
1289 private void restoreWindowState(boolean mainWindow) {
1290 // We need to name things or this doesn't work.
1291 setObjectName("NeverNote");
1292 restoreState(Global.restoreState(objectName()));
1293 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1294 browserIndexSplitter.setObjectName("browserIndexSplitter");
1295 leftSplitter1.setObjectName("leftSplitter1");
1297 // Restore the actual positions.
1299 restoreGeometry(Global.restoreGeometry(objectName()));
1300 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1301 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1302 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1305 // Save window positions for the next start
1306 private void saveWindowState() {
1307 Global.saveGeometry(objectName(), saveGeometry());
1308 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1309 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1310 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1311 Global.saveState(objectName(), saveState());
1313 // Load the style sheet
1314 private void loadStyleSheet() {
1315 String styleSheetName = "default.qss";
1316 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1317 styleSheetName = "default-cleanlooks.qss";
1318 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1319 QFile file = new QFile(fileName);
1321 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1322 if (!file.exists()) {
1323 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1324 file = new QFile(fileName);
1326 file.open(OpenModeFlag.ReadOnly);
1327 String styleSheet = file.readAll().toString();
1329 setStyleSheet(styleSheet);
1331 // Save column positions for the next time
1332 private void saveNoteColumnPositions() {
1333 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1334 Global.setColumnPosition("noteTableCreationPosition", position);
1335 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1336 Global.setColumnPosition("noteTableTagPosition", position);
1337 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1338 Global.setColumnPosition("noteTableNotebookPosition", position);
1339 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1340 Global.setColumnPosition("noteTableChangedPosition", position);
1341 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1342 Global.setColumnPosition("noteTableAuthorPosition", position);
1343 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1344 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1345 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1346 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1347 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1348 Global.setColumnPosition("noteTableTitlePosition", position);
1349 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1350 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1351 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1352 Global.setColumnPosition("noteTableGuidPosition", position);
1353 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1354 Global.setColumnPosition("noteTableThumbnailPosition", position);
1355 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1356 Global.setColumnPosition("noteTablePinnedPosition", position);
1359 // Save column widths for the next time
1360 private void saveNoteIndexWidth() {
1362 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1363 Global.setColumnWidth("noteTableCreationPosition", width);
1364 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1365 Global.setColumnWidth("noteTableChangedPosition", width);
1366 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1367 Global.setColumnWidth("noteTableGuidPosition", width);
1368 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1369 Global.setColumnWidth("noteTableNotebookPosition", width);
1370 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1371 Global.setColumnWidth("noteTableTagPosition", width);
1372 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1373 Global.setColumnWidth("noteTableTitlePosition", width);
1374 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1375 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1376 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1377 Global.setColumnWidth("noteTableAuthorPosition", width);
1378 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1379 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1380 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1381 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1382 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1383 Global.setColumnWidth("noteTableThumbnailPosition", width);
1384 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1385 Global.setColumnWidth("noteTableGuidPosition", width);
1386 width = noteTableView.getColumnWidth(Global.noteTablePinnedPosition);
1387 Global.setColumnWidth("noteTablePinnedPosition", width);
1390 @SuppressWarnings("unused")
1391 private void toggleSearchWindow() {
1392 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1393 searchLayout.toggleSearchField();
1394 menuBar.hideSearch.setChecked(searchField.isVisible());
1395 Global.saveWindowVisible("searchField", searchField.isVisible());
1396 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1398 @SuppressWarnings("unused")
1399 private void toggleQuotaWindow() {
1400 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1401 searchLayout.toggleQuotaBar();
1402 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1403 Global.saveWindowVisible("quota", quotaBar.isVisible());
1404 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1406 @SuppressWarnings("unused")
1407 private void toggleZoomWindow() {
1408 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1409 searchLayout.toggleZoom();
1410 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1411 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1412 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1417 //***************************************************************
1418 //***************************************************************
1419 //** These functions deal with Notebook menu items
1420 //***************************************************************
1421 //***************************************************************
1422 // Setup the tree containing the user's notebooks.
1423 private void initializeNotebookTree() {
1424 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1425 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1426 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1427 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1428 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1430 // Listener when a notebook is selected
1431 private void notebookTreeSelection() {
1432 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1433 noteTableView.proxyModel.blocked = true;
1436 clearAttributeFilter();
1437 clearSavedSearchFilter();
1438 if (Global.mimicEvernoteInterface) {
1440 searchField.clear();
1442 menuBar.noteRestoreAction.setVisible(false);
1443 menuBar.notebookEditAction.setEnabled(true);
1444 menuBar.notebookDeleteAction.setEnabled(true);
1445 menuBar.notebookPublishAction.setEnabled(true);
1446 menuBar.notebookShareAction.setEnabled(true);
1447 menuBar.notebookIconAction.setEnabled(true);
1448 menuBar.notebookStackAction.setEnabled(true);
1449 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1450 selectedNotebookGUIDs.clear();
1452 String stackName = "";
1453 if (selections.size() > 0) {
1454 guid = (selections.get(0).text(2));
1455 stackName = selections.get(0).text(0);
1457 if (!Global.mimicEvernoteInterface) {
1458 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1459 if (selections.size()==0) {
1460 selectedNotebookGUIDs.clear();
1461 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1462 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1464 menuBar.notebookEditAction.setEnabled(false);
1465 menuBar.notebookDeleteAction.setEnabled(false);
1466 menuBar.notebookStackAction.setEnabled(false);
1467 menuBar.notebookIconAction.setEnabled(false);
1470 if (!guid.equals("") && !guid.equals("STACK")) {
1471 selectedNotebookGUIDs.add(guid);
1472 menuBar.notebookIconAction.setEnabled(true);
1474 menuBar.notebookIconAction.setEnabled(true);
1475 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1476 Notebook book = listManager.getNotebookIndex().get(j);
1477 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1478 selectedNotebookGUIDs.add(book.getGuid());
1481 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1482 listManager.loadNotesIndex();
1483 noteIndexUpdated(false);
1484 refreshEvernoteNote(true);
1485 listManager.refreshCounters = true;
1486 listManager.refreshCounters();
1487 if (selectedNotebookGUIDs.size() == 1) {
1488 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1489 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1491 noteTableView.proxyModel.blocked = true;
1493 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1495 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1498 noteTableView.proxyModel.blocked = false;
1499 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1502 private void clearNotebookFilter() {
1503 notebookTree.blockSignals(true);
1504 notebookTree.clearSelection();
1505 menuBar.noteRestoreAction.setVisible(false);
1506 menuBar.notebookEditAction.setEnabled(false);
1507 menuBar.notebookDeleteAction.setEnabled(false);
1508 selectedNotebookGUIDs.clear();
1509 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1510 notebookTree.blockSignals(false);
1512 // Triggered when the notebook DB has been updated
1513 private void notebookIndexUpdated() {
1514 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1516 // Get the possible icons
1517 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1518 notebookTree.setIcons(icons);
1520 if (selectedNotebookGUIDs == null)
1521 selectedNotebookGUIDs = new ArrayList<String>();
1522 List<Notebook> books = conn.getNotebookTable().getAll();
1523 for (int i=books.size()-1; i>=0; i--) {
1524 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1525 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1527 j=listManager.getArchiveNotebookIndex().size();
1533 listManager.countNotebookResults(listManager.getNoteIndex());
1534 notebookTree.blockSignals(true);
1535 notebookTree.load(books, listManager.getLocalNotebooks());
1536 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1537 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1539 selectedNotebookGUIDs.remove(i);
1541 listManager.refreshCounters = true;
1542 listManager.refreshCounters();
1543 notebookTree.blockSignals(false);
1545 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1547 // Show/Hide note information
1548 @SuppressWarnings("unused")
1549 private void toggleNotebookWindow() {
1550 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1551 searchLayout.toggleNotebook();
1552 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1553 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1554 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1556 // Add a new notebook
1557 @SuppressWarnings("unused")
1558 private void addNotebook() {
1559 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1560 NotebookEdit edit = new NotebookEdit();
1561 edit.setNotebooks(listManager.getNotebookIndex());
1564 if (!edit.okPressed())
1567 Calendar currentTime = new GregorianCalendar();
1568 Long l = new Long(currentTime.getTimeInMillis());
1569 String randint = new String(Long.toString(l));
1571 Notebook newBook = new Notebook();
1572 newBook.setUpdateSequenceNum(0);
1573 newBook.setGuid(randint);
1574 newBook.setName(edit.getNotebook());
1575 newBook.setServiceCreated(new Date().getTime());
1576 newBook.setServiceUpdated(new Date().getTime());
1577 newBook.setDefaultNotebook(false);
1578 newBook.setPublished(false);
1580 listManager.getNotebookIndex().add(newBook);
1582 listManager.getLocalNotebooks().add(newBook.getGuid());
1583 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1584 notebookIndexUpdated();
1585 listManager.countNotebookResults(listManager.getNoteIndex());
1586 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1587 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1589 // Edit an existing notebook
1590 @SuppressWarnings("unused")
1591 private void stackNotebook() {
1592 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1593 StackNotebook edit = new StackNotebook();
1595 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1596 QTreeWidgetItem currentSelection;
1597 for (int i=0; i<selections.size(); i++) {
1598 currentSelection = selections.get(0);
1599 String guid = currentSelection.text(2);
1600 if (guid.equalsIgnoreCase("")) {
1601 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1604 if (guid.equalsIgnoreCase("STACK")) {
1605 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1610 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1615 if (!edit.okPressed())
1618 String stack = edit.getStackName();
1620 for (int i=0; i<selections.size(); i++) {
1621 currentSelection = selections.get(i);
1622 String guid = currentSelection.text(2);
1623 listManager.updateNotebookStack(guid, stack);
1625 notebookIndexUpdated();
1626 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1628 // Edit an existing notebook
1629 @SuppressWarnings("unused")
1630 private void editNotebook() {
1631 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1632 NotebookEdit edit = new NotebookEdit();
1634 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1635 QTreeWidgetItem currentSelection;
1636 currentSelection = selections.get(0);
1637 edit.setNotebook(currentSelection.text(0));
1639 String guid = currentSelection.text(2);
1640 if (!guid.equalsIgnoreCase("STACK")) {
1641 edit.setTitle(tr("Edit Notebook"));
1642 edit.setNotebooks(listManager.getNotebookIndex());
1643 edit.setLocalCheckboxEnabled(false);
1644 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1645 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1646 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1647 i=listManager.getNotebookIndex().size();
1651 edit.setTitle(tr("Edit Stack"));
1652 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1653 edit.hideLocalCheckbox();
1654 edit.hideDefaultCheckbox();
1659 if (!edit.okPressed())
1663 if (guid.equalsIgnoreCase("STACK")) {
1664 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1665 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1666 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1667 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1668 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1670 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1671 currentSelection.setText(0, edit.getNotebook());
1675 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1676 currentSelection.setText(0, edit.getNotebook());
1678 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1679 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1680 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1681 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1682 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1683 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1684 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1685 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1687 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1688 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1689 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1690 linkedNotebook.setShareName(edit.getNotebook());
1691 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1693 i=listManager.getNotebookIndex().size();
1697 // Build a list of non-closed notebooks
1698 List<Notebook> nbooks = new ArrayList<Notebook>();
1699 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1700 boolean found=false;
1701 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1702 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1706 nbooks.add(listManager.getNotebookIndex().get(i));
1710 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1711 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1712 browserWindow.setNotebookList(filteredBooks);
1713 Iterator<String> set = externalWindows.keySet().iterator();
1714 while(set.hasNext())
1715 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1716 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1718 // Publish a notebook
1719 @SuppressWarnings("unused")
1720 private void publishNotebook() {
1721 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1722 QTreeWidgetItem currentSelection;
1723 currentSelection = selections.get(0);
1724 String guid = currentSelection.text(2);
1726 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);
1735 i = listManager.getNotebookIndex().size();
1741 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1744 if (!publish.okClicked())
1747 Publishing p = publish.getPublishing();
1748 boolean isPublished = !publish.isStopPressed();
1749 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1750 n.setPublished(isPublished);
1752 listManager.getNotebookIndex().set(position, n);
1753 notebookIndexUpdated();
1755 // Publish a notebook
1756 @SuppressWarnings("unused")
1757 private void shareNotebook() {
1758 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1759 QTreeWidgetItem currentSelection;
1760 currentSelection = selections.get(0);
1761 String guid = currentSelection.text(2);
1763 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1767 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1768 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1769 n = listManager.getNotebookIndex().get(i);
1770 i = listManager.getNotebookIndex().size();
1774 String authToken = null;
1775 if (syncRunner.isConnected)
1776 authToken = syncRunner.authToken;
1777 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1782 // Delete an existing notebook
1783 @SuppressWarnings("unused")
1784 private void deleteNotebook() {
1785 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1786 boolean stacksFound = false;
1787 boolean notebooksFound = false;
1788 boolean assigned = false;
1789 // Check if any notes have this notebook
1790 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1791 for (int i=0; i<selections.size(); i++) {
1792 QTreeWidgetItem currentSelection;
1793 currentSelection = selections.get(i);
1794 String guid = currentSelection.text(2);
1795 if (!guid.equalsIgnoreCase("STACK")) {
1796 notebooksFound = true;
1797 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1798 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1799 if (noteGuid.equals(guid)) {
1801 j=listManager.getNoteIndex().size();
1802 i=selections.size();
1810 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1811 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1815 if (conn.getNotebookTable().getAll().size() == 1) {
1816 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1820 // If all notebooks are clear, verify the delete
1821 String msg1 = new String(tr("Delete selected notebooks?"));
1822 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1823 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1824 " not deleted unless selected?"));
1826 if (stacksFound && notebooksFound)
1828 if (!stacksFound && notebooksFound)
1830 if (stacksFound && !notebooksFound)
1832 if (QMessageBox.question(this, tr("Confirmation"), msg,
1833 QMessageBox.StandardButton.Yes,
1834 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1838 // If confirmed, delete the notebook
1839 for (int i=selections.size()-1; i>=0; i--) {
1840 QTreeWidgetItem currentSelection;
1841 currentSelection = selections.get(i);
1842 String guid = currentSelection.text(2);
1843 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1844 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1845 listManager.renameStack(currentSelection.text(0), "");
1847 conn.getNotebookTable().expungeNotebook(guid, true);
1848 listManager.deleteNotebook(guid);
1852 notebookIndexUpdated();
1853 // notebookTreeSelection();
1854 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1855 // listManager.countNotebookResults(listManager.getNoteIndex());
1856 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1858 // A note's notebook has been updated
1859 @SuppressWarnings("unused")
1860 private void updateNoteNotebook(String guid, String notebookGuid) {
1862 // Update the list manager
1863 listManager.updateNoteNotebook(guid, notebookGuid);
1864 listManager.countNotebookResults(listManager.getNoteIndex());
1865 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1867 // Find the name of the notebook
1868 String notebookName = null;
1869 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1870 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1871 notebookName = listManager.getNotebookIndex().get(i).getName();
1876 // If we found the name, update the browser window
1877 if (notebookName != null) {
1878 updateListNoteNotebook(guid, notebookName);
1879 if (guid.equals(currentNoteGuid)) {
1880 int pos = browserWindow.notebookBox.findText(notebookName);
1882 browserWindow.notebookBox.setCurrentIndex(pos);
1886 // If we're dealing with the current note, then we need to be sure and update the notebook there
1887 if (guid.equals(currentNoteGuid)) {
1888 if (currentNote != null) {
1889 currentNote.setNotebookGuid(notebookGuid);
1893 // Open/close notebooks
1894 @SuppressWarnings("unused")
1895 private void closeNotebooks() {
1896 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1898 if (!na.okClicked())
1902 listManager.getArchiveNotebookIndex().clear();
1904 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1905 String text = na.getClosedBookList().takeItem(i).text();
1906 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1907 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1908 Notebook n = listManager.getNotebookIndex().get(j);
1909 conn.getNotebookTable().setArchived(n.getGuid(),true);
1910 listManager.getArchiveNotebookIndex().add(n);
1911 j=listManager.getNotebookIndex().size();
1916 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1917 String text = na.getOpenBookList().takeItem(i).text();
1918 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1919 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1920 Notebook n = listManager.getNotebookIndex().get(j);
1921 conn.getNotebookTable().setArchived(n.getGuid(),false);
1922 j=listManager.getNotebookIndex().size();
1926 notebookTreeSelection();
1927 listManager.loadNotesIndex();
1928 notebookIndexUpdated();
1929 noteIndexUpdated(false);
1930 reloadTagTree(true);
1931 // noteIndexUpdated(false);
1933 // Build a list of non-closed notebooks
1934 List<Notebook> nbooks = new ArrayList<Notebook>();
1935 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1936 boolean found=false;
1937 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1938 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1942 nbooks.add(listManager.getNotebookIndex().get(i));
1945 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1946 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1947 browserWindow.setNotebookList(filteredBooks);
1949 // Update any external windows
1950 Iterator<String> set = externalWindows.keySet().iterator();
1951 while(set.hasNext())
1952 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1956 // Change the notebook's icon
1957 @SuppressWarnings("unused")
1958 private void setNotebookIcon() {
1959 boolean stackSelected = false;
1960 boolean allNotebookSelected = false;
1962 QTreeWidgetItem currentSelection;
1963 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1964 if (selections.size() == 0)
1967 currentSelection = selections.get(0);
1968 String guid = currentSelection.text(2);
1969 if (guid.equalsIgnoreCase(""))
1970 allNotebookSelected = true;
1971 if (guid.equalsIgnoreCase("STACK"))
1972 stackSelected = true;
1974 QIcon currentIcon = currentSelection.icon(0);
1978 if (!stackSelected && !allNotebookSelected) {
1979 icon = conn.getNotebookTable().getIcon(guid);
1981 dialog = new SetIcon(currentIcon, saveLastPath);
1982 dialog.setUseDefaultIcon(true);
1984 dialog = new SetIcon(icon, saveLastPath);
1985 dialog.setUseDefaultIcon(false);
1988 if (stackSelected) {
1989 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1991 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1994 dialog = new SetIcon(currentIcon, saveLastPath);
1995 dialog.setUseDefaultIcon(true);
1997 dialog = new SetIcon(icon, saveLastPath);
1998 dialog.setUseDefaultIcon(false);
2002 if (dialog.okPressed()) {
2003 saveLastPath = dialog.getPath();
2005 QIcon newIcon = dialog.getIcon();
2006 if (stackSelected) {
2007 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
2008 if (newIcon == null) {
2009 newIcon = new QIcon(iconPath+"books2.png");
2011 currentSelection.setIcon(0,newIcon);
2014 if (allNotebookSelected) {
2015 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
2016 if (newIcon == null) {
2017 newIcon = new QIcon(iconPath+"notebook-green.png");
2019 currentSelection.setIcon(0,newIcon);
2022 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
2023 if (newIcon == null) {
2024 boolean isPublished = false;;
2025 boolean found = false;
2026 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
2027 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
2028 isPublished = listManager.getNotebookIndex().get(i).isPublished();
2032 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
2034 currentSelection.setIcon(0, newIcon);
2040 //***************************************************************
2041 //***************************************************************
2042 //** These functions deal with Tag menu items
2043 //***************************************************************
2044 //***************************************************************
2045 // Add a new notebook
2046 @SuppressWarnings("unused")
2047 private void addTag() {
2048 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2049 TagEdit edit = new TagEdit();
2050 edit.setTagList(listManager.getTagIndex());
2052 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2053 QTreeWidgetItem currentSelection = null;
2054 if (selections.size() > 0) {
2055 currentSelection = selections.get(0);
2056 edit.setParentTag(currentSelection.text(0));
2061 if (!edit.okPressed())
2064 Calendar currentTime = new GregorianCalendar();
2065 Long l = new Long(currentTime.getTimeInMillis());
2066 String randint = new String(Long.toString(l));
2068 Tag newTag = new Tag();
2069 newTag.setUpdateSequenceNum(0);
2070 newTag.setGuid(randint);
2071 newTag.setName(edit.getTag());
2072 if (edit.getParentTag().isChecked()) {
2073 newTag.setParentGuid(currentSelection.text(2));
2074 newTag.setParentGuidIsSet(true);
2075 currentSelection.setExpanded(true);
2077 conn.getTagTable().addTag(newTag, true);
2078 listManager.getTagIndex().add(newTag);
2079 reloadTagTree(true);
2081 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2083 @SuppressWarnings("unused")
2084 private void reloadTagTree() {
2085 reloadTagTree(false);
2087 private void reloadTagTree(boolean reload) {
2088 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2089 tagIndexUpdated(reload);
2090 boolean filter = false;
2092 listManager.countTagResults(listManager.getNoteIndex());
2093 if (notebookTree.selectedItems().size() > 0
2094 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2096 if (tagTree.selectedItems().size() > 0)
2098 tagTree.showAllTags(!filter);
2099 tagIndexUpdated(false);
2100 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2102 // Edit an existing tag
2103 @SuppressWarnings("unused")
2104 private void editTag() {
2105 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2106 TagEdit edit = new TagEdit();
2107 edit.setTitle("Edit Tag");
2108 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2109 QTreeWidgetItem currentSelection;
2110 currentSelection = selections.get(0);
2111 edit.setTag(currentSelection.text(0));
2112 edit.setTagList(listManager.getTagIndex());
2115 if (!edit.okPressed())
2118 String guid = currentSelection.text(2);
2119 currentSelection.setText(0,edit.getTag());
2121 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2122 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2123 listManager.getTagIndex().get(i).setName(edit.getTag());
2124 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2125 updateListTagName(guid);
2126 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2127 browserWindow.setTag(getTagNamesForNote(currentNote));
2128 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2132 listManager.reloadNoteTagNames(guid, edit.getTag());
2133 noteIndexUpdated(true);
2134 refreshEvernoteNote(true);
2135 browserWindow.setTag(getTagNamesForNote(currentNote));
2136 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2138 // Delete an existing tag
2139 @SuppressWarnings("unused")
2140 private void deleteTag() {
2141 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2143 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2144 QMessageBox.StandardButton.Yes,
2145 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2149 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2150 for (int i=selections.size()-1; i>=0; i--) {
2151 QTreeWidgetItem currentSelection;
2152 currentSelection = selections.get(i);
2153 removeTagItem(currentSelection.text(2));
2155 tagIndexUpdated(true);
2157 listManager.countTagResults(listManager.getNoteIndex());
2158 // tagTree.updateCounts(listManager.getTagCounter());
2159 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2161 // Remove a tag tree item. Go recursively down & remove the children too
2162 private void removeTagItem(String guid) {
2163 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2164 String parent = listManager.getTagIndex().get(j).getParentGuid();
2165 if (parent != null && parent.equals(guid)) {
2166 //Remove this tag's children
2167 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2170 //Now, remove this tag
2171 removeListTagName(guid);
2172 conn.getTagTable().expungeTag(guid, true);
2173 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2174 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2175 listManager.getTagIndex().remove(a);
2180 // Setup the tree containing the user's tags
2181 private void initializeTagTree() {
2182 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2183 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2184 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2185 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2186 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2187 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2189 // Listener when a tag is selected
2190 private void tagTreeSelection() {
2191 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2194 clearAttributeFilter();
2195 clearSavedSearchFilter();
2197 menuBar.noteRestoreAction.setVisible(false);
2199 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2200 QTreeWidgetItem currentSelection;
2201 selectedTagGUIDs.clear();
2202 for (int i=0; i<selections.size(); i++) {
2203 currentSelection = selections.get(i);
2204 selectedTagGUIDs.add(currentSelection.text(2));
2206 if (selections.size() > 0) {
2207 menuBar.tagEditAction.setEnabled(true);
2208 menuBar.tagDeleteAction.setEnabled(true);
2209 menuBar.tagIconAction.setEnabled(true);
2212 menuBar.tagEditAction.setEnabled(false);
2213 menuBar.tagDeleteAction.setEnabled(false);
2214 menuBar.tagIconAction.setEnabled(true);
2216 if (selections.size() > 1)
2217 menuBar.tagMergeAction.setEnabled(true);
2219 menuBar.tagMergeAction.setEnabled(false);
2220 listManager.setSelectedTags(selectedTagGUIDs);
2221 listManager.loadNotesIndex();
2222 noteIndexUpdated(false);
2223 refreshEvernoteNote(true);
2224 listManager.refreshCounters = true;
2225 listManager.refreshCounters();
2226 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2228 // trigger the tag index to be refreshed
2229 @SuppressWarnings("unused")
2230 private void tagIndexUpdated() {
2231 tagIndexUpdated(true);
2233 private void tagIndexUpdated(boolean reload) {
2234 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2235 if (selectedTagGUIDs == null)
2236 selectedTagGUIDs = new ArrayList<String>();
2238 listManager.reloadTagIndex();
2240 tagTree.blockSignals(true);
2242 tagTree.setIcons(conn.getTagTable().getAllIcons());
2243 tagTree.load(listManager.getTagIndex());
2246 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2247 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2249 selectedTagGUIDs.remove(i);
2251 tagTree.blockSignals(false);
2253 browserWindow.setTag(getTagNamesForNote(currentNote));
2254 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2256 // Show/Hide note information
2257 @SuppressWarnings("unused")
2258 private void toggleTagWindow() {
2259 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2260 if (tagTree.isVisible())
2264 menuBar.hideTags.setChecked(tagTree.isVisible());
2265 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2266 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2268 // A note's tags have been updated
2269 @SuppressWarnings("unused")
2270 private void updateNoteTags(String guid, List<String> tags) {
2271 // Save any new tags. We'll need them later.
2272 List<String> newTags = new ArrayList<String>();
2273 for (int i=0; i<tags.size(); i++) {
2274 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2275 newTags.add(tags.get(i));
2278 listManager.saveNoteTags(guid, tags);
2279 listManager.countTagResults(listManager.getNoteIndex());
2280 StringBuffer names = new StringBuffer("");
2281 for (int i=0; i<tags.size(); i++) {
2282 names = names.append(tags.get(i));
2283 if (i<tags.size()-1) {
2284 names.append(Global.tagDelimeter + " ");
2287 browserWindow.setTag(names.toString());
2290 // Now, we need to add any new tags to the tag tree
2291 for (int i=0; i<newTags.size(); i++)
2292 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2294 // Get a string containing all tag names for a note
2295 private String getTagNamesForNote(Note n) {
2296 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2297 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2299 StringBuffer buffer = new StringBuffer(100);
2300 Vector<String> v = new Vector<String>();
2301 List<String> guids = n.getTagGuids();
2306 for (int i=0; i<guids.size(); i++) {
2307 v.add(listManager.getTagNameByGuid(guids.get(i)));
2309 Comparator<String> comparator = Collections.reverseOrder();
2310 Collections.sort(v,comparator);
2311 Collections.reverse(v);
2313 for (int i = 0; i<v.size(); i++) {
2315 buffer.append(", ");
2316 buffer.append(v.get(i));
2319 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2320 return buffer.toString();
2322 // Tags were added via dropping notes from the note list
2323 @SuppressWarnings("unused")
2324 private void tagsAdded(String noteGuid, String tagGuid) {
2325 String tagName = null;
2326 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2327 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2328 tagName = listManager.getTagIndex().get(i).getName();
2329 i=listManager.getTagIndex().size();
2332 if (tagName == null)
2335 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2336 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2337 List<String> tagNames = new ArrayList<String>();
2338 tagNames.add(new String(tagName));
2339 Note n = listManager.getMasterNoteIndex().get(i);
2340 for (int j=0; j<n.getTagNames().size(); j++) {
2341 tagNames.add(new String(n.getTagNames().get(j)));
2343 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2344 if (n.getGuid().equals(currentNoteGuid)) {
2345 Collections.sort(tagNames);
2346 String display = "";
2347 for (int j=0; j<tagNames.size(); j++) {
2348 display = display+tagNames.get(j);
2349 if (j+2<tagNames.size())
2350 display = display+Global.tagDelimeter+" ";
2352 browserWindow.setTag(display);
2354 i=listManager.getMasterNoteIndex().size();
2359 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2361 private void clearTagFilter() {
2362 tagTree.blockSignals(true);
2363 tagTree.clearSelection();
2364 menuBar.noteRestoreAction.setVisible(false);
2365 menuBar.tagEditAction.setEnabled(false);
2366 menuBar.tagMergeAction.setEnabled(false);
2367 menuBar.tagDeleteAction.setEnabled(false);
2368 menuBar.tagIconAction.setEnabled(false);
2369 selectedTagGUIDs.clear();
2370 listManager.setSelectedTags(selectedTagGUIDs);
2371 tagTree.blockSignals(false);
2373 // Change the icon for a tag
2374 @SuppressWarnings("unused")
2375 private void setTagIcon() {
2376 QTreeWidgetItem currentSelection;
2377 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2378 if (selections.size() == 0)
2381 currentSelection = selections.get(0);
2382 String guid = currentSelection.text(2);
2384 QIcon currentIcon = currentSelection.icon(0);
2385 QIcon icon = conn.getTagTable().getIcon(guid);
2388 dialog = new SetIcon(currentIcon, saveLastPath);
2389 dialog.setUseDefaultIcon(true);
2391 dialog = new SetIcon(icon, saveLastPath);
2392 dialog.setUseDefaultIcon(false);
2395 if (dialog.okPressed()) {
2396 saveLastPath = dialog.getPath();
2397 QIcon newIcon = dialog.getIcon();
2398 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2399 if (newIcon == null)
2400 newIcon = new QIcon(iconPath+"tag.png");
2401 currentSelection.setIcon(0, newIcon);
2406 @SuppressWarnings("unused")
2407 private void mergeTags() {
2408 List<Tag> tags = new ArrayList<Tag>();
2409 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2410 for (int i=0; i<selections.size(); i++) {
2411 Tag record = new Tag();
2412 record.setGuid(selections.get(i).text(2));
2413 record.setName(selections.get(i).text(0));
2417 TagMerge mergeDialog = new TagMerge(tags);
2419 if (!mergeDialog.okClicked())
2421 String newGuid = mergeDialog.getNewTagGuid();
2423 for (int i=0; i<tags.size(); i++) {
2424 if (!tags.get(i).getGuid().equals(newGuid)) {
2425 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2426 for (int j=0; j<noteGuids.size(); j++) {
2427 String noteGuid = noteGuids.get(j);
2428 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2429 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2430 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2434 listManager.reloadIndexes();
2437 //***************************************************************
2438 //***************************************************************
2439 //** These functions deal with Saved Search menu items
2440 //***************************************************************
2441 //***************************************************************
2442 // Add a new notebook
2443 @SuppressWarnings("unused")
2444 private void addSavedSearch() {
2445 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2446 SavedSearchEdit edit = new SavedSearchEdit();
2447 edit.setSearchList(listManager.getSavedSearchIndex());
2450 if (!edit.okPressed())
2453 Calendar currentTime = new GregorianCalendar();
2454 Long l = new Long(currentTime.getTimeInMillis());
2455 String randint = new String(Long.toString(l));
2457 SavedSearch search = new SavedSearch();
2458 search.setUpdateSequenceNum(0);
2459 search.setGuid(randint);
2460 search.setName(edit.getName());
2461 search.setQuery(edit.getQuery());
2462 search.setFormat(QueryFormat.USER);
2463 listManager.getSavedSearchIndex().add(search);
2464 conn.getSavedSearchTable().addSavedSearch(search, true);
2465 savedSearchIndexUpdated();
2466 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2468 // Edit an existing tag
2469 @SuppressWarnings("unused")
2470 private void editSavedSearch() {
2471 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2472 SavedSearchEdit edit = new SavedSearchEdit();
2473 edit.setTitle(tr("Edit Search"));
2474 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2475 QTreeWidgetItem currentSelection;
2476 currentSelection = selections.get(0);
2477 String guid = currentSelection.text(1);
2478 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2479 edit.setName(currentSelection.text(0));
2480 edit.setQuery(s.getQuery());
2481 edit.setSearchList(listManager.getSavedSearchIndex());
2484 if (!edit.okPressed())
2487 List<SavedSearch> list = listManager.getSavedSearchIndex();
2488 SavedSearch search = null;
2489 boolean found = false;
2490 for (int i=0; i<list.size(); i++) {
2491 search = list.get(i);
2492 if (search.getGuid().equals(guid)) {
2499 search.setName(edit.getName());
2500 search.setQuery(edit.getQuery());
2501 conn.getSavedSearchTable().updateSavedSearch(search, true);
2502 savedSearchIndexUpdated();
2503 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2505 // Delete an existing tag
2506 @SuppressWarnings("unused")
2507 private void deleteSavedSearch() {
2508 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2510 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2511 QMessageBox.StandardButton.Yes,
2512 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2516 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2517 for (int i=selections.size()-1; i>=0; i--) {
2518 QTreeWidgetItem currentSelection;
2519 currentSelection = selections.get(i);
2520 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2521 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2522 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2523 listManager.getSavedSearchIndex().remove(j);
2524 j=listManager.getSavedSearchIndex().size()+1;
2527 selections.remove(i);
2529 savedSearchIndexUpdated();
2530 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2532 // Setup the tree containing the user's tags
2533 private void initializeSavedSearchTree() {
2534 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2535 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2536 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2538 // Listener when a tag is selected
2539 @SuppressWarnings("unused")
2540 private void savedSearchTreeSelection() {
2541 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2543 clearNotebookFilter();
2546 clearAttributeFilter();
2548 String currentGuid = selectedSavedSearchGUID;
2549 menuBar.savedSearchEditAction.setEnabled(true);
2550 menuBar.savedSearchDeleteAction.setEnabled(true);
2551 menuBar.savedSearchIconAction.setEnabled(true);
2552 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2553 QTreeWidgetItem currentSelection;
2554 selectedSavedSearchGUID = "";
2555 for (int i=0; i<selections.size(); i++) {
2556 currentSelection = selections.get(i);
2557 if (currentSelection.text(1).equals(currentGuid)) {
2558 currentSelection.setSelected(false);
2560 selectedSavedSearchGUID = currentSelection.text(1);
2562 // i = selections.size() +1;
2565 // There is the potential for no notebooks to be selected if this
2566 // happens then we make it look like all notebooks were selecetd.
2567 // If that happens, just select the "all notebooks"
2568 if (selections.size()==0) {
2569 clearSavedSearchFilter();
2571 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2573 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2575 private void clearSavedSearchFilter() {
2576 menuBar.savedSearchEditAction.setEnabled(false);
2577 menuBar.savedSearchDeleteAction.setEnabled(false);
2578 menuBar.savedSearchIconAction.setEnabled(false);
2579 savedSearchTree.blockSignals(true);
2580 savedSearchTree.clearSelection();
2581 savedSearchTree.blockSignals(false);
2582 selectedSavedSearchGUID = "";
2583 searchField.setEditText("");
2584 searchPerformed = false;
2585 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2587 // trigger the tag index to be refreshed
2588 private void savedSearchIndexUpdated() {
2589 if (selectedSavedSearchGUID == null)
2590 selectedSavedSearchGUID = new String();
2591 savedSearchTree.blockSignals(true);
2592 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2593 savedSearchTree.load(listManager.getSavedSearchIndex());
2594 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2595 savedSearchTree.blockSignals(false);
2597 // trigger when the saved search selection changes
2598 @SuppressWarnings("unused")
2599 private void updateSavedSearchSelection() {
2600 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2602 menuBar.savedSearchEditAction.setEnabled(true);
2603 menuBar.savedSearchDeleteAction.setEnabled(true);
2604 menuBar.savedSearchIconAction.setEnabled(true);
2605 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2607 if (selections.size() > 0) {
2608 menuBar.savedSearchEditAction.setEnabled(true);
2609 menuBar.savedSearchDeleteAction.setEnabled(true);
2610 menuBar.savedSearchIconAction.setEnabled(true);
2611 selectedSavedSearchGUID = selections.get(0).text(1);
2612 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2613 searchField.setEditText(s.getQuery());
2615 menuBar.savedSearchEditAction.setEnabled(false);
2616 menuBar.savedSearchDeleteAction.setEnabled(false);
2617 menuBar.savedSearchIconAction.setEnabled(false);
2618 selectedSavedSearchGUID = "";
2619 searchField.setEditText("");
2621 searchFieldChanged();
2623 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2627 // Show/Hide note information
2628 @SuppressWarnings("unused")
2629 private void toggleSavedSearchWindow() {
2630 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2631 if (savedSearchTree.isVisible())
2632 savedSearchTree.hide();
2634 savedSearchTree.show();
2635 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2637 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2638 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2640 // Change the icon for a saved search
2641 @SuppressWarnings("unused")
2642 private void setSavedSearchIcon() {
2643 QTreeWidgetItem currentSelection;
2644 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2645 if (selections.size() == 0)
2648 currentSelection = selections.get(0);
2649 String guid = currentSelection.text(1);
2651 QIcon currentIcon = currentSelection.icon(0);
2652 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2655 dialog = new SetIcon(currentIcon, saveLastPath);
2656 dialog.setUseDefaultIcon(true);
2658 dialog = new SetIcon(icon, saveLastPath);
2659 dialog.setUseDefaultIcon(false);
2662 if (dialog.okPressed()) {
2663 saveLastPath = dialog.getPath();
2664 QIcon newIcon = dialog.getIcon();
2665 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2666 if (newIcon == null)
2667 newIcon = new QIcon(iconPath+"search.png");
2668 currentSelection.setIcon(0, newIcon);
2676 //***************************************************************
2677 //***************************************************************
2678 //** These functions deal with Help menu & tool menu items
2679 //***************************************************************
2680 //***************************************************************
2681 // Show database status
2682 @SuppressWarnings("unused")
2683 private void databaseStatus() {
2685 indexRunner.interrupt = true;
2686 int dirty = conn.getNoteTable().getDirtyCount();
2687 int unindexed = conn.getNoteTable().getUnindexedCount();
2688 DatabaseStatus status = new DatabaseStatus();
2689 status.setUnsynchronized(dirty);
2690 status.setUnindexed(unindexed);
2691 status.setNoteCount(conn.getNoteTable().getNoteCount());
2692 status.setNotebookCount(listManager.getNotebookIndex().size());
2693 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2694 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2695 status.setTagCount(listManager.getTagIndex().size());
2696 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2697 status.setWordCount(conn.getWordsTable().getWordCount());
2701 // Compact the database
2702 @SuppressWarnings("unused")
2703 private void compactDatabase() {
2704 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2705 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2706 "but please be aware that depending upon the size of your database this can be time consuming " +
2707 "and NixNote will be unresponsive until it is complete. Do you wish to continue?"),
2708 QMessageBox.StandardButton.Yes,
2709 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2712 setMessage("Compacting database.");
2714 listManager.compactDatabase();
2716 setMessage("Database compact is complete.");
2717 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2719 @SuppressWarnings("unused")
2720 private void accountInformation() {
2721 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2722 AccountDialog dialog = new AccountDialog();
2724 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2726 @SuppressWarnings("unused")
2727 private void releaseNotes() {
2728 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2729 QDialog dialog = new QDialog(this);
2730 QHBoxLayout layout = new QHBoxLayout();
2731 QTextEdit textBox = new QTextEdit();
2732 layout.addWidget(textBox);
2733 textBox.setReadOnly(true);
2734 QFile file = new QFile(Global.getFileManager().getProgramDirPath("release.txt"));
2735 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2736 QIODevice.OpenModeFlag.Text)))
2738 textBox.setText(file.readAll().toString());
2740 dialog.setWindowTitle(tr("Release Notes"));
2741 dialog.setLayout(layout);
2743 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2745 // Called when user picks Log from the help menu
2746 @SuppressWarnings("unused")
2747 private void logger() {
2748 logger.log(logger.HIGH, "Entering NeverNote.logger");
2749 LogFileDialog dialog = new LogFileDialog(emitLog);
2751 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2753 // Menu option "help/about" was selected
2754 @SuppressWarnings("unused")
2755 private void about() {
2756 logger.log(logger.HIGH, "Entering NeverNote.about");
2757 QMessageBox.about(this,
2758 tr("About NixNote"),
2759 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2763 +"Open Source Evernote Client.<br><br>"
2764 +"Licensed under GPL v2. <br><hr><br>"
2765 +"</center>Evernote is copyright 2001-2012 by Evernote Corporation<br>"
2766 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2767 +"PDFRenderer is licened under the LGPL<br>"
2768 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2769 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2770 +"Jazzy is licened under the LGPL<br>"
2771 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2772 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2773 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2774 logger.log(logger.HIGH, "Leaving NeverNote.about");
2776 // Hide the entire left hand side
2777 @SuppressWarnings("unused")
2778 private void toggleLeftSide() {
2781 hidden = !menuBar.hideLeftSide.isChecked();
2782 menuBar.hideLeftSide.setChecked(!hidden);
2785 leftSplitter1.setHidden(true);
2787 leftSplitter1.setHidden(false);
2789 Global.saveWindowVisible("leftPanel", hidden);
2792 public void checkForUpdates() {
2793 // Send off thread to check for a new version
2794 versionChecker = new QNetworkAccessManager(this);
2795 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2796 QNetworkRequest request = new QNetworkRequest();
2797 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2798 versionChecker.get(request);
2800 @SuppressWarnings("unused")
2801 private void upgradeFileRead(QNetworkReply reply) {
2802 if (!reply.isReadable())
2805 String winVersion = Global.version;
2806 String osxVersion = Global.version;
2807 String linuxVersion = Global.version;
2808 String linux64Version = Global.version;
2809 String version = Global.version;
2811 // Determine the versions available
2812 QByteArray data = reply.readLine();
2813 while (data != null && !reply.atEnd()) {
2814 String line = data.toString();
2816 if (line.contains(":"))
2817 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2820 if (line.toLowerCase().contains("windows"))
2821 winVersion = lineVersion;
2822 else if (line.toLowerCase().contains("os-x"))
2823 osxVersion = lineVersion;
2824 else if (line.toLowerCase().contains("linux amd64"))
2825 linux64Version = lineVersion;
2826 else if (line.toLowerCase().contains("linux i386"))
2827 linuxVersion = lineVersion;
2828 else if (line.toLowerCase().contains("default"))
2829 version = lineVersion;
2831 // Read the next line
2832 data = reply.readLine();
2835 // Now we need to determine what system we are on.
2836 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2837 version = winVersion;
2838 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2839 version = osxVersion;
2840 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2841 if (System.getProperty("os.arch").contains("amd64") ||
2842 System.getProperty("os.arch").contains("x86_64"))
2843 version = linux64Version;
2845 version = linuxVersion;
2849 for (String validVersion : Global.validVersions) {
2850 if (version.equals(validVersion))
2854 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2856 if (dialog.remindMe())
2857 Global.setCheckVersionUpgrade(true);
2859 Global.setCheckVersionUpgrade(false);
2863 //***************************************************************
2864 //***************************************************************
2865 //** These functions deal with the Toolbar
2866 //***************************************************************
2867 //***************************************************************
2868 @SuppressWarnings("unused")
2869 private void focusSearch() {
2870 searchField.setFocus();
2873 // Text in the search bar has been cleared
2874 private void searchFieldCleared() {
2877 // This is done because we want to force a reload of
2878 // images. Some images we may want to highlight the text.
2879 readOnlyCache.clear();
2880 inkNoteCache.clear();
2882 QWebSettings.setMaximumPagesInCache(0);
2883 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2885 searchField.setEditText("");
2886 saveNoteColumnPositions();
2887 saveNoteIndexWidth();
2888 noteIndexUpdated(true);
2889 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2890 currentNote = listManager.getNoteIndex().get(0);
2891 currentNoteGuid = currentNote.getGuid();
2893 refreshEvernoteNote(true);
2894 if (currentNote != null)
2895 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2897 // text in the search bar changed. We only use this to tell if it was cleared,
2898 // otherwise we trigger off searchFieldChanged.
2899 @SuppressWarnings("unused")
2900 private void searchFieldTextChanged(String text) {
2901 QWebSettings.setMaximumPagesInCache(0);
2902 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2904 if (text.trim().equals("")) {
2905 searchFieldCleared();
2906 if (searchPerformed) {
2908 // This is done because we want to force a reload of
2909 // images. Some images we may want to highlight the text.
2911 readOnlyCache.clear();
2912 inkNoteCache.clear();
2914 listManager.setEnSearch("");
2915 listManager.loadNotesIndex();
2916 refreshEvernoteNote(true);
2917 noteIndexUpdated(false);
2918 refreshEvernoteNote(true);
2920 searchPerformed = false;
2923 // Text in the toolbar has changed
2924 private void searchFieldChanged() {
2925 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2927 readOnlyCache.clear();
2928 inkNoteCache.clear();
2929 saveNoteColumnPositions();
2930 saveNoteIndexWidth();
2931 String text = searchField.currentText();
2932 listManager.setEnSearch(text.trim());
2933 listManager.loadNotesIndex();
2934 noteIndexUpdated(false);
2936 refreshEvernoteNote(true);
2937 searchPerformed = true;
2939 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2942 // Build the window tool bar
2943 private void setupToolBar() {
2944 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2945 toolBar = addToolBar(tr("Tool Bar"));
2946 toolBar.setObjectName("toolBar");
2947 menuBar.setupToolBarVisible();
2948 if (!Global.isWindowVisible("toolBar"))
2949 toolBar.setVisible(false);
2951 toolBar.setVisible(true);
2953 // toolBar.addWidget(menuBar);
2954 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2955 // toolBar.addSeparator();
2956 prevButton = toolBar.addAction(tr("Previous"));
2957 QIcon prevIcon = new QIcon(iconPath+"back.png");
2958 prevButton.setIcon(prevIcon);
2959 prevButton.triggered.connect(this, "previousViewedAction()");
2960 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2962 nextButton = toolBar.addAction(tr("Next"));
2963 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2964 nextButton.setIcon(nextIcon);
2965 nextButton.triggered.connect(this, "nextViewedAction()");
2966 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2968 upButton = toolBar.addAction(tr("Up"));
2969 QIcon upIcon = new QIcon(iconPath+"up.png");
2970 upButton.setIcon(upIcon);
2971 upButton.triggered.connect(this, "upAction()");
2972 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2975 downButton = toolBar.addAction(tr("Down"));
2976 QIcon downIcon = new QIcon(iconPath+"down.png");
2977 downButton.setIcon(downIcon);
2978 downButton.triggered.connect(this, "downAction()");
2979 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2981 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2982 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2983 synchronizeIconAngle = 0;
2984 synchronizeButton.triggered.connect(this, "evernoteSync()");
2985 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2987 printButton = toolBar.addAction(tr("Print"));
2988 QIcon printIcon = new QIcon(iconPath+"print.png");
2989 printButton.setIcon(printIcon);
2990 printButton.triggered.connect(this, "printNote()");
2991 togglePrintButton(Global.isToolbarButtonVisible("print"));
2993 tagButton = toolBar.addAction(tr("Tag"));
2994 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2995 tagButton.setIcon(tagIcon);
2996 tagButton.triggered.connect(browserWindow, "modifyTags()");
2997 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2999 attributeButton = toolBar.addAction(tr("Attributes"));
3000 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
3001 attributeButton.setIcon(attributeIcon);
3002 attributeButton.triggered.connect(this, "toggleNoteInformation()");
3003 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
3005 emailButton = toolBar.addAction(tr("Email"));
3006 QIcon emailIcon = new QIcon(iconPath+"email.png");
3007 emailButton.setIcon(emailIcon);
3008 emailButton.triggered.connect(this, "emailNote()");
3009 toggleEmailButton(Global.isToolbarButtonVisible("email"));
3011 deleteButton = toolBar.addAction(tr("Delete"));
3012 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
3013 deleteButton.setIcon(deleteIcon);
3014 deleteButton.triggered.connect(this, "deleteNote()");
3015 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
3017 newButton = toolBar.addAction(tr("New"));
3018 QIcon newIcon = new QIcon(iconPath+"new.png");
3019 newButton.triggered.connect(this, "addNote()");
3020 newButton.setIcon(newIcon);
3021 toggleNewButton(Global.isToolbarButtonVisible("new"));
3023 allNotesButton = toolBar.addAction(tr("All Notes"));
3024 QIcon allIcon = new QIcon(iconPath+"books.png");
3025 allNotesButton.triggered.connect(this, "allNotes()");
3026 allNotesButton.setIcon(allIcon);
3027 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
3029 //toolBar.addSeparator();
3030 //toolBar.addWidget(new QLabel(tr("Quota:")));
3031 //toolBar.addWidget(quotaBar);
3032 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
3034 //toolBar.addSeparator();
3036 //toolBar.addWidget(new QLabel(tr("Zoom")));
3037 //toolBar.addWidget(zoomSpinner);
3039 //toolBar.addWidget(new QLabel(" "));
3040 //toolBar.addSeparator();
3041 //toolBar.addWidget(new QLabel(tr(" Search:")));
3042 //toolBar.addWidget(searchField);
3043 QSizePolicy sizePolicy = new QSizePolicy();
3044 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
3045 QLabel spacer = new QLabel("");
3046 spacer.setSizePolicy(sizePolicy);
3047 toolBar.addWidget(spacer);
3048 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3050 //searchClearButton = toolBar.addAction("Search Clear");
3051 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3052 //searchClearButton.setIcon(searchClearIcon);
3053 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3054 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3056 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3058 // Update the sychronize button picture
3060 public QMenu createPopupMenu() {
3061 QMenu contextMenu = super.createPopupMenu();
3063 contextMenu.addSeparator();
3064 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3065 contextMenu.addAction(prevAction);
3066 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3068 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3069 contextMenu.addAction(nextAction);
3070 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3072 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3073 contextMenu.addAction(upAction);
3074 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3076 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3077 contextMenu.addAction(downAction);
3078 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3080 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3081 contextMenu.addAction(synchronizeAction);
3082 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3084 QAction printAction = addContextAction("print", tr("Print"));
3085 contextMenu.addAction(printAction);
3086 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3088 QAction tagAction = addContextAction("tag", tr("Tag"));
3089 contextMenu.addAction(tagAction);
3090 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3092 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3093 contextMenu.addAction(attributeAction);
3094 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3096 QAction emailAction = addContextAction("email", tr("Email"));
3097 contextMenu.addAction(emailAction);
3098 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3100 QAction deleteAction = addContextAction("delete", tr("Delete"));
3101 contextMenu.addAction(deleteAction);
3102 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3104 QAction newAction = addContextAction("new", tr("Add"));
3105 contextMenu.addAction(newAction);
3106 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3108 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3109 contextMenu.addAction(allNotesAction);
3110 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3112 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3113 contextMenu.addAction(searchClearAction);
3114 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3119 private QAction addContextAction(String config, String name) {
3120 QAction newAction = new QAction(this);
3121 newAction.setText(name);
3122 newAction.setCheckable(true);
3123 newAction.setChecked(Global.isToolbarButtonVisible(config));
3126 private void togglePrevArrowButton(Boolean toggle) {
3127 prevButton.setVisible(toggle);
3128 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3130 private void toggleNextArrowButton(Boolean toggle) {
3131 nextButton.setVisible(toggle);
3132 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3134 private void toggleUpArrowButton(Boolean toggle) {
3135 upButton.setVisible(toggle);
3136 Global.saveToolbarButtonsVisible("upArrow", toggle);
3138 private void toggleDownArrowButton(Boolean toggle) {
3139 downButton.setVisible(toggle);
3140 Global.saveToolbarButtonsVisible("downArrow", toggle);
3142 private void toggleSynchronizeButton(Boolean toggle) {
3143 synchronizeButton.setVisible(toggle);
3144 Global.saveToolbarButtonsVisible("synchronize", toggle);
3146 private void togglePrintButton(Boolean toggle) {
3147 printButton.setVisible(toggle);
3148 Global.saveToolbarButtonsVisible("print", toggle);
3150 private void toggleTagButton(Boolean toggle) {
3151 tagButton.setVisible(toggle);
3152 Global.saveToolbarButtonsVisible("tag", toggle);
3154 private void toggleAttributeButton(Boolean toggle) {
3155 attributeButton.setVisible(toggle);
3156 Global.saveToolbarButtonsVisible("attribute", toggle);
3158 private void toggleEmailButton(Boolean toggle) {
3159 emailButton.setVisible(toggle);
3160 Global.saveToolbarButtonsVisible("email", toggle);
3162 private void toggleDeleteButton(Boolean toggle) {
3163 deleteButton.setVisible(toggle);
3164 Global.saveToolbarButtonsVisible("delete", toggle);
3166 private void toggleNewButton(Boolean toggle) {
3167 newButton.setVisible(toggle);
3168 Global.saveToolbarButtonsVisible("new", toggle);
3170 private void toggleAllNotesButton(Boolean toggle) {
3171 allNotesButton.setVisible(toggle);
3172 Global.saveToolbarButtonsVisible("allNotes", toggle);
3174 @SuppressWarnings("unused")
3175 private void toggleSearchClearButton(Boolean toggle) {
3176 searchClearButton.setVisible(toggle);
3177 Global.saveToolbarButtonsVisible("searchClear", toggle);
3184 @SuppressWarnings("unused")
3185 private void updateSyncButton() {
3187 if (syncIcons == null) {
3188 syncIcons = new ArrayList<QPixmap>();
3190 synchronizeIconAngle = 0;
3191 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3193 for (int i=0; i<=360; i++) {
3194 QPixmap rotatedPix = new QPixmap(pix.size());
3195 QPainter p = new QPainter(rotatedPix);
3196 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3197 QSize size = pix.size();
3198 p.translate(size.width()/2, size.height()/2);
3201 p.setBackgroundMode(BGMode.OpaqueMode);
3202 p.translate(-size.width()/2, -size.height()/2);
3203 p.drawPixmap(0,0, pix);
3205 syncIcons.add(rotatedPix);
3209 synchronizeIconAngle++;
3210 if (synchronizeIconAngle > 359)
3211 synchronizeIconAngle=0;
3212 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3215 // Synchronize with Evernote
3217 private void evernoteSync() {
3218 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3219 if (!Global.isConnected)
3221 if (Global.isConnected)
3222 synchronizeAnimationTimer.start(5);
3223 // synchronizeAnimationTimer.start(200);
3225 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3227 private void updateQuotaBar() {
3228 long limit = Global.getUploadLimit();
3229 long amount = Global.getUploadAmount();
3230 if (amount>0 && limit>0) {
3231 int percent =(int)(amount*100/limit);
3232 quotaBar.setValue(percent);
3234 quotaBar.setValue(0);
3237 @SuppressWarnings("unused")
3238 private void zoomChanged() {
3239 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3242 //****************************************************************
3243 //****************************************************************
3244 //* System Tray functions
3245 //****************************************************************
3246 //****************************************************************
3247 private void trayToggleVisible() {
3252 if (windowMaximized)
3259 @SuppressWarnings("unused")
3260 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3261 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3262 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3263 trayToggleVisible();
3268 //***************************************************************
3269 //***************************************************************
3270 //** These functions deal with the trash tree
3271 //***************************************************************
3272 //***************************************************************
3273 // Setup the tree containing the trash.
3274 @SuppressWarnings("unused")
3275 private void trashTreeSelection() {
3276 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3278 clearNotebookFilter();
3280 clearAttributeFilter();
3281 clearSavedSearchFilter();
3283 String tempGuid = currentNoteGuid;
3285 // currentNoteGuid = "";
3286 currentNote = new Note();
3287 selectedNoteGUIDs.clear();
3288 listManager.getSelectedNotebooks().clear();
3289 listManager.getSelectedTags().clear();
3290 listManager.setSelectedSavedSearch("");
3291 browserWindow.clear();
3293 // toggle the add buttons
3294 newButton.setEnabled(!newButton.isEnabled());
3295 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3296 menuBar.noteAdd.setVisible(true);
3298 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3299 if (selections.size() == 0) {
3300 currentNoteGuid = trashNoteGuid;
3301 trashNoteGuid = tempGuid;
3302 Global.showDeleted = false;
3303 menuBar.noteRestoreAction.setEnabled(false);
3304 menuBar.noteRestoreAction.setVisible(false);
3307 trashNoteGuid = tempGuid;
3308 currentNoteGuid = trashNoteGuid;
3309 menuBar.noteRestoreAction.setEnabled(true);
3310 menuBar.noteRestoreAction.setVisible(true);
3311 Global.showDeleted = true;
3313 listManager.loadNotesIndex();
3314 noteIndexUpdated(false);
3315 //// browserWindow.setEnabled(newButton.isEnabled());
3316 browserWindow.setReadOnly(!newButton.isEnabled());
3317 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3319 // Empty the trash file
3320 @SuppressWarnings("unused")
3321 private void emptyTrash() {
3322 // browserWindow.clear();
3323 logger.log(logger.EXTREME, "Emptying Trash");
3324 listManager.emptyTrash();
3325 logger.log(logger.EXTREME, "Resetting view after trash empty");
3326 if (trashTree.selectedItems().size() > 0) {
3327 listManager.getSelectedNotebooks().clear();
3328 listManager.getSelectedTags().clear();
3329 listManager.setSelectedSavedSearch("");
3330 newButton.setEnabled(!newButton.isEnabled());
3331 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3332 menuBar.noteAdd.setVisible(true);
3333 browserWindow.clear();
3336 clearNotebookFilter();
3337 clearSavedSearchFilter();
3338 clearAttributeFilter();
3340 Global.showDeleted = false;
3341 menuBar.noteRestoreAction.setEnabled(false);
3342 menuBar.noteRestoreAction.setVisible(false);
3344 listManager.loadNotesIndex();
3345 noteIndexUpdated(false);
3348 // Show/Hide trash window
3349 @SuppressWarnings("unused")
3350 private void toggleTrashWindow() {
3351 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3352 if (trashTree.isVisible())
3356 menuBar.hideTrash.setChecked(trashTree.isVisible());
3358 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3359 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3361 private void clearTrashFilter() {
3362 Global.showDeleted = false;
3363 newButton.setEnabled(true);
3364 menuBar.noteAdd.setEnabled(true);
3365 menuBar.noteAdd.setVisible(true);
3366 trashTree.blockSignals(true);
3367 trashTree.clearSelection();
3368 trashTree.blockSignals(false);
3373 //***************************************************************
3374 //***************************************************************
3375 //** These functions deal with connection settings
3376 //***************************************************************
3377 //***************************************************************
3378 // SyncRunner had a problem and things are disconnected
3379 @SuppressWarnings("unused")
3380 private void remoteErrorDisconnect() {
3381 menuBar.connectAction.setText(tr("Connect"));
3382 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3383 menuBar.synchronizeAction.setEnabled(false);
3384 Global.isConnected = false;
3385 synchronizeAnimationTimer.stop();
3388 // Do a manual connect/disconnect
3389 private void remoteConnect() {
3391 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3393 // If we are already connected, we just disconnect
3394 if (Global.isConnected) {
3395 Global.isConnected = false;
3396 syncRunner.enDisconnect();
3397 setupConnectMenuOptions();
3402 OAuthTokenizer tokenizer = new OAuthTokenizer();
3403 AESEncrypter aes = new AESEncrypter();
3405 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("oauth.txt")));
3406 } catch (FileNotFoundException e) {
3407 // File not found, so we'll just get empty strings anyway.
3411 if (Global.getProxyValue("url").equals("")) {
3412 System.setProperty("http.proxyHost","") ;
3413 System.setProperty("http.proxyPort", "") ;
3414 System.setProperty("https.proxyHost","") ;
3415 System.setProperty("https.proxyPort", "") ;
3418 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3419 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3420 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3421 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3423 if (Global.getProxyValue("userid").equals("")) {
3424 Authenticator.setDefault(new Authenticator() {
3426 protected PasswordAuthentication getPasswordAuthentication() {
3428 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3434 syncRunner.userStoreUrl = Global.userStoreUrl;
3435 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3436 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3440 String authString = aes.getString();
3441 if (!authString.equals("")) {
3442 tokenizer.tokenize(authString);
3443 syncRunner.authToken = tokenizer.oauth_token;
3444 syncRunner.enConnect();
3447 Global.isConnected = syncRunner.isConnected;
3449 if (!Global.isConnected) {
3450 OAuthWindow window = new OAuthWindow(logger);
3452 setMessage(window.errorMessage);
3457 setMessage(window.errorMessage);
3460 tokenizer.tokenize(window.response);
3461 if (tokenizer.oauth_token.equals("")) {
3462 setMessage(tr("Invalid authorization token received."));
3465 aes.setString(window.response);
3467 aes.encrypt(new FileOutputStream(Global.getFileManager().getHomeDirFile("oauth.txt")));
3468 } catch (FileNotFoundException e) {
3469 // TODO Auto-generated catch block
3470 e.printStackTrace();
3472 syncRunner.authToken = tokenizer.oauth_token;
3473 syncRunner.enConnect();
3474 Global.isConnected = syncRunner.isConnected;
3476 Global.username = syncRunner.username;
3478 if (!Global.isConnected)
3481 setupConnectMenuOptions();
3482 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3486 private void setupConnectMenuOptions() {
3487 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3488 if (!Global.isConnected) {
3489 menuBar.connectAction.setText(tr("Connect"));
3490 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3491 menuBar.synchronizeAction.setEnabled(false);
3493 menuBar.connectAction.setText(tr("Disconnect"));
3494 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3495 menuBar.synchronizeAction.setEnabled(true);
3497 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3502 //***************************************************************
3503 //***************************************************************
3504 //** These functions deal with the GUI Attribute tree
3505 //***************************************************************
3506 //***************************************************************
3507 @SuppressWarnings("unused")
3508 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3510 // clearTagFilter();
3511 // clearNotebookFilter();
3513 // clearSavedSearchFilter();
3515 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3516 if (item.childCount() > 0) {
3517 item.setSelected(false);
3519 Global.createdBeforeFilter.reset();
3520 Global.createdSinceFilter.reset();
3521 Global.changedBeforeFilter.reset();
3522 Global.changedSinceFilter.reset();
3523 Global.containsFilter.reset();
3524 attributeTreeSelected = item;
3525 DateAttributeFilterTable f = null;
3526 f = findDateAttributeFilterTable(item.parent());
3528 f.select(item.parent().indexOfChild(item));
3530 Global.containsFilter.select(item.parent().indexOfChild(item));
3533 listManager.loadNotesIndex();
3534 noteIndexUpdated(false);
3537 attributeTreeSelected = null;
3538 item.setSelected(false);
3539 Global.createdBeforeFilter.reset();
3540 Global.createdSinceFilter.reset();
3541 Global.changedBeforeFilter.reset();
3542 Global.changedSinceFilter.reset();
3543 Global.containsFilter.reset();
3544 listManager.loadNotesIndex();
3545 noteIndexUpdated(false);
3547 // This determines what attribute filter we need, depending upon the selection
3548 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3549 if (w.parent() != null && w.childCount() > 0) {
3550 QTreeWidgetItem parent = w.parent();
3551 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3552 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3553 return Global.createdSinceFilter;
3554 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3555 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3556 return Global.createdBeforeFilter;
3557 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3558 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3559 return Global.changedSinceFilter;
3560 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3561 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3562 return Global.changedBeforeFilter;
3567 // Show/Hide attribute search window
3568 @SuppressWarnings("unused")
3569 private void toggleAttributesWindow() {
3570 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3571 if (attributeTree.isVisible())
3572 attributeTree.hide();
3574 attributeTree.show();
3575 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3577 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3578 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3580 private void clearAttributeFilter() {
3581 Global.createdBeforeFilter.reset();
3582 Global.createdSinceFilter.reset();
3583 Global.changedBeforeFilter.reset();
3584 Global.changedSinceFilter.reset();
3585 Global.containsFilter.reset();
3586 attributeTreeSelected = null;
3587 attributeTree.blockSignals(true);
3588 attributeTree.clearSelection();
3589 attributeTree.blockSignals(false);
3593 //***************************************************************
3594 //***************************************************************
3595 //** These functions deal with the GUI Note index table
3596 //***************************************************************
3597 //***************************************************************
3598 // Initialize the note list table
3599 private void initializeNoteTable() {
3600 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3601 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3602 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3603 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3605 // Show/Hide trash window
3606 @SuppressWarnings("unused")
3607 private void toggleNoteListWindow() {
3608 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3609 if (noteTableView.isVisible())
3610 noteTableView.hide();
3612 noteTableView.show();
3613 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3615 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3616 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3618 // Handle the event that a user selects a note from the table
3619 @SuppressWarnings("unused")
3620 private void noteTableSelection() {
3621 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3625 // If we have more than one selection, then set the merge note action to true.
3626 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3627 if (selections.size() > 1)
3628 menuBar.noteMergeAction.setEnabled(true);
3630 menuBar.noteMergeAction.setEnabled(false);
3632 // If the ctrl key is pressed, then they are selecting multiple
3633 // entries and we don't want to change the currently viewed note.
3634 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3635 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3638 if (historyGuids.size() == 0) {
3639 historyGuids.add(currentNoteGuid);
3640 historyPosition = 1;
3642 noteTableView.showColumn(Global.noteTableGuidPosition);
3644 if (!Global.isColumnVisible("guid"))
3645 noteTableView.hideColumn(Global.noteTableGuidPosition);
3647 if (selections.size() > 0) {
3649 menuBar.noteDuplicateAction.setEnabled(true);
3650 menuBar.noteOnlineHistoryAction.setEnabled(true);
3651 menuBar.noteMergeAction.setEnabled(true);
3652 selectedNoteGUIDs.clear();
3653 if (selections.size() != 1 || Global.showDeleted) {
3654 menuBar.noteDuplicateAction.setEnabled(false);
3656 if (selections.size() != 1 || !Global.isConnected) {
3657 menuBar.noteOnlineHistoryAction.setEnabled(false);
3659 if (selections.size() == 1) {
3660 menuBar.noteMergeAction.setEnabled(false);
3662 for (int i=0; i<selections.size(); i++) {
3663 int row = selections.get(i).row();
3665 upButton.setEnabled(false);
3667 upButton.setEnabled(true);
3668 if (row < listManager.getNoteTableModel().rowCount()-1)
3669 downButton.setEnabled(true);
3671 downButton.setEnabled(false);
3672 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3673 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3674 currentNoteGuid = (String)ix.values().toArray()[0];
3675 selectedNoteGUIDs.add(currentNoteGuid);
3679 nextButton.setEnabled(true);
3680 prevButton.setEnabled(true);
3682 int endPosition = historyGuids.size()-1;
3683 for (int j=historyPosition; j<=endPosition; j++) {
3684 historyGuids.remove(historyGuids.size()-1);
3686 historyGuids.add(currentNoteGuid);
3687 historyPosition = historyGuids.size();
3689 if (historyPosition <= 1)
3690 prevButton.setEnabled(false);
3691 if (historyPosition == historyGuids.size())
3692 nextButton.setEnabled(false);
3694 fromHistory = false;
3695 scrollToGuid(currentNoteGuid);
3696 refreshEvernoteNote(true);
3697 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3699 // Trigger a refresh when the note db has been updated
3700 private void noteIndexUpdated(boolean reload) {
3701 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3703 refreshEvernoteNoteList();
3704 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3705 noteTableView.load(reload);
3706 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3708 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3709 pos = noteTableView.proxyModel.rowCount();
3712 if (noteTableView.proxyModel.rowCount() == 0)
3715 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3717 currentNoteGuid = (String)i.data();
3721 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3723 scrollToGuid(currentNoteGuid);
3724 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3726 // Called when the list of notes is updated
3727 private void refreshEvernoteNoteList() {
3728 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3729 browserWindow.setDisabled(false);
3730 if (selectedNoteGUIDs == null)
3731 selectedNoteGUIDs = new ArrayList<String>();
3732 selectedNoteGUIDs.clear(); // clear out old entries
3734 String saveCurrentNoteGuid = new String();
3735 String tempNoteGuid = new String();
3737 historyGuids.clear();
3738 historyPosition = 0;
3739 prevButton.setEnabled(false);
3740 nextButton.setEnabled(false);
3742 if (currentNoteGuid == null)
3743 currentNoteGuid = new String();
3745 //determine current note guid
3746 for (Note note : listManager.getNoteIndex()) {
3747 tempNoteGuid = note.getGuid();
3748 if (currentNoteGuid.equals(tempNoteGuid)) {
3749 saveCurrentNoteGuid = tempNoteGuid;
3753 if (listManager.getNoteIndex().size() == 0) {
3754 currentNoteGuid = "";
3756 browserWindow.clear();
3757 browserWindow.setDisabled(true);
3760 if (Global.showDeleted && listManager.getNotebookIndex().size() > 0 && saveCurrentNoteGuid.equals("")) {
3761 currentNoteGuid = listManager.getNoteIndex().get(0).getGuid();
3762 saveCurrentNoteGuid = currentNoteGuid;
3763 refreshEvernoteNote(true);
3766 if (!saveCurrentNoteGuid.equals("")) {
3767 refreshEvernoteNote(false);
3769 currentNoteGuid = "";
3771 reloadTagTree(false);
3773 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3775 // Called when the previous arrow button is clicked
3776 @SuppressWarnings("unused")
3777 private void previousViewedAction() {
3778 if (!prevButton.isEnabled())
3780 if (historyPosition == 0)
3783 if (historyPosition <= 0)
3785 String historyGuid = historyGuids.get(historyPosition-1);
3787 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3788 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3789 if (modelIndex != null) {
3790 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3791 String tableGuid = (String)ix.values().toArray()[0];
3792 if (tableGuid.equals(historyGuid)) {
3793 noteTableView.selectRow(i);
3799 @SuppressWarnings("unused")
3800 private void nextViewedAction() {
3801 if (!nextButton.isEnabled())
3803 String historyGuid = historyGuids.get(historyPosition);
3806 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3807 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3808 if (modelIndex != null) {
3809 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3810 String tableGuid = (String)ix.values().toArray()[0];
3811 if (tableGuid.equals(historyGuid)) {
3812 noteTableView.selectRow(i);
3818 // Called when the up arrow is clicked
3819 @SuppressWarnings("unused")
3820 private void upAction() {
3821 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3822 int row = selections.get(0).row();
3824 noteTableView.selectRow(row-1);
3827 // Called when the down arrow is clicked
3828 @SuppressWarnings("unused")
3829 private void downAction() {
3830 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3831 int row = selections.get(0).row();
3832 int max = listManager.getNoteTableModel().rowCount();
3834 noteTableView.selectRow(row+1);
3837 // Update a tag string for a specific note in the list
3838 @SuppressWarnings("unused")
3839 private void updateListTags(String guid, List<String> tags) {
3840 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3841 StringBuffer tagBuffer = new StringBuffer();
3842 for (int i=0; i<tags.size(); i++) {
3843 tagBuffer.append(tags.get(i));
3844 if (i<tags.size()-1)
3845 tagBuffer.append(", ");
3848 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3849 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3850 if (modelIndex != null) {
3851 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3852 String tableGuid = (String)ix.values().toArray()[0];
3853 if (tableGuid.equals(guid)) {
3854 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3855 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3856 noteTableView.proxyModel.invalidate();
3861 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3863 // Update a title for a specific note in the list
3864 @SuppressWarnings("unused")
3865 private void updateListAuthor(String guid, String author) {
3866 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3868 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3869 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3870 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3871 if (modelIndex != null) {
3872 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3873 String tableGuid = (String)ix.values().toArray()[0];
3874 if (tableGuid.equals(guid)) {
3875 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3876 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3877 noteTableView.proxyModel.invalidate();
3883 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3885 private void updateListNoteNotebook(String guid, String notebook) {
3886 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3887 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3888 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3890 // Update a title for a specific note in the list
3891 @SuppressWarnings("unused")
3892 private void updateListSourceUrl(String guid, String url) {
3893 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3895 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3896 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3897 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3898 if (modelIndex != null) {
3899 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3900 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3901 String tableGuid = (String)ix.values().toArray()[0];
3902 if (tableGuid.equals(guid)) {
3903 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3904 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3905 noteTableView.proxyModel.invalidate();
3910 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3912 @SuppressWarnings("unused")
3913 private void updateListGuid(String oldGuid, String newGuid) {
3914 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3916 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3917 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3918 if (modelIndex != null) {
3919 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3920 String tableGuid = (String)ix.values().toArray()[0];
3921 if (tableGuid.equals(oldGuid)) {
3922 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3923 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3928 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3930 private void updateListTagName(String guid) {
3931 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3933 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3934 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3935 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3937 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3938 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3939 if (modelIndex != null) {
3940 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3941 String noteGuid = (String)ix.values().toArray()[0];
3942 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3943 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3944 i=listManager.getNoteTableModel().rowCount();
3950 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3952 private void removeListTagName(String guid) {
3953 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3955 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3956 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3957 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3958 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3959 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3962 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3963 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3964 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3965 if (modelIndex != null) {
3966 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3967 String noteGuid = (String)ix.values().toArray()[0];
3968 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3969 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3970 i=listManager.getNoteTableModel().rowCount();
3976 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3978 private void updateListNotebookName(String oldName, String newName) {
3979 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3981 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3982 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3983 if (modelIndex != null) {
3984 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3985 String tableName = (String)ix.values().toArray()[0];
3986 if (tableName.equalsIgnoreCase(oldName)) {
3987 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3991 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3993 @SuppressWarnings("unused")
3994 private void updateListDateCreated(String guid, QDateTime date) {
3995 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3997 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3998 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3999 if (modelIndex != null) {
4000 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4001 String tableGuid = (String)ix.values().toArray()[0];
4002 if (tableGuid.equals(guid)) {
4003 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4004 noteTableView.proxyModel.invalidate();
4009 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
4011 @SuppressWarnings("unused")
4012 private void updateListDateSubject(String guid, QDateTime date) {
4013 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
4015 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4016 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4017 if (modelIndex != null) {
4018 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4019 String tableGuid = (String)ix.values().toArray()[0];
4020 if (tableGuid.equals(guid)) {
4021 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4022 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4023 noteTableView.proxyModel.invalidate();
4028 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
4030 private void updateListDateChanged(String guid, QDateTime date) {
4031 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
4033 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4034 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4035 if (modelIndex != null) {
4036 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4037 String tableGuid = (String)ix.values().toArray()[0];
4038 if (tableGuid.equals(guid)) {
4039 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4040 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4045 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4047 private void updateListDateChanged() {
4048 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
4049 QDateTime date = new QDateTime(QDateTime.currentDateTime());
4050 updateListDateChanged(currentNoteGuid, date);
4051 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4054 private void scrollToCurrentGuid() {
4055 //scrollToGuid(currentNoteGuid);
4056 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
4057 if (selections.size() == 0)
4059 QModelIndex index = selections.get(0);
4060 int row = selections.get(0).row();
4061 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
4064 // Scroll to the current GUID in tthe list.
4065 // Scroll to a particular index item
4066 private void scrollToGuid(String guid) {
4067 if (currentNote == null || guid == null)
4069 if (currentNote.isActive() && Global.showDeleted) {
4070 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4071 if (!listManager.getNoteIndex().get(i).isActive()) {
4072 currentNote = listManager.getNoteIndex().get(i);
4073 currentNoteGuid = currentNote.getGuid();
4074 i = listManager.getNoteIndex().size();
4078 if (!currentNote.isActive() && !Global.showDeleted) {
4079 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4080 if (listManager.getNoteIndex().get(i).isActive()) {
4081 currentNote = listManager.getNoteIndex().get(i);
4082 currentNoteGuid = currentNote.getGuid();
4083 i = listManager.getNoteIndex().size();
4088 for (int i=0; i<noteTableView.model().rowCount(); i++) {
4089 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4090 if (currentNoteGuid.equals(index.data())) {
4091 // noteTableView.selectionModel().blockSignals(true);
4092 noteTableView.selectRow(i);
4093 // noteTableView.selectionModel().blockSignals(false);
4094 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
4095 i=listManager.getNoteTableModel().rowCount();
4098 noteTableView.repaint();
4100 // Show/Hide columns
4101 private void showColumns() {
4102 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4103 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4104 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4105 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4106 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4107 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4108 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4109 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4110 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4111 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4112 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4113 noteTableView.setColumnHidden(Global.noteTablePinnedPosition, !Global.isColumnVisible("pinned"));
4115 // Title color has changed
4116 @SuppressWarnings("unused")
4117 private void titleColorChanged(Integer color) {
4118 logger.log(logger.HIGH, "Entering NeverNote.titleColorChanged");
4121 QColor backgroundColor = new QColor();
4122 QColor foregroundColor = new QColor(QColor.black);
4123 backgroundColor.setRgb(color);
4125 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4126 foregroundColor.setRgb(QColor.white.rgb());
4128 if (selectedNoteGUIDs.size() == 0)
4129 selectedNoteGUIDs.add(currentNoteGuid);
4131 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4132 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4133 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4134 if (modelIndex != null) {
4135 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4136 String tableGuid = (String)ix.values().toArray()[0];
4137 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4138 for (int k=0; k<Global.noteTableColumnCount; k++) {
4139 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4140 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4141 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4143 i=listManager.getNoteTableModel().rowCount();
4148 logger.log(logger.HIGH, "Leaving NeverNote.titleColorChanged");
4150 // A note has been pinned or unpinned
4151 @SuppressWarnings("unused")
4152 private void notePinned() {
4153 logger.log(logger.EXTREME, "Entering NeverNote.notePinned()");
4156 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4157 NoteMetadata meta = listManager.getNoteMetadata().get(selectedNoteGUIDs.get(j));
4158 boolean pinned = !meta.isPinned();
4159 meta.setPinned(pinned); // Toggle the pinned/unpinned
4161 // Update the list & table
4162 listManager.updateNoteMetadata(meta);
4163 noteTableView.proxyModel.addGuid(selectedNoteGUIDs.get(j), meta);
4166 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4168 // Wide list was chosen
4169 public void narrowListView() {
4170 saveNoteColumnPositions();
4171 saveNoteIndexWidth();
4173 int sortCol = noteTableView.proxyModel.sortColumn();
4174 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4175 Global.setSortColumn(sortCol);
4176 Global.setSortOrder(sortOrder);
4178 Global.setListView(Global.View_List_Narrow);
4180 menuBar.wideListView.blockSignals(true);
4181 menuBar.narrowListView.blockSignals(true);
4183 menuBar.wideListView.setChecked(false);
4184 menuBar.narrowListView.setChecked(true);
4186 menuBar.wideListView.blockSignals(false);
4187 menuBar.narrowListView.blockSignals(false);
4189 mainLeftRightSplitter.addWidget(noteTableView);
4190 mainLeftRightSplitter.addWidget(browserWindow);
4191 restoreWindowState(false);
4192 noteTableView.repositionColumns();
4193 noteTableView.resizeColumnWidths();
4194 noteTableView.resizeRowHeights();
4196 sortCol = Global.getSortColumn();
4197 sortOrder = Global.getSortOrder();
4198 noteTableView.proxyModel.blocked = true;
4199 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4200 noteTableView.proxyModel.blocked = false;
4204 noteTableView.load(false);
4205 refreshEvernoteNote(true);
4206 scrollToCurrentGuid();
4208 public void wideListView() {
4209 int sortCol = noteTableView.proxyModel.sortColumn();
4210 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4211 Global.setSortColumn(sortCol);
4212 Global.setSortOrder(sortOrder);
4215 saveNoteColumnPositions();
4216 saveNoteIndexWidth();
4217 Global.setListView(Global.View_List_Wide);
4219 menuBar.wideListView.blockSignals(true);
4220 menuBar.narrowListView.blockSignals(true);
4222 menuBar.wideListView.setChecked(true);
4223 menuBar.narrowListView.setChecked(false);
4225 menuBar.wideListView.blockSignals(false);
4226 menuBar.narrowListView.blockSignals(false);
4227 browserIndexSplitter.setVisible(true);
4228 browserIndexSplitter.addWidget(noteTableView);
4229 browserIndexSplitter.addWidget(browserWindow);
4230 restoreWindowState(false);
4231 noteTableView.repositionColumns();
4232 noteTableView.resizeColumnWidths();
4233 noteTableView.resizeRowHeights();
4235 sortCol = Global.getSortColumn();
4236 sortOrder = Global.getSortOrder();
4237 noteTableView.proxyModel.blocked = true;
4238 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4239 noteTableView.proxyModel.blocked = false;
4242 noteTableView.load(false);
4243 scrollToCurrentGuid();
4245 // Sort order for the notebook has changed
4246 public void tableSortOrderChanged(Integer column, Integer order) {
4248 // Find what notebook (if any) is selected. We ignore stacks & the "All Notebooks".
4249 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4250 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4251 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4253 notebook = currentSelectedNotebook.text(2);
4254 conn.getNotebookTable().setSortOrder(notebook, column, order);
4258 //***************************************************************
4259 @SuppressWarnings("unused")
4260 private void evernoteLinkClick(String syncGuid, String locGuid) {
4262 if (conn.getNoteTable().guidExists(syncGuid)) {
4265 // If we didn't find it via the synchronized guid, look under the local guid
4266 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4267 // later synchronized (that causes the guid to change so we need to find the new one).
4268 if (conn.getNoteTable().guidExists(locGuid))
4271 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4274 openExternalEditor(guid);
4278 //If we've gotten this far, we can't find the note
4279 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4280 " seem to find that note."));
4282 //***************************************************************
4283 //***************************************************************
4284 //** External editor window functions
4285 //***************************************************************
4286 //***************************************************************
4287 private void listDoubleClick() {
4289 openExternalEditor(currentNoteGuid);
4291 private void openExternalEditor(String guid) {
4293 if (externalWindows.containsKey(guid)) {
4294 externalWindows.get(guid).raise();
4297 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4298 // We have a new external editor to create
4299 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4300 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4301 newBrowser.setWindowIcon(appIcon);
4302 externalWindows.put(guid, newBrowser);
4303 showEditorButtons(newBrowser.getBrowserWindow());
4304 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4305 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4306 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4307 //newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4308 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4309 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4310 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4311 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4313 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4314 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4315 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4319 @SuppressWarnings({ "rawtypes", "unused" })
4320 private void externalWindowTagsEdited(String guid, List values) {
4321 StringBuffer line = new StringBuffer(100);
4322 for (int i=0; i<values.size(); i++) {
4324 line.append(Global.tagDelimeter+" ");
4325 line.append(values.get(i));
4327 if (guid.equals(currentNoteGuid)) {
4328 browserWindow.setTag(line.toString());
4331 @SuppressWarnings("unused")
4332 private void externalWindowClosing(String guid) {
4333 externalWindows.remove(guid);
4338 //***************************************************************
4339 //***************************************************************
4340 //** These functions deal with Note specific things
4341 //***************************************************************
4342 //***************************************************************
4343 private void setNoteDirty() {
4344 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4346 // Find if the note is being edited externally. If it is, update it.
4347 if (externalWindows.containsKey(currentNoteGuid)) {
4348 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4349 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4350 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4351 window.getBrowserWindow().setContent(unicode);
4354 // If the note is dirty, then it is unsynchronized by default.
4358 // Set the note as dirty and check if its status is synchronized in the display table
4360 if (listManager.getNoteMetadata().containsKey(currentNoteGuid) &&
4361 listManager.getNoteMetadata().get(currentNoteGuid).isDirty()) {
4365 // If this wasn't already marked as unsynchronized, then we need to update the table
4366 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4367 // listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4368 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4369 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4370 if (modelIndex != null) {
4371 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4372 String tableGuid = (String)ix.values().toArray()[0];
4373 if (tableGuid.equals(currentNoteGuid)) {
4374 listManager.getNoteTableModel().proxyModel.setData(i, Global.noteTableSynchronizedPosition, "false");
4380 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4382 @SuppressWarnings("unused")
4383 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4384 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4385 QByteArray unicode = codec.fromUnicode(content);
4386 noteCache.remove(guid);
4387 noteCache.put(guid, unicode.toString());
4388 if (guid.equals(currentNoteGuid)) {
4390 browserWindow.setContent(unicode);
4393 thumbnailRunner.addWork("GENERATE "+ guid);
4394 saveNote(guid, browser);
4398 private void saveNote() {
4400 saveNote(currentNoteGuid, browserWindow);
4401 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4405 private void saveNote(String guid, BrowserWindow window) {
4406 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4409 logger.log(logger.EXTREME, "Saving to cache");
4410 QTextCodec codec = QTextCodec.codecForLocale();
4411 // QTextDecoder decoder = codec.makeDecoder();
4412 codec = QTextCodec.codecForName("UTF-8");
4413 QByteArray unicode = codec.fromUnicode(window.getContent());
4414 noteCache.put(guid, unicode.toString());
4416 logger.log(logger.EXTREME, "updating list manager");
4417 listManager.updateNoteContent(guid, window.getContent());
4418 logger.log(logger.EXTREME, "Updating title");
4419 listManager.updateNoteTitle(guid, window.getTitle());
4420 updateListDateChanged();
4422 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4423 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4424 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4425 currentNote = listManager.getNoteIndex().get(i);
4426 i = listManager.getNoteIndex().size();
4431 // Get a note from Evernote (and put it in the browser)
4432 private void refreshEvernoteNote(boolean reload) {
4433 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4435 if (Global.disableViewing) {
4436 browserWindow.setEnabled(false);
4441 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4443 Global.cryptCounter =0;
4445 browserWindow.setReadOnly(true);
4452 browserWindow.loadingData(true);
4454 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4455 if (currentNote == null)
4457 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4460 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4461 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4462 formatter.setNote(note, Global.pdfPreview());
4463 formatter.setHighlight(listManager.getEnSearch());
4465 if (!noteCache.containsKey(guid)) {
4466 js = new QByteArray();
4467 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4468 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4469 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>");
4470 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4471 js.append("<style> img { height:auto; width:auto; max-height:auto; max-width:100%; }</style>");
4472 if (Global.displayRightToLeft())
4473 js.append("<style> body { direction:rtl; }</style>");
4474 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4475 js.append("</head>");
4476 formatter.setNote(note, Global.pdfPreview());
4477 js.append(formatter.rebuildNoteHTML());
4478 js.append("</HTML>");
4479 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4480 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4481 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4482 // if (Global.enableHTMLEntitiesFix) {
4483 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4485 browser.setContent(js);
4486 noteCache.put(guid, js.toString());
4488 if (formatter.resourceError)
4489 resourceErrorMessage();
4490 if (formatter.formatError) {
4492 QMessageBox.information(this, tr("Error"),
4493 tr("NixNote had issues formatting this note." +
4494 " To protect your data this note is being marked as read-only."));
4497 readOnly = formatter.readOnly;
4498 inkNote = formatter.inkNote;
4500 readOnlyCache.put(guid, true);
4502 inkNoteCache.put(guid, true);
4504 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4505 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4506 js = new QByteArray(cachedContent);
4507 browser.setContent(js);
4508 if (readOnlyCache.containsKey(guid))
4510 if (inkNoteCache.containsKey(guid))
4513 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4514 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4516 if (readOnly || inkNote ||
4517 (note.getAttributes() != null && note.getAttributes().getContentClass() != null && note.getAttributes().getContentClass() != ""))
4518 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4520 browser.getBrowser().page().setContentEditable(true);
4521 browser.setReadOnly(readOnly);
4522 deleteButton.setEnabled(!readOnly);
4523 tagButton.setEnabled(!readOnly);
4524 menuBar.noteDelete.setEnabled(!readOnly);
4525 menuBar.noteTags.setEnabled(!readOnly);
4526 browser.setNote(note);
4528 if (note != null && note.getNotebookGuid() != null &&
4529 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4530 deleteButton.setEnabled(false);
4531 menuBar.notebookDeleteAction.setEnabled(false);
4533 deleteButton.setEnabled(true);
4534 menuBar.notebookDeleteAction.setEnabled(true);
4537 // Build a list of non-closed notebooks
4538 List<Notebook> nbooks = new ArrayList<Notebook>();
4539 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4540 boolean found=false;
4541 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4542 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4546 nbooks.add(listManager.getNotebookIndex().get(i));
4549 browser.setTitle(note.getTitle());
4550 browser.setTag(getTagNamesForNote(note));
4551 browser.setAuthor(note.getAttributes().getAuthor());
4553 browser.setAltered(note.getUpdated());
4554 browser.setCreation(note.getCreated());
4555 if (note.getAttributes().getSubjectDate() > 0)
4556 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4558 browser.setSubjectDate(note.getCreated());
4559 browser.setUrl(note.getAttributes().getSourceURL());
4561 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4562 List<Tag> tagList = tagFilter.getValidTags(note);
4563 browser.setAllTags(tagList);
4565 browser.setCurrentTags(note.getTagNames());
4569 browser.loadingData(false);
4570 if (thumbnailViewer.isActiveWindow())
4573 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4574 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4577 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4579 // Save a generated thumbnail
4580 private void toggleNoteInformation() {
4581 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4582 browserWindow.toggleInformation();
4583 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4584 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4585 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4587 // Listener triggered when a print button is pressed
4588 @SuppressWarnings("unused")
4589 private void printNote() {
4590 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4592 QPrintDialog dialog = new QPrintDialog();
4593 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4594 QPrinter printer = dialog.printer();
4595 browserWindow.getBrowser().print(printer);
4597 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4600 // Listener triggered when the email button is pressed
4601 @SuppressWarnings("unused")
4602 private void emailNote() {
4603 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4605 if (Desktop.isDesktopSupported()) {
4606 Desktop desktop = Desktop.getDesktop();
4608 String text2 = browserWindow.getContentsToEmail();
4609 QUrl url = new QUrl("mailto:");
4610 url.addQueryItem("subject", currentNote.getTitle());
4611 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4612 url.addQueryItem("body", text2);
4613 QDesktopServices.openUrl(url);
4617 if (desktop.isSupported(Desktop.Action.MAIL)) {
4618 URI uriMailTo = null;
4620 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4621 String text = browserWindow.getContentsToEmail();
4622 //text = "<b>" +text +"</b>";
4623 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4624 +"&BODY=" +text, null);
4625 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4626 +"&ATTACHMENT=d:/test.pdf", null);
4627 desktop.mail(uriMailTo);
4628 } catch (URISyntaxException e) {
4629 e.printStackTrace();
4630 } catch (IOException e) {
4631 e.printStackTrace();
4638 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4640 // Reindex all notes
4641 @SuppressWarnings("unused")
4642 private void fullReindex() {
4643 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4644 indexRunner.addWork("REINDEXALL");
4645 setMessage(tr("Database will be reindexed."));
4646 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4648 // Listener when a user wants to reindex a specific note
4649 @SuppressWarnings("unused")
4650 private void reindexNote() {
4651 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4652 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4653 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4655 if (selectedNotebookGUIDs.size() > 1)
4656 setMessage(tr("Notes will be reindexed."));
4658 setMessage(tr("Note will be reindexed."));
4659 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4662 @SuppressWarnings("unused")
4663 private void deleteNote() {
4664 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4665 if (currentNote == null)
4667 if (currentNoteGuid.equals(""))
4669 String title = null;
4670 if (selectedNoteGUIDs.size() == 1)
4671 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4673 // If we are deleting non-trash notes
4674 if (currentNote.isActive()) {
4675 if (Global.verifyDelete()) {
4677 if (selectedNoteGUIDs.size() > 1) {
4678 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4681 msg = new String(tr("Delete note \"") +title +"\"?");
4683 msg = new String(tr("Delete note selected note?"));
4685 if (QMessageBox.question(this, tr("Confirmation"), msg,
4686 QMessageBox.StandardButton.Yes,
4687 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4691 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4692 selectedNoteGUIDs.add(currentNoteGuid);
4693 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4694 listManager.deleteNote(selectedNoteGUIDs.get(i));
4697 // If we are deleting from the trash.
4698 if (Global.verifyDelete()) {
4700 if (selectedNoteGUIDs.size() > 1) {
4701 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4704 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4706 msg = new String(tr("Permanently delete note selected note?"));
4708 if (QMessageBox.question(this, "Confirmation", msg,
4709 QMessageBox.StandardButton.Yes,
4710 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4714 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4715 selectedNoteGUIDs.add(currentNoteGuid);
4716 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4717 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4718 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4719 if (modelIndex != null) {
4720 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4721 String tableGuid = (String)ix.values().toArray()[0];
4722 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4723 listManager.getNoteTableModel().removeRow(j);
4728 listManager.expungeNote(selectedNoteGUIDs.get(i));
4731 currentNoteGuid = "";
4732 listManager.loadNotesIndex();
4733 noteIndexUpdated(false);
4734 refreshEvernoteNote(true);
4735 scrollToGuid(currentNoteGuid);
4736 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4739 @SuppressWarnings("unused")
4740 private void addNote() {
4741 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4742 // browserWindow.setEnabled(true);
4743 browserWindow.setReadOnly(false);
4745 Calendar currentTime = new GregorianCalendar();
4746 StringBuffer noteString = new StringBuffer(100);
4747 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4748 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4751 if (Global.overrideDefaultFont()) {
4752 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4753 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4754 noteString.append("<br clear=\"none\" />\n");
4755 noteString.append("</span>\n</font>\n");
4757 noteString.append("<br clear=\"none\" />\n");
4758 noteString.append("</en-note>");
4760 Long l = new Long(currentTime.getTimeInMillis());
4761 String randint = new String(Long.toString(l));
4763 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4765 // for the first non-archived notebook. Finally, if nothing else we
4766 // pick the first notebook in the list.
4767 String notebook = null;
4768 listManager.getNotebookIndex().get(0).getGuid();
4769 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4770 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4771 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4772 notebook = currentSelectedNotebook.text(2);
4774 boolean found = false;
4775 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4776 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4777 boolean match = false;
4778 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4779 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4781 j = listManager.getArchiveNotebookIndex().size();
4785 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4786 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4788 // Now we have a list of good notebooks, so we can look for the default
4790 for (int i=0; i<goodNotebooks.size(); i++) {
4791 if (goodNotebooks.get(i).isDefaultNotebook()) {
4792 notebook = goodNotebooks.get(i).getGuid();
4794 i = goodNotebooks.size();
4798 if (goodNotebooks.size() > 0 && !found)
4799 notebook = goodNotebooks.get(0).getGuid();
4802 notebook = listManager.getNotebookIndex().get(0).getGuid();
4805 Note newNote = new Note();
4806 newNote.setUpdateSequenceNum(0);
4807 newNote.setGuid(randint);
4808 newNote.setNotebookGuid(notebook);
4809 newNote.setTitle("Untitled Note");
4810 newNote.setContent(noteString.toString());
4811 newNote.setDeleted(0);
4812 newNote.setCreated(System.currentTimeMillis());
4813 newNote.setUpdated(System.currentTimeMillis());
4814 newNote.setActive(true);
4815 NoteAttributes na = new NoteAttributes();
4816 na.setLatitude(0.0);
4817 na.setLongitude(0.0);
4818 na.setAltitude(0.0);
4819 newNote.setAttributes(new NoteAttributes());
4820 newNote.setTagGuids(new ArrayList<String>());
4821 newNote.setTagNames(new ArrayList<String>());
4823 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4824 if (Global.newNoteWithSelectedTags()) {
4825 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4826 QTreeWidgetItem currentSelection;
4827 for (int i=0; i<selections.size(); i++) {
4828 currentSelection = selections.get(i);
4829 newNote.getTagGuids().add(currentSelection.text(2));
4830 newNote.getTagNames().add(currentSelection.text(0));
4834 conn.getNoteTable().addNote(newNote, true);
4835 NoteMetadata metadata = new NoteMetadata();
4836 metadata.setGuid(newNote.getGuid());
4837 metadata.setDirty(true);
4838 listManager.addNote(newNote, metadata);
4839 // noteTableView.insertRow(newNote, true, -1);
4841 currentNote = newNote;
4842 currentNoteGuid = currentNote.getGuid();
4843 noteTableView.clearSelection();
4844 refreshEvernoteNote(true);
4845 listManager.countNotebookResults(listManager.getNoteIndex());
4846 browserWindow.titleLabel.setFocus();
4847 browserWindow.titleLabel.selectAll();
4848 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4850 // If the window is hidden, then we want to popup this in an external window &
4854 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4856 // Restore a note from the trash;
4857 @SuppressWarnings("unused")
4858 private void restoreNote() {
4860 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4861 selectedNoteGUIDs.add(currentNoteGuid);
4862 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4863 listManager.restoreNote(selectedNoteGUIDs.get(i));
4865 currentNoteGuid = "";
4866 listManager.loadNotesIndex();
4867 noteIndexUpdated(false);
4870 // Search a note for specific txt
4871 @SuppressWarnings("unused")
4872 private void findText() {
4874 find.setFocusOnTextField();
4876 @SuppressWarnings("unused")
4877 private void doFindText() {
4878 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4881 @SuppressWarnings("unused")
4882 private void updateNoteTitle(String guid, String title) {
4883 listManager.setNoteSynchronized(guid, false);
4885 // We do this manually because if we've edited the note in an
4886 // external window we run into the possibility of signal recursion
4888 if (guid.equals(currentNoteGuid)) {
4889 browserWindow.titleLabel.blockSignals(true);
4890 browserWindow.titleLabel.setText(title);
4891 browserWindow.titleLabel.blockSignals(false);
4894 // Signal received that note content has changed. Normally we just need the guid to remove
4895 // it from the cache.
4896 @SuppressWarnings("unused")
4897 private void invalidateNoteCache(String guid, String content) {
4898 noteCache.remove(guid);
4899 refreshEvernoteNote(true);
4901 // Signal received that a note guid has changed
4902 @SuppressWarnings("unused")
4903 private void noteGuidChanged(String oldGuid, String newGuid) {
4904 if (noteCache.containsKey(oldGuid)) {
4905 if (!oldGuid.equals(currentNoteGuid)) {
4906 String cache = noteCache.get(oldGuid);
4907 noteCache.put(newGuid, cache);
4908 noteCache.remove(oldGuid);
4910 noteCache.remove(oldGuid);
4911 noteCache.put(newGuid, browserWindow.getContent());
4915 listManager.updateNoteGuid(oldGuid, newGuid, false);
4916 if (currentNoteGuid.equals(oldGuid)) {
4917 if (currentNote != null)
4918 currentNote.setGuid(newGuid);
4919 currentNoteGuid = newGuid;
4922 if (externalWindows.containsKey(oldGuid)) {
4923 ExternalBrowse b = externalWindows.get(oldGuid);
4924 externalWindows.remove(oldGuid);
4925 b.getBrowserWindow().getNote().setGuid(newGuid);
4926 externalWindows.put(newGuid, b);
4929 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4930 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4931 noteTableView.proxyModel.addGuid(newGuid, listManager.getNoteMetadata().get(newGuid));
4932 i=listManager.getNoteIndex().size();
4936 if (listManager.getNoteTableModel().metaData.containsKey(oldGuid)) {
4937 NoteMetadata meta = listManager.getNoteTableModel().metaData.get(oldGuid);
4938 listManager.getNoteTableModel().metaData.put(newGuid, meta);
4939 listManager.getNoteTableModel().metaData.remove(oldGuid);
4943 // Toggle the note editor button bar
4944 private void toggleEditorButtonBar() {
4945 if (browserWindow.buttonsVisible) {
4946 browserWindow.hideButtons();
4947 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4948 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4950 browserWindow.buttonsVisible = true;
4951 showEditorButtons(browserWindow);
4953 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4955 // Show editor buttons
4956 private void showEditorButtons(BrowserWindow browser) {
4957 browser.buttonLayout.setVisible(true);
4958 browser.undoAction.setVisible(false);
4960 browser.undoButton.setVisible(false);
4962 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4963 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4964 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4965 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4966 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4967 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4968 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4969 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4970 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4971 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4972 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4973 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4974 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4975 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4976 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4977 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4978 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4979 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4980 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4981 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4982 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4983 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4984 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4986 private void duplicateNote(String guid) {
4988 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4989 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4990 oldNote.setContent(conn.getNoteTable().getNoteContentNoUTFConversion(guid));
4991 oldNote.setResources(resList);
4992 duplicateNote(oldNote);
4994 private void duplicateNote(Note oldNote) {
4996 // Now that we have a good notebook guid, we need to move the conflicting note
4997 // to the local notebook
4998 Calendar currentTime = new GregorianCalendar();
4999 Long l = new Long(currentTime.getTimeInMillis());
5000 String newGuid = new String(Long.toString(l));
5002 // Note newNote = oldNote.deepCopy();
5003 Note newNote = (Note)Global.deepCopy(oldNote);
5004 newNote.setUpdateSequenceNum(0);
5005 newNote.setGuid(newGuid);
5006 newNote.setDeleted(0);
5007 newNote.setActive(true);
5010 List<String> tagNames = new ArrayList<String>();
5011 List<String> tagGuids = new ArrayList<String>();;
5012 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
5013 tagNames.add(oldNote.getTagNames().get(i));
5014 tagGuids.add(oldNote.getTagGuids().get(i));
5017 // Sort note Tags to make them look nice
5018 for (int i=0; i<tagNames.size()-1; i++) {
5019 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
5020 String n1 = tagNames.get(i);
5021 String n2 = tagNames.get(i+1);
5022 tagNames.set(i, n2);
5023 tagNames.set(i+1, n1);
5026 newNote.setTagGuids(tagGuids);
5027 newNote.setTagNames(tagNames);
5029 // Add tag guids to note
5032 // Duplicate resources
5033 List<Resource> resList = oldNote.getResources();
5034 if (resList == null)
5035 resList = new ArrayList<Resource>();
5037 for (int i=0; i<resList.size(); i++) {
5039 while (l == prevGuid) {
5040 currentTime = new GregorianCalendar();
5041 l = new Long(currentTime.getTimeInMillis());
5044 String newResGuid = new String(Long.toString(l));
5045 resList.get(i).setNoteGuid(newGuid);
5046 resList.get(i).setGuid(newResGuid);
5047 resList.get(i).setUpdateSequenceNum(0);
5048 resList.get(i).setActive(true);
5049 conn.getNoteTable().noteResourceTable.saveNoteResource(
5050 (Resource)Global.deepCopy(resList.get(i)), true);
5052 newNote.setResources(resList);
5054 // Add note to the database
5055 conn.getNoteTable().addNote(newNote, true);
5056 NoteMetadata metaData = new NoteMetadata();
5057 NoteMetadata oldMeta = listManager.getNoteMetadata().get(oldNote.getGuid());
5058 metaData.copy(oldMeta);
5059 metaData.setGuid(newNote.getGuid());
5060 listManager.addNote(newNote, metaData);
5061 noteTableView.insertRow(newNote, metaData, true, -1);
5062 currentNoteGuid = newNote.getGuid();
5063 currentNote = newNote;
5064 refreshEvernoteNote(true);
5065 listManager.countNotebookResults(listManager.getNoteIndex());
5069 @SuppressWarnings("unused")
5070 private void allNotes() {
5071 clearAttributeFilter();
5072 clearNotebookFilter();
5073 clearSavedSearchFilter();
5076 searchField.clear();
5077 if (Global.mimicEvernoteInterface) {
5078 notebookTree.selectGuid("");
5080 notebookTreeSelection();
5081 refreshEvernoteNote(true);
5084 @SuppressWarnings("unused")
5085 private void mergeNotes() {
5086 logger.log(logger.HIGH, "Merging notes");
5089 String masterGuid = null;
5090 List<String> sources = new ArrayList<String>();
5092 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
5093 int r = noteTableView.selectionModel().selectedRows().get(i).row();
5094 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
5095 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5097 masterGuid = (String)ix.values().toArray()[0];
5099 sources.add((String)ix.values().toArray()[0]);
5102 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
5103 logger.log(logger.EXTREME, "Children count: "+sources.size());
5104 mergeNoteContents(masterGuid, sources);
5105 currentNoteGuid = masterGuid;
5106 noteIndexUpdated(false);
5107 refreshEvernoteNote(true);
5110 private void mergeNoteContents(String targetGuid, List<String> sources) {
5111 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
5112 String newContent = target.getContent();
5113 newContent = newContent.replace("</en-note>", "<br></br>");
5115 for (int i=0; i<sources.size(); i++) {
5116 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
5117 if (source.isSetTitle()) {
5118 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
5120 String sourceContent = source.getContent();
5121 logger.log(logger.EXTREME, "Merging contents into note");
5122 logger.log(logger.EXTREME, sourceContent);
5123 logger.log(logger.EXTREME, "End of content");
5124 int startOfNote = sourceContent.indexOf("<en-note>");
5125 sourceContent = sourceContent.substring(startOfNote+9);
5126 int endOfNote = sourceContent.indexOf("</en-note>");
5127 sourceContent = sourceContent.substring(0,endOfNote);
5128 newContent = newContent + sourceContent;
5129 logger.log(logger.EXTREME, "New note content");
5130 logger.log(logger.EXTREME, newContent);
5131 logger.log(logger.EXTREME, "End of content");
5132 for (int j=0; j<source.getResourcesSize(); j++) {
5133 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
5134 Resource r = source.getResources().get(j);
5135 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
5137 Calendar currentTime = new GregorianCalendar();
5138 Long l = new Long(currentTime.getTimeInMillis());
5142 while (l == prevGuid) {
5143 currentTime = new GregorianCalendar();
5144 l = new Long(currentTime.getTimeInMillis());
5146 String newResGuid = new String(Long.toString(l));
5147 newRes.setNoteGuid(targetGuid);
5148 newRes.setGuid(newResGuid);
5149 newRes.setUpdateSequenceNum(0);
5150 newRes.setActive(true);
5151 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5154 logger.log(logger.EXTREME, "Updating note");
5155 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5156 for (int i=0; i<sources.size(); i++) {
5157 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5158 listManager.deleteNote(sources.get(i));
5160 logger.log(logger.EXTREME, "Exiting merge note");
5162 // A resource within a note has had a guid change
5163 @SuppressWarnings("unused")
5164 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5165 if (oldGuid != null && !oldGuid.equals(newGuid))
5166 Global.resourceMap.put(oldGuid, newGuid);
5168 // View a thumbnail of the note
5169 public void thumbnailView() {
5171 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5172 QFile thumbnail = new QFile(thumbnailName);
5173 if (!thumbnail.exists()) {
5175 QImage img = new QImage();
5176 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5177 thumbnailViewer.setThumbnail(img);
5179 thumbnailViewer.setThumbnail(thumbnailName);
5180 if (!thumbnailViewer.isVisible())
5181 thumbnailViewer.showFullScreen();
5183 // An error happened while saving a note. Inform the user
5184 @SuppressWarnings("unused")
5185 private void saveRunnerError(String guid, String msg) {
5187 String title = "*Unknown*";
5188 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5189 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5190 title = listManager.getMasterNoteIndex().get(i).getTitle();
5191 i=listManager.getMasterNoteIndex().size();
5194 msg = tr("An error has happened while saving the note \"") +title+
5195 tr("\".\n\nThis is probably due to a document that is too complex for NixNote to process. "+
5196 "As a result, changes to the note may not be saved properly in the database."+
5197 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5198 "\nbe lost. Please review the note to recover any critical data before restarting.");
5200 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5203 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5204 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5205 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5206 // Find an idle preview object
5207 for (int i=0; i<thumbGenerators.size(); i++) {
5208 if (thumbGenerators.get(i).mutex.tryLock()) {
5209 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5210 thumbGenerators.get(i).loadContent(guid, html, zoom);
5214 if (thumbGenerators.size() >= 1) {
5215 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5219 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5220 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5221 thumbGenerators.add(preview);
5223 if (preview.mutex.tryLock()) {
5224 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5225 preview.loadContent(guid, html, zoom);
5227 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5232 //**********************************************************
5233 //**********************************************************
5234 //* Online user actions
5235 //**********************************************************
5236 //**********************************************************
5237 private void setupOnlineMenu() {
5238 if (!Global.isConnected) {
5239 menuBar.noteOnlineHistoryAction.setEnabled(false);
5240 menuBar.selectiveSyncAction.setEnabled(false);
5243 menuBar.noteOnlineHistoryAction.setEnabled(true);
5244 menuBar.selectiveSyncAction.setEnabled(true);
5247 @SuppressWarnings("unused")
5248 private void viewNoteHistory() {
5249 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5251 if (currentNote.getUpdateSequenceNum() == 0) {
5252 setMessage(tr("Note has never been synchronized."));
5253 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5257 setMessage(tr("Getting Note History"));
5259 Note currentOnlineNote = null;
5262 if (Global.isPremium())
5263 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5265 versions = new ArrayList<NoteVersionId>();
5266 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5267 } catch (EDAMUserException e) {
5268 setMessage("EDAMUserException: " +e.getMessage());
5270 } catch (EDAMSystemException e) {
5271 setMessage("EDAMSystemException: " +e.getMessage());
5273 } catch (EDAMNotFoundException e) {
5274 setMessage(tr("Note not found on server."));
5275 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5277 } catch (TException e) {
5278 setMessage("EDAMTransactionException: " +e.getMessage());
5282 // If we've gotten this far, we have a good note.
5283 if (historyWindow == null) {
5284 historyWindow = new OnlineNoteHistory(logger, conn);
5285 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5286 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5287 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5289 historyWindow.historyCombo.clear();
5291 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5292 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5294 historyWindow.setCurrent(isDirty);
5296 loadHistoryWindowContent(currentOnlineNote);
5297 historyWindow.load(versions);
5298 setMessage(tr("History retrieved"));
5300 historyWindow.exec();
5302 private Note reloadHistoryWindow(String selection) {
5304 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5305 String dateTimeFormat = new String(fmt);
5306 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5310 for (int i=0; i<versions.size(); i++) {
5311 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5312 if (versionDate.toString().equals(selection))
5316 if (index > -1 || selection.indexOf("Current") > -1) {
5317 Note historyNote = null;
5320 usn = versions.get(index).getUpdateSequenceNum();
5321 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5323 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5324 } catch (EDAMUserException e) {
5325 setMessage("EDAMUserException: " +e.getMessage());
5328 } catch (EDAMSystemException e) {
5329 setMessage("EDAMSystemException: " +e.getMessage());
5332 } catch (EDAMNotFoundException e) {
5333 setMessage("EDAMNotFoundException: " +e.getMessage());
5336 } catch (TException e) {
5337 setMessage("EDAMTransactionException: " +e.getMessage());
5343 if (historyNote != null)
5344 historyWindow.setContent(historyNote);
5350 private void loadHistoryWindowContent(Note note) {
5351 note.setUpdateSequenceNum(0);
5352 historyWindow.setContent(note);
5354 @SuppressWarnings("unused")
5355 private void restoreHistoryNoteAsNew() {
5356 setMessage(tr("Restoring as new note."));
5357 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5358 setMessage(tr("Note has been restored as a new note."));
5360 @SuppressWarnings("unused")
5361 private void restoreHistoryNote() {
5362 setMessage(tr("Restoring note."));
5363 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5364 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5367 for (int i=0; i<n.getResourcesSize(); i++) {
5368 n.getResources().get(i).setActive(true);
5369 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5371 NoteMetadata metadata = new NoteMetadata();
5372 metadata.setGuid(n.getGuid());
5373 listManager.addNote(n, metadata);
5374 conn.getNoteTable().addNote(n, true);
5375 refreshEvernoteNote(true);
5376 setMessage(tr("Note has been restored."));
5378 @SuppressWarnings("unused")
5379 private void setupSelectiveSync() {
5381 // Get a list of valid notebooks
5382 List<Notebook> notebooks = null;
5383 List<Tag> tags = null;
5384 List<LinkedNotebook> linkedNotebooks = null;
5386 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5387 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5388 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5389 } catch (EDAMUserException e) {
5390 setMessage("EDAMUserException: " +e.getMessage());
5392 } catch (EDAMSystemException e) {
5393 setMessage("EDAMSystemException: " +e.getMessage());
5395 } catch (TException e) {
5396 setMessage("EDAMTransactionException: " +e.getMessage());
5398 } catch (EDAMNotFoundException e) {
5399 setMessage("EDAMNotFoundException: " +e.getMessage());
5403 // Split up notebooks into synchronized & non-synchronized
5404 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5405 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5407 for (int i=notebooks.size()-1; i>=0; i--) {
5408 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5409 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5410 ignoredBooks.add(notebooks.get(i));
5411 j=dbIgnoredNotebooks.size();
5416 // split up tags into synchronized & non-synchronized
5417 List<Tag> ignoredTags = new ArrayList<Tag>();
5418 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5420 for (int i=tags.size()-1; i>=0; i--) {
5421 for (int j=0; j<dbIgnoredTags.size(); j++) {
5422 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5423 ignoredTags.add(tags.get(i));
5424 j=dbIgnoredTags.size();
5429 // split up linked notebooks into synchronized & non-synchronized
5430 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5431 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5432 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5433 String notebookGuid = linkedNotebooks.get(i).getGuid();
5434 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5435 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5436 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5437 j=dbIgnoredLinkedNotebooks.size();
5442 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5444 if (!ignore.okClicked())
5449 // Clear out old notebooks & add the new ones
5450 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5451 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5452 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5455 List<String> newNotebooks = new ArrayList<String>();
5456 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5457 String text = ignore.getIgnoredBookList().takeItem(i).text();
5458 for (int j=0; j<notebooks.size(); j++) {
5459 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5460 Notebook n = notebooks.get(j);
5461 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5463 newNotebooks.add(n.getGuid());
5468 // Clear out old tags & add new ones
5469 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5470 for (int i=0; i<oldIgnoreTags.size(); i++) {
5471 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5474 List<String> newTags = new ArrayList<String>();
5475 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5476 String text = ignore.getIgnoredTagList().takeItem(i).text();
5477 for (int j=0; j<tags.size(); j++) {
5478 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5479 Tag t = tags.get(j);
5480 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5481 newTags.add(t.getGuid());
5487 // Clear out old tags & add new ones
5488 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5489 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5490 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5493 List<String> newLinked = new ArrayList<String>();
5494 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5495 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5496 for (int j=0; j<linkedNotebooks.size(); j++) {
5497 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5498 LinkedNotebook t = linkedNotebooks.get(j);
5499 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5500 newLinked.add(t.getGuid());
5501 j=linkedNotebooks.size();
5506 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5512 //**********************************************************
5513 //**********************************************************
5514 //* XML Modifying methods
5515 //**********************************************************
5516 //**********************************************************
5517 // An error has happended fetching a resource. let the user know
5518 private void resourceErrorMessage() {
5522 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5523 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5524 "In a perfect world this wouldn't happen, but it has.\n" +
5525 "It is embarasing when a program like me, designed to save all your\n"+
5526 "precious data, has a problem finding data.\n\n" +
5527 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5528 "In the mean time, I'm not going to let you make changes to this note.\n" +
5529 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5530 "this note on the Evernote servers. Sorry."+
5531 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5533 browserWindow.setReadOnly(true);
5540 //**********************************************************
5541 //**********************************************************
5543 //**********************************************************
5544 //**********************************************************
5545 // We should now do a sync with Evernote
5546 private void syncTimer() {
5547 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5548 syncRunner.syncNeeded = true;
5549 syncRunner.disableUploads = Global.disableUploads;
5551 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5553 private void syncStart() {
5554 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5556 if (!syncRunning && Global.isConnected) {
5557 syncRunner.setConnected(true);
5558 syncRunner.setKeepRunning(Global.keepRunning);
5559 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5561 if (syncThreadsReady > 0) {
5562 thumbnailRunner.interrupt = true;
5563 saveNoteIndexWidth();
5564 saveNoteColumnPositions();
5565 if (syncRunner.addWork("SYNC")) {
5567 syncRunner.syncNeeded = true;
5572 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5574 @SuppressWarnings("unused")
5575 private void syncThreadComplete(Boolean refreshNeeded) {
5576 setMessage(tr("Finalizing Synchronization"));
5578 syncRunning = false;
5579 syncRunner.syncNeeded = false;
5580 synchronizeAnimationTimer.stop();
5581 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5583 if (currentNote == null) {
5584 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5586 listManager.refreshNoteMetadata();
5587 noteIndexUpdated(true);
5588 noteTableView.selectionModel().blockSignals(true);
5589 scrollToGuid(currentNoteGuid);
5590 noteTableView.selectionModel().blockSignals(false);
5591 refreshEvernoteNote(false);
5592 scrollToGuid(currentNoteGuid);
5595 // Check to see if there were any shared notebook errors
5596 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5597 String guid = syncRunner.errorSharedNotebooks.get(0);
5598 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5599 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5600 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5602 if (syncDialog.okPressed()) {
5603 if (syncDialog.doNothing.isChecked()) {
5604 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5607 if (syncDialog.deleteNotebook.isChecked()) {
5608 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5609 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5610 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5611 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5619 // Finalize the synchronization
5620 if (!syncRunner.error)
5621 setMessage(tr("Synchronization Complete"));
5623 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5624 logger.log(logger.MEDIUM, "Sync complete.");
5626 public void saveUploadAmount(long t) {
5627 Global.saveUploadAmount(t);
5629 public void saveUserInformation(User user) {
5630 Global.saveUserInformation(user);
5632 public void saveEvernoteUpdateCount(int i) {
5633 Global.saveEvernoteUpdateCount(i);
5635 public void refreshLists() {
5636 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5638 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5639 tagIndexUpdated(true);
5640 notebookIndexUpdated();
5641 savedSearchIndexUpdated();
5642 listManager.loadNotesIndex();
5644 noteTableView.selectionModel().blockSignals(true);
5645 noteIndexUpdated(true);
5646 noteTableView.selectionModel().blockSignals(false);
5647 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5651 @SuppressWarnings("unused")
5652 private void authTimer() {
5653 Calendar cal = Calendar.getInstance();
5655 // If we are not connected let's get out of here
5656 if (!Global.isConnected)
5659 // If this is the first time through, then we need to set this
5660 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5661 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5663 // long now = new Date().getTime();
5664 // if (now > Global.authRefreshTime && Global.isConnected) {
5665 syncRunner.authRefreshNeeded = true;
5669 @SuppressWarnings("unused")
5670 private void authRefreshComplete(boolean goodSync) {
5671 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5672 Global.isConnected = syncRunner.isConnected;
5674 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5675 authTimer.start(1000*60*15);
5676 logger.log(logger.LOW, "Authentication token has been renewed");
5677 // setMessage("Authentication token has been renewed.");
5679 authTimer.start(1000*60*5);
5680 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5681 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5683 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5687 @SuppressWarnings("unused")
5688 private synchronized void indexTimer() {
5689 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5692 if (!indexDisabled && indexRunner.idle) {
5693 thumbnailRunner.interrupt = true;
5694 indexRunner.addWork("SCAN");
5696 logger.log(logger.EXTREME, "Leaving NixNote index timer");
5699 @SuppressWarnings("unused")
5700 private void indexStarted() {
5701 setMessage(tr("Indexing notes"));
5703 @SuppressWarnings("unused")
5704 private void indexComplete() {
5705 setMessage(tr("Index complete"));
5707 @SuppressWarnings("unused")
5708 private synchronized void toggleNoteIndexing() {
5709 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5710 indexDisabled = !indexDisabled;
5712 setMessage(tr("Indexing is now enabled."));
5714 setMessage(tr("Indexing is now disabled."));
5715 menuBar.disableIndexing.setChecked(indexDisabled);
5716 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5719 @SuppressWarnings("unused")
5720 private void threadMonitorCheck() {
5725 alive = listManager.threadCheck(Global.tagCounterThreadId);
5728 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5729 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died. I recommend "+
5730 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5731 disableTagThreadCheck = true;
5736 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5738 notebookThreadDeadCount++;
5739 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5740 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died. I recommend "+
5741 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5742 disableNotebookThreadCheck=true;
5745 notebookThreadDeadCount=0;
5747 alive = listManager.threadCheck(Global.trashCounterThreadId);
5750 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5751 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died. I recommend "+
5752 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5753 disableTrashThreadCheck = true;
5758 alive = listManager.threadCheck(Global.saveThreadId);
5760 saveThreadDeadCount++;
5761 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5762 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died. I recommend "+
5763 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5764 disableSaveThreadCheck = true;
5767 saveThreadDeadCount=0;
5769 if (!syncThread.isAlive()) {
5770 syncThreadDeadCount++;
5771 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5772 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died. I recommend "+
5773 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5774 disableSyncThreadCheck = true;
5777 syncThreadDeadCount=0;
5779 if (!indexThread.isAlive()) {
5780 indexThreadDeadCount++;
5781 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5782 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died. I recommend "+
5783 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5784 disableIndexThreadCheck = true;
5787 indexThreadDeadCount=0;
5792 private void thumbnailTimer() {
5793 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5794 thumbnailRunner.addWork("SCAN");
5798 //**************************************************
5799 //* Backup & Restore
5800 //**************************************************
5801 @SuppressWarnings("unused")
5802 private void databaseBackup() {
5803 QFileDialog fd = new QFileDialog(this);
5804 fd.setFileMode(FileMode.AnyFile);
5805 fd.setConfirmOverwrite(true);
5806 fd.setWindowTitle(tr("Backup Database"));
5807 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5808 fd.setAcceptMode(AcceptMode.AcceptSave);
5809 if (saveLastPath == null || saveLastPath.equals(""))
5810 fd.setDirectory(System.getProperty("user.home"));
5812 fd.setDirectory(saveLastPath);
5813 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5819 saveLastPath = fd.selectedFiles().get(0);
5820 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5821 setMessage(tr("Backing up database"));
5823 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5825 ExportData noteWriter = new ExportData(conn, true);
5826 String fileName = fd.selectedFiles().get(0);
5828 if (!fileName.endsWith(".nnex"))
5829 fileName = fileName +".nnex";
5830 noteWriter.exportData(fileName);
5831 setMessage(tr("Database backup completed."));
5836 @SuppressWarnings("unused")
5837 private void databaseRestore() {
5838 if (QMessageBox.question(this, tr("Confirmation"),
5839 tr("This is used to restore a database from backups.\n" +
5840 "It is HIGHLY recommened that this only be used to populate\n" +
5841 "an empty database. Restoring into a database that\n already has data" +
5842 " can cause problems.\n\nAre you sure you want to continue?"),
5843 QMessageBox.StandardButton.Yes,
5844 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5849 QFileDialog fd = new QFileDialog(this);
5850 fd.setFileMode(FileMode.ExistingFile);
5851 fd.setConfirmOverwrite(true);
5852 fd.setWindowTitle(tr("Restore Database"));
5853 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5854 fd.setAcceptMode(AcceptMode.AcceptOpen);
5855 if (saveLastPath == null || saveLastPath.equals(""))
5856 fd.setDirectory(System.getProperty("user.home"));
5858 fd.setDirectory(saveLastPath);
5859 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5865 saveLastPath = fd.selectedFiles().get(0);
5866 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5868 setMessage(tr("Restoring database"));
5869 ImportData noteReader = new ImportData(conn, true);
5870 noteReader.importData(fd.selectedFiles().get(0));
5872 if (noteReader.lastError != 0) {
5873 setMessage(noteReader.getErrorMessage());
5874 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5879 listManager.loadNoteTitleColors();
5881 refreshEvernoteNote(true);
5882 setMessage(tr("Database has been restored."));
5885 @SuppressWarnings("unused")
5886 private void exportNotes() {
5887 QFileDialog fd = new QFileDialog(this);
5888 fd.setFileMode(FileMode.AnyFile);
5889 fd.setConfirmOverwrite(true);
5890 fd.setWindowTitle(tr("Backup Database"));
5891 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5892 fd.setAcceptMode(AcceptMode.AcceptSave);
5893 fd.setDirectory(System.getProperty("user.home"));
5894 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5900 setMessage(tr("Exporting Notes"));
5903 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5904 selectedNoteGUIDs.add(currentNoteGuid);
5906 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5907 String fileName = fd.selectedFiles().get(0);
5909 if (!fileName.endsWith(".nnex"))
5910 fileName = fileName +".nnex";
5911 noteWriter.exportData(fileName);
5912 setMessage(tr("Export completed."));
5918 @SuppressWarnings("unused")
5919 private void importNotes() {
5920 QFileDialog fd = new QFileDialog(this);
5921 fd.setFileMode(FileMode.ExistingFile);
5922 fd.setConfirmOverwrite(true);
5923 fd.setWindowTitle(tr("Import Notes"));
5924 fd.setFilter(tr("NixNote Export (*.nnex);;Evernote Export (*.enex);;All Files (*.*)"));
5925 fd.setAcceptMode(AcceptMode.AcceptOpen);
5926 if (saveLastPath == null || saveLastPath.equals(""))
5927 fd.setDirectory(System.getProperty("user.home"));
5929 fd.setDirectory(saveLastPath);
5930 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5936 setMessage(tr("Importing Notes"));
5939 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5940 selectedNoteGUIDs.add(currentNoteGuid);
5942 String fileName = fd.selectedFiles().get(0);
5943 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5945 if (fileName.endsWith(".nnex")) {
5946 ImportData noteReader = new ImportData(conn, false);
5947 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5948 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5950 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5952 noteReader.importData(fileName);
5954 if (noteReader.lastError != 0) {
5955 setMessage(noteReader.getErrorMessage());
5956 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5961 if (fileName.endsWith(".enex")) {
5962 ImportEnex noteReader = new ImportEnex(conn, false);
5963 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5964 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5966 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5969 if (QMessageBox.question(this, tr("Confirmation"),
5970 tr("Create new tags from import?"),
5971 QMessageBox.StandardButton.Yes,
5972 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
5973 noteReader.createNewTags = true;
5975 noteReader.createNewTags = false;
5977 noteReader.importData(fileName);
5979 if (noteReader.lastError != 0) {
5980 setMessage(noteReader.getErrorMessage());
5981 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5988 listManager.loadNoteTitleColors();
5990 refreshEvernoteNote(false);
5991 setMessage(tr("Notes have been imported."));
5994 setMessage(tr("Import completed."));
6001 //**************************************************
6002 //* Duplicate a note
6003 //**************************************************
6004 @SuppressWarnings("unused")
6005 private void duplicateNote() {
6007 duplicateNote(currentNoteGuid);
6010 //**************************************************
6011 //* Action from when a user clicks Copy As URL
6012 //**************************************************
6013 @SuppressWarnings("unused")
6014 private void copyAsUrlClicked() {
6015 QClipboard clipboard = QApplication.clipboard();
6016 QMimeData mime = new QMimeData();
6018 mime.setText(currentNoteGuid);
6019 List<QUrl> urls = new ArrayList<QUrl>();
6021 // Start building the URL
6022 User user = Global.getUserInformation();
6024 // Check that we have everything we need
6025 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
6026 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
6028 if (!warning.neverSynchronize())
6031 Global.setBypassSynchronizationWarning(true);
6032 user.setShardId("s0");
6038 // Start building a list of URLs based upon the selected notes
6039 noteTableView.showColumn(Global.noteTableGuidPosition);
6041 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
6042 if (!Global.isColumnVisible("guid"))
6043 noteTableView.hideColumn(Global.noteTableGuidPosition);
6045 // Check that the note is either synchronized, or in a local notebook
6046 for (int i=0; i<selections.size(); i++) {
6048 int row = selections.get(i).row();
6049 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
6050 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6051 String selectedGuid = (String)ix.values().toArray()[0];
6053 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6054 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
6055 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
6056 "new notes to a local notebook."));
6061 // Start building the URLs
6062 for (int i=0; i<selections.size(); i++) {
6064 int row = selections.get(i).row();
6065 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
6066 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6067 String selectedGuid = (String)ix.values().toArray()[0];
6068 mime.setText(selectedGuid);
6072 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6073 if (selectedNote.getUpdateSequenceNum() > 0) {
6077 gid = "00000000-0000-0000-0000-000000000000";
6080 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
6082 urls.add(new QUrl(url));
6085 clipboard.setMimeData(mime);
6089 //**************************************************
6091 //**************************************************
6092 public void setupFolderImports() {
6093 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
6095 if (importKeepWatcher == null)
6096 importKeepWatcher = new QFileSystemWatcher();
6097 if (importDeleteWatcher == null) {
6098 importDeleteWatcher = new QFileSystemWatcher();
6099 for (int i=0; i<records.size(); i++) {
6100 if (!records.get(i).keep)
6101 folderImportDelete(records.get(i).folder);
6107 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
6108 for (int i=0; i<records.size(); i++) {
6109 if (records.get(i).keep)
6110 importKeepWatcher.addPath(records.get(i).folder);
6112 importDeleteWatcher.addPath(records.get(i).folder);
6115 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
6116 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
6118 // Look at the files already there so we don't import them again if a new file is created
6119 if (importedFiles == null) {
6120 importedFiles = new ArrayList<String>();
6121 for (int j=0; j<records.size(); j++) {
6122 QDir dir = new QDir(records.get(j).folder);
6123 List<QFileInfo> list = dir.entryInfoList();
6124 for (int k=0; k<list.size(); k++) {
6125 if (list.get(k).isFile())
6126 importedFiles.add(list.get(k).absoluteFilePath());
6131 public void folderImport() {
6132 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
6133 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
6135 if (!dialog.okClicked())
6138 // We have some sort of update.
6139 if (importKeepWatcher.directories().size() > 0)
6140 importKeepWatcher.removePaths(importKeepWatcher.directories());
6141 if (importDeleteWatcher.directories().size() > 0)
6142 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
6144 conn.getWatchFolderTable().expungeAll();
6145 // Start building from the table
6146 for (int i=0; i<dialog.table.rowCount(); i++) {
6147 QTableWidgetItem item = dialog.table.item(i, 0);
6148 String dir = item.text();
6149 item = dialog.table.item(i, 1);
6150 String notebook = item.text();
6151 item = dialog.table.item(i, 2);
6153 if (item.text().equalsIgnoreCase("Keep"))
6158 String guid = conn.getNotebookTable().findNotebookByName(notebook);
6159 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
6161 setupFolderImports();
6164 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
6166 String whichOS = System.getProperty("os.name");
6167 if (whichOS.contains("Windows"))
6168 dirName = dirName.replace('/','\\');
6170 FileImporter importer = new FileImporter(logger, conn);
6172 QDir dir = new QDir(dirName);
6173 List<QFileInfo> list = dir.entryInfoList();
6174 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6176 for (int i=0; i<list.size(); i++){
6178 boolean redundant = false;
6179 // Check if we've already imported this one or if it existed before
6180 for (int j=0; j<importedFiles.size(); j++) {
6181 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6186 importer.setFileInfo(list.get(i));
6187 importer.setFileName(list.get(i).absoluteFilePath());
6190 if (list.get(i).isFile() && importer.isValidType()) {
6192 if (!importer.importFile()) {
6193 // If we can't get to the file, it is probably locked. We'll try again later.
6194 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6195 importFilesKeep.add(list.get(i).absoluteFilePath());
6199 Note newNote = importer.getNote();
6200 newNote.setNotebookGuid(notebook);
6201 newNote.setTitle(dir.at(i));
6202 NoteMetadata metadata = new NoteMetadata();
6203 metadata.setDirty(true);
6204 metadata.setGuid(newNote.getGuid());
6205 listManager.addNote(newNote, metadata);
6206 conn.getNoteTable().addNote(newNote, true);
6207 noteTableView.insertRow(newNote, metadata, true, -1);
6208 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6209 listManager.countNotebookResults(listManager.getNoteIndex());
6210 importedFiles.add(list.get(i).absoluteFilePath());
6218 public void folderImportDelete(String dirName) {
6220 String whichOS = System.getProperty("os.name");
6221 if (whichOS.contains("Windows"))
6222 dirName = dirName.replace('/','\\');
6224 FileImporter importer = new FileImporter(logger, conn);
6225 QDir dir = new QDir(dirName);
6226 List<QFileInfo> list = dir.entryInfoList();
6227 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6229 for (int i=0; i<list.size(); i++){
6230 importer.setFileInfo(list.get(i));
6231 importer.setFileName(list.get(i).absoluteFilePath());
6233 if (list.get(i).isFile() && importer.isValidType()) {
6235 if (!importer.importFile()) {
6236 // If we can't get to the file, it is probably locked. We'll try again later.
6237 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6238 importFilesKeep.add(list.get(i).absoluteFilePath());
6242 Note newNote = importer.getNote();
6243 newNote.setNotebookGuid(notebook);
6244 newNote.setTitle(dir.at(i));
6245 NoteMetadata metadata = new NoteMetadata();
6246 metadata.setDirty(true);
6247 metadata.setGuid(newNote.getGuid());
6248 listManager.addNote(newNote, metadata);
6249 conn.getNoteTable().addNote(newNote, true);
6250 noteTableView.insertRow(newNote, metadata, true, -1);
6251 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6252 listManager.countNotebookResults(listManager.getNoteIndex());
6253 dir.remove(dir.at(i));
6259 //**************************************************
6261 //**************************************************
6262 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6263 logger.log(logger.HIGH, "Entering exernalFileEdited");
6265 // Strip URL prefix and base dir path
6266 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6267 String name = fileName.replace(dPath, "");
6268 int pos = name.lastIndexOf('.');
6271 guid = guid.substring(0,pos);
6273 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6275 guid = name.substring(0, pos);
6278 QFile file = new QFile(fileName);
6279 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6280 // If we can't get to the file, it is probably locked. We'll try again later.
6281 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6282 externalFiles.add(fileName);
6285 QByteArray binData = file.readAll();
6287 if (binData.size() == 0) {
6288 // If we can't get to the file, it is probably locked. We'll try again later.
6289 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6290 externalFiles.add(fileName);
6294 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6296 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6297 if (r == null || r.getData() == null || r.getData().getBody() == null)
6299 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6300 MessageDigest md = MessageDigest.getInstance("MD5");
6301 md.update(binData.toByteArray());
6302 byte[] hash = md.digest();
6303 String newHash = Global.byteArrayToHexString(hash);
6304 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6305 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6307 if (externalWindows.containsKey(r.getNoteGuid())) {
6308 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6309 r.getGuid(), oldHash, newHash);
6311 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6312 Data data = r.getData();
6313 data.setBody(binData.toByteArray());
6314 data.setBodyHash(hash);
6315 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6317 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6319 if (r.getNoteGuid().equals(currentNoteGuid)) {
6320 QWebSettings.setMaximumPagesInCache(0);
6321 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6322 refreshEvernoteNote(true);
6323 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6326 if (externalWindows.containsKey(r.getNoteGuid())) {
6327 QWebSettings.setMaximumPagesInCache(0);
6328 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6329 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6333 logger.log(logger.HIGH, "Exiting externalFielEdited");
6335 // This is a timer event that tries to save any external files that were edited. This
6336 // is only needed if we couldn't save a file earlier.
6337 public void externalFileEditedSaver() {
6338 for (int i=externalFiles.size()-1; i>=0; i--) {
6340 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6341 externalFileEdited(externalFiles.get(i));
6342 externalFiles.remove(i);
6343 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6345 for (int i=0; i<importFilesKeep.size(); i++) {
6347 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6348 folderImportKeep(importFilesKeep.get(i));
6349 importFilesKeep.remove(i);
6350 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6352 for (int i=0; i<importFilesDelete.size(); i++) {
6353 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6354 folderImportDelete(importFilesDelete.get(i));
6355 importFilesDelete.remove(i);
6362 // If an attachment on the current note was edited, we need to update the current notes's hash
6363 // Update a note content's hash. This happens if a resource is edited outside of NN
6364 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6365 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6367 for (;position>-1;) {
6368 endPos = browser.getContent().indexOf(">", position+1);
6369 String oldSegment = browser.getContent().substring(position,endPos);
6370 int hashPos = oldSegment.indexOf("hash=\"");
6371 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6372 String hash = oldSegment.substring(hashPos+6, hashEnd);
6373 if (hash.equalsIgnoreCase(oldHash)) {
6374 String newSegment = oldSegment.replace(oldHash, newHash);
6375 String content = browser.getContent().substring(0,position) +
6377 browser.getContent().substring(endPos);
6378 browser.setContent(new QByteArray(content));;
6381 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6386 //*************************************************
6387 //* Minimize to tray
6388 //*************************************************
6390 public void changeEvent(QEvent e) {
6391 if (e.type() == QEvent.Type.WindowStateChange) {
6392 if (QSystemTrayIcon.isSystemTrayAvailable()) {
6393 if (isMinimized() && (Global.showTrayIcon() || Global.showTrayIcon())) {
6395 QTimer.singleShot(10, this, "hide()");
6399 windowMaximized = true;
6401 windowMaximized = false;
6406 //*************************************************
6407 //* Check database userid & passwords
6408 //*************************************************
6409 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6410 Connection connection;
6413 Class.forName("org.h2.Driver");
6414 } catch (ClassNotFoundException e1) {
6415 e1.printStackTrace();
6420 String passwordString = null;
6421 if (cypherPassword==null || cypherPassword.trim().equals(""))
6422 passwordString = userPassword;
6424 passwordString = cypherPassword+" "+userPassword;
6425 connection = DriverManager.getConnection(url,userid,passwordString);
6426 } catch (SQLException e) {
6431 } catch (SQLException e) {
6432 e.printStackTrace();
6437 //*************************************************
6438 //* View / Hide source HTML for a note
6439 //*************************************************
6440 public void viewSource() {
6441 browserWindow.showSource(menuBar.viewSource.isChecked());
6443 //*************************************************
6444 // Block the program. This is used for things
6445 // like async web calls.
6446 //*************************************************
6447 @SuppressWarnings("unused")
6448 private void blockApplication(BrowserWindow b) {
6449 // Block all signals
6453 blockTimer = new QTimer();
6454 blockTimer.setSingleShot(true);
6455 blockTimer.setInterval(15000);
6456 blockTimer.timeout.connect(this, "unblockApplication()");
6461 @SuppressWarnings("unused")
6462 private void unblockApplication() {
6464 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6465 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6466 blockingWindow.unblockTime = -1;
6467 blockingWindow.awaitingHttpResponse = false;
6469 blockingWindow = null;
6470 blockSignals(false);