2 * This file is part of NixNote
3 * Copyright 2009 Randy Baumgarte
5 * This file may be licensed under the terms of of the
6 * GNU General Public License Version 2 (the ``GPL'').
8 * Software distributed under the License is distributed
9 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10 * express or implied. See the GPL for the specific language
11 * governing rights and limitations.
13 * You should have received a copy of the GPL along with this
14 * program. If not, go to http://www.gnu.org/licenses/gpl.html
15 * or write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 package cx.fbn.nevernote;
20 import java.awt.Desktop;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.net.Authenticator;
25 import java.net.PasswordAuthentication;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.SQLException;
31 import java.sql.Statement;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.SortedMap;
44 import java.util.Vector;
46 import org.apache.log4j.Level;
47 import org.apache.log4j.Logger;
48 import org.apache.thrift.TException;
49 import org.h2.tools.ChangeFileEncryption;
51 import com.evernote.edam.error.EDAMNotFoundException;
52 import com.evernote.edam.error.EDAMSystemException;
53 import com.evernote.edam.error.EDAMUserException;
54 import com.evernote.edam.notestore.NoteFilter;
55 import com.evernote.edam.notestore.NoteVersionId;
56 import com.evernote.edam.type.Data;
57 import com.evernote.edam.type.LinkedNotebook;
58 import com.evernote.edam.type.Note;
59 import com.evernote.edam.type.NoteAttributes;
60 import com.evernote.edam.type.Notebook;
61 import com.evernote.edam.type.Publishing;
62 import com.evernote.edam.type.QueryFormat;
63 import com.evernote.edam.type.Resource;
64 import com.evernote.edam.type.SavedSearch;
65 import com.evernote.edam.type.Tag;
66 import com.evernote.edam.type.User;
67 import com.trolltech.qt.QThread;
68 import com.trolltech.qt.core.QByteArray;
69 import com.trolltech.qt.core.QDateTime;
70 import com.trolltech.qt.core.QDir;
71 import com.trolltech.qt.core.QEvent;
72 import com.trolltech.qt.core.QFile;
73 import com.trolltech.qt.core.QFileInfo;
74 import com.trolltech.qt.core.QFileSystemWatcher;
75 import com.trolltech.qt.core.QIODevice;
76 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
77 import com.trolltech.qt.core.QLocale;
78 import com.trolltech.qt.core.QMimeData;
79 import com.trolltech.qt.core.QModelIndex;
80 import com.trolltech.qt.core.QSize;
81 import com.trolltech.qt.core.QTemporaryFile;
82 import com.trolltech.qt.core.QTextCodec;
83 import com.trolltech.qt.core.QThreadPool;
84 import com.trolltech.qt.core.QTimer;
85 import com.trolltech.qt.core.QTranslator;
86 import com.trolltech.qt.core.QUrl;
87 import com.trolltech.qt.core.Qt;
88 import com.trolltech.qt.core.Qt.BGMode;
89 import com.trolltech.qt.core.Qt.ItemDataRole;
90 import com.trolltech.qt.core.Qt.KeyboardModifier;
91 import com.trolltech.qt.core.Qt.MouseButton;
92 import com.trolltech.qt.core.Qt.SortOrder;
93 import com.trolltech.qt.core.Qt.WidgetAttribute;
94 import com.trolltech.qt.gui.QAbstractItemView;
95 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
96 import com.trolltech.qt.gui.QAction;
97 import com.trolltech.qt.gui.QApplication;
98 import com.trolltech.qt.gui.QClipboard;
99 import com.trolltech.qt.gui.QCloseEvent;
100 import com.trolltech.qt.gui.QColor;
101 import com.trolltech.qt.gui.QComboBox;
102 import com.trolltech.qt.gui.QCursor;
103 import com.trolltech.qt.gui.QDesktopServices;
104 import com.trolltech.qt.gui.QDialog;
105 import com.trolltech.qt.gui.QFileDialog;
106 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
107 import com.trolltech.qt.gui.QFileDialog.FileMode;
108 import com.trolltech.qt.gui.QGridLayout;
109 import com.trolltech.qt.gui.QHBoxLayout;
110 import com.trolltech.qt.gui.QIcon;
111 import com.trolltech.qt.gui.QImage;
112 import com.trolltech.qt.gui.QKeySequence;
113 import com.trolltech.qt.gui.QLabel;
114 import com.trolltech.qt.gui.QMainWindow;
115 import com.trolltech.qt.gui.QMenu;
116 import com.trolltech.qt.gui.QMessageBox;
117 import com.trolltech.qt.gui.QMessageBox.StandardButton;
118 import com.trolltech.qt.gui.QPainter;
119 import com.trolltech.qt.gui.QPalette.ColorRole;
120 import com.trolltech.qt.gui.QPixmap;
121 import com.trolltech.qt.gui.QPrintDialog;
122 import com.trolltech.qt.gui.QPrinter;
123 import com.trolltech.qt.gui.QShortcut;
124 import com.trolltech.qt.gui.QSizePolicy;
125 import com.trolltech.qt.gui.QSizePolicy.Policy;
126 import com.trolltech.qt.gui.QSpinBox;
127 import com.trolltech.qt.gui.QSplashScreen;
128 import com.trolltech.qt.gui.QSplitter;
129 import com.trolltech.qt.gui.QStatusBar;
130 import com.trolltech.qt.gui.QSystemTrayIcon;
131 import com.trolltech.qt.gui.QTableWidgetItem;
132 import com.trolltech.qt.gui.QTextEdit;
133 import com.trolltech.qt.gui.QToolBar;
134 import com.trolltech.qt.gui.QTreeWidgetItem;
135 import com.trolltech.qt.network.QNetworkAccessManager;
136 import com.trolltech.qt.network.QNetworkReply;
137 import com.trolltech.qt.network.QNetworkRequest;
138 import com.trolltech.qt.webkit.QWebPage.WebAction;
139 import com.trolltech.qt.webkit.QWebSettings;
141 import cx.fbn.nevernote.config.InitializationException;
142 import cx.fbn.nevernote.config.StartupConfig;
143 import cx.fbn.nevernote.dialog.AccountDialog;
144 import cx.fbn.nevernote.dialog.ConfigDialog;
145 import cx.fbn.nevernote.dialog.DBEncryptDialog;
146 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
147 import cx.fbn.nevernote.dialog.DatabaseStatus;
148 import cx.fbn.nevernote.dialog.FindDialog;
149 import cx.fbn.nevernote.dialog.IgnoreSync;
150 import cx.fbn.nevernote.dialog.LogFileDialog;
151 import cx.fbn.nevernote.dialog.LoginDialog;
152 import cx.fbn.nevernote.dialog.NotebookArchive;
153 import cx.fbn.nevernote.dialog.NotebookEdit;
154 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
155 import cx.fbn.nevernote.dialog.PublishNotebook;
156 import cx.fbn.nevernote.dialog.SavedSearchEdit;
157 import cx.fbn.nevernote.dialog.SetIcon;
158 import cx.fbn.nevernote.dialog.ShareNotebook;
159 import cx.fbn.nevernote.dialog.SharedNotebookSyncError;
160 import cx.fbn.nevernote.dialog.StackNotebook;
161 import cx.fbn.nevernote.dialog.SynchronizationRequiredWarning;
162 import cx.fbn.nevernote.dialog.TagEdit;
163 import cx.fbn.nevernote.dialog.TagMerge;
164 import cx.fbn.nevernote.dialog.ThumbnailViewer;
165 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
166 import cx.fbn.nevernote.dialog.WatchFolder;
167 import cx.fbn.nevernote.evernote.NoteMetadata;
168 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
169 import cx.fbn.nevernote.filters.FilterEditorTags;
170 import cx.fbn.nevernote.gui.AttributeTreeWidget;
171 import cx.fbn.nevernote.gui.BrowserWindow;
172 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
173 import cx.fbn.nevernote.gui.ExternalBrowse;
174 import cx.fbn.nevernote.gui.MainMenuBar;
175 import cx.fbn.nevernote.gui.NotebookTreeWidget;
176 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
177 import cx.fbn.nevernote.gui.SearchPanel;
178 import cx.fbn.nevernote.gui.TableView;
179 import cx.fbn.nevernote.gui.TagTreeWidget;
180 import cx.fbn.nevernote.gui.Thumbnailer;
181 import cx.fbn.nevernote.gui.TrashTreeWidget;
182 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
183 import cx.fbn.nevernote.sql.DatabaseConnection;
184 import cx.fbn.nevernote.sql.WatchFolderRecord;
185 import cx.fbn.nevernote.threads.IndexRunner;
186 import cx.fbn.nevernote.threads.SyncRunner;
187 import cx.fbn.nevernote.threads.ThumbnailRunner;
188 import cx.fbn.nevernote.utilities.AESEncrypter;
189 import cx.fbn.nevernote.utilities.ApplicationLogger;
190 import cx.fbn.nevernote.utilities.FileImporter;
191 import cx.fbn.nevernote.utilities.FileUtils;
192 import cx.fbn.nevernote.utilities.ListManager;
193 import cx.fbn.nevernote.utilities.SyncTimes;
194 import cx.fbn.nevernote.xml.ExportData;
195 import cx.fbn.nevernote.xml.ImportData;
196 import cx.fbn.nevernote.xml.ImportEnex;
197 import cx.fbn.nevernote.xml.NoteFormatter;
200 public class NeverNote extends QMainWindow{
202 QStatusBar statusBar; // Application status bar
204 DatabaseConnection conn;
206 MainMenuBar menuBar; // Main menu bar
207 FindDialog find; // Text search in note dialog
208 List<String> emitLog; // Messages displayed in the status bar;
209 QSystemTrayIcon trayIcon; // little tray icon
210 QMenu trayMenu; // System tray menu
211 QAction trayExitAction; // Exit the application
212 QAction trayShowAction; // toggle the show/hide action
213 QAction trayAddNoteAction; // Add a note from the system tray
214 QNetworkAccessManager versionChecker; // Used when checking for new versions
216 NotebookTreeWidget notebookTree; // List of notebooks
217 AttributeTreeWidget attributeTree; // List of note attributes
218 TagTreeWidget tagTree; // list of user created tags
219 SavedSearchTreeWidget savedSearchTree; // list of saved searches
220 TrashTreeWidget trashTree; // Trashcan
221 TableView noteTableView; // List of notes (the widget).
223 public BrowserWindow browserWindow; // Window containing browser & labels
224 public QToolBar toolBar; // The tool bar under the menu
225 QComboBox searchField; // search filter bar on the toolbar;
226 QShortcut searchShortcut; // Shortcut to search bar
227 boolean searchPerformed = false; // Search was done?
228 QuotaProgressBar quotaBar; // The current quota usage
230 ApplicationLogger logger;
231 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
232 List<String> selectedTagGUIDs; // List of selected tag GUIDs
233 List<String> selectedNoteGUIDs; // List of selected notes
234 String selectedSavedSearchGUID; // Currently selected saved searches
235 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
237 NoteFilter filter; // Note filter
238 String currentNoteGuid; // GUID of the current note
239 Note currentNote; // The currently viewed note
240 boolean noteDirty; // Has the note been changed?
241 boolean inkNote; // if this is an ink note, it is read only
242 boolean readOnly; // Is this note read-only?
245 ListManager listManager; // DB runnable task
247 List<QTemporaryFile> tempFiles; // Array of temporary files;
249 QTimer indexTimer; // timer to start the index thread
250 IndexRunner indexRunner; // thread to index notes
253 QTimer syncTimer; // Sync on an interval
254 QTimer syncDelayTimer; // Sync delay to free up database
255 SyncRunner syncRunner; // thread to do a sync.
256 QThread syncThread; // Thread which talks to evernote
257 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
258 QThread thumbnailThread; // Thread that generates pretty pictures
259 QTimer saveTimer; // Timer to save note contents
261 QTimer authTimer; // Refresh authentication
262 QTimer externalFileSaveTimer; // Save files altered externally
263 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
264 List<String> externalFiles; // External files to save later
265 List<String> importFilesKeep; // Auto-import files to save later
266 List<String> importFilesDelete; // Auto-import files to save later
268 int indexTime; // how often to try and index
269 boolean indexRunning; // Is indexing running?
270 boolean indexDisabled; // Is indexing disabled?
272 int syncThreadsReady; // number of sync threads that are free
273 int syncTime; // Sync interval
274 boolean syncRunning; // Is sync running?
275 boolean automaticSync; // do sync automatically?
276 QTreeWidgetItem attributeTreeSelected;
278 QAction prevButton; // Go to the previous item viewed
279 QAction nextButton; // Go to the next item in the history
280 QAction downButton; // Go to the next item in the list
281 QAction upButton; // Go to the prev. item in the list;
282 QAction synchronizeButton; // Synchronize with Evernote
283 QAction allNotesButton; // Reset & view all notes
284 QTimer synchronizeAnimationTimer; // Timer to change animation button
285 int synchronizeIconAngle; // Used to rotate sync icon
286 QAction printButton; // Print Button
287 QAction tagButton; // Tag edit button
288 QAction attributeButton; // Attribute information button
289 QAction emailButton; // Email button
290 QAction deleteButton; // Delete button
291 QAction newButton; // new Note Button;
292 QSpinBox zoomSpinner; // Zoom zoom
293 QAction searchClearButton; // Clear the search field
295 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
297 QSplitter mainLeftRightSplitter; // main splitter for left/right side
298 QSplitter leftSplitter1; // first left hand splitter
299 QSplitter browserIndexSplitter; // splitter between note index & note text
301 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
302 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
303 List<String> importedFiles; // History of imported files (so we don't import twice)
305 OnlineNoteHistory historyWindow; // online history window
306 List<NoteVersionId> versions; // history versions
308 QTimer threadMonitorTimer; // Timer to watch threads.
309 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
310 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
311 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
312 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
313 int tagDeadCount=0; // number of consecutive dead times for the tag thread
314 int trashDeadCount=0; // number of consecutive dead times for the trash thread
315 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
316 boolean disableTagThreadCheck=false;
317 boolean disableNotebookThreadCheck=false;
318 boolean disableTrashThreadCheck=false;
319 boolean disableSaveThreadCheck=false;
320 boolean disableSyncThreadCheck=false;
321 boolean disableIndexThreadCheck=false;
323 HashMap<String, String> noteCache; // Cash of note content
324 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
325 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
326 List<String> historyGuids; // GUIDs of previously viewed items
327 int historyPosition; // Position within the viewed items
328 boolean fromHistory; // Is this from the history queue?
329 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
330 List<Thumbnailer> thumbGenerators; // generate preview image
331 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
332 boolean encryptOnShutdown; // should I encrypt when I close?
333 boolean decryptOnShutdown; // should I decrypt on shutdown;
334 String encryptCipher; // What cipher should I use?
335 //Signal0 minimizeToTray;
336 boolean windowMaximized = false; // Keep track of the window state for restores
337 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
338 List<QPixmap> syncIcons; // Array of icons used in sync animation
339 private boolean closeAction = false; // Used to say when to close or when to minimize
340 private static Logger log = Logger.getLogger(NeverNote.class);
341 private String saveLastPath; // last path we used
342 private final QTimer messageTimer; // Timer to clear the status message.
343 private QTimer blockTimer;
344 BrowserWindow blockingWindow;
346 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
349 //***************************************************************
350 //***************************************************************
351 //** Constructor & main entry point
352 //***************************************************************
353 //***************************************************************
354 // Application Constructor
355 @SuppressWarnings("static-access")
356 public NeverNote(DatabaseConnection dbConn) {
358 if (conn.getConnection() == null) {
359 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
360 "is accessing the database or NixNote is already running.\n\n" +
361 "Please end any other process or shutdown the other NixNote before starting.\n\nExiting program."));
363 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
366 setObjectName("mainWindow");
367 // thread().setPriority(Thread.MAX_PRIORITY);
369 logger = new ApplicationLogger("nevernote.log");
370 logger.log(logger.HIGH, "Starting Application");
372 decryptOnShutdown = false;
373 encryptOnShutdown = false;
374 conn.checkDatabaseVersion();
378 // Start building the invalid XML tables
379 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
380 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
382 for (int i=0; i<elements.size(); i++) {
383 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
386 logger.log(logger.EXTREME, "Starting GUI build");
388 QTranslator nevernoteTranslator = new QTranslator();
389 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
390 QApplication.instance().installTranslator(nevernoteTranslator);
392 Global.originalPalette = QApplication.palette();
393 QApplication.setStyle(Global.getStyle());
394 if (Global.useStandardPalette())
395 QApplication.setPalette(QApplication.style().standardPalette());
396 setWindowTitle(tr("NixNote"));
398 mainLeftRightSplitter = new QSplitter();
399 setCentralWidget(mainLeftRightSplitter);
400 leftSplitter1 = new QSplitter();
401 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
403 browserIndexSplitter = new QSplitter();
404 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
406 //* Setup threads & thread timers
407 // int indexRunnerCount = Global.getIndexThreads();
408 // indexRunnerCount = 1;
409 QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount); // increase max thread count
411 logger.log(logger.EXTREME, "Building list manager");
412 listManager = new ListManager(conn, logger);
414 logger.log(logger.EXTREME, "Building index runners & timers");
415 indexRunner = new IndexRunner("indexRunner.log",
416 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
417 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
418 indexThread = new QThread(indexRunner, "Index Thread");
419 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
420 indexRunner.indexImageRecognition = Global.indexImageRecognition();
421 indexRunner.indexNoteBody = Global.indexNoteBody();
422 indexRunner.indexNoteTitle = Global.indexNoteTitle();
423 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
426 synchronizeAnimationTimer = new QTimer();
427 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
429 indexTimer = new QTimer();
430 indexTime = 1000*Global.getIndexThreadSleepInterval();
431 indexTimer.start(indexTime); // Start indexing timer
432 indexTimer.timeout.connect(this, "indexTimer()");
433 indexDisabled = false;
434 indexRunning = false;
436 logger.log(logger.EXTREME, "Setting sync thread & timers");
438 syncRunner = new SyncRunner("syncRunner.log",
439 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
440 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
441 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
442 syncTimer = new QTimer();
443 syncTimer.timeout.connect(this, "syncTimer()");
444 syncRunner.status.message.connect(this, "setMessage(String)");
445 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
446 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
449 automaticSync = true;
450 syncTimer.start(syncTime*60*1000);
452 automaticSync = false;
455 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
456 syncThread = new QThread(syncRunner, "Synchronization Thread");
460 logger.log(logger.EXTREME, "Starting thumnail thread");
461 pdfReadyQueue = new ArrayList<String>();
462 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
463 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
464 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
465 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
466 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
467 thumbnailThread.start();
468 thumbGenerators = new ArrayList<Thumbnailer>();
469 thumbnailTimer = new QTimer();
470 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
472 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
473 thumbnailTimer.start();
475 logger.log(logger.EXTREME, "Starting authentication timer");
476 authTimer = new QTimer();
477 authTimer.timeout.connect(this, "authTimer()");
478 authTimer.start(1000*60*15);
479 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
481 logger.log(logger.EXTREME, "Setting save note timer");
482 saveTimer = new QTimer();
483 saveTimer.timeout.connect(this, "saveNote()");
484 if (Global.getAutoSaveInterval() > 0) {
485 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
488 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
490 logger.log(logger.EXTREME, "Starting external file monitor timer");
491 externalFileSaveTimer = new QTimer();
492 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
493 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
494 externalFiles = new ArrayList<String>();
495 importFilesDelete = new ArrayList<String>();
496 importFilesKeep = new ArrayList<String>();
497 externalFileSaveTimer.start();
499 notebookTree = new NotebookTreeWidget(conn);
500 attributeTree = new AttributeTreeWidget();
501 tagTree = new TagTreeWidget(conn);
502 savedSearchTree = new SavedSearchTreeWidget();
503 trashTree = new TrashTreeWidget();
504 noteTableView = new TableView(logger, listManager);
506 searchField = new QComboBox();
507 searchField.setObjectName("searchField");
508 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
509 searchField.setEditable(true);
510 searchField.activatedIndex.connect(this, "searchFieldChanged()");
511 searchField.setDuplicatesEnabled(false);
512 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
513 searchShortcut = new QShortcut(this);
514 setupShortcut(searchShortcut, "Focus_Search");
515 searchShortcut.activated.connect(this, "focusSearch()");
517 quotaBar = new QuotaProgressBar();
519 zoomSpinner = new QSpinBox();
520 zoomSpinner.setMinimum(10);
521 zoomSpinner.setMaximum(1000);
522 zoomSpinner.setAccelerated(true);
523 zoomSpinner.setSingleStep(10);
524 zoomSpinner.setValue(100);
525 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
527 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
530 QGridLayout leftGrid = new QGridLayout();
531 leftSplitter1.setContentsMargins(5, 0, 0, 7);
532 leftSplitter1.setLayout(leftGrid);
533 leftGrid.addWidget(searchLayout,1,1);
534 leftGrid.addWidget(tagTree,2,1);
535 leftGrid.addWidget(attributeTree,3,1);
536 leftGrid.addWidget(savedSearchTree,4,1);
537 leftGrid.addWidget(trashTree,5, 1);
539 // Setup the browser window
540 noteCache = new HashMap<String,String>();
541 readOnlyCache = new HashMap<String, Boolean>();
542 inkNoteCache = new HashMap<String, Boolean>();
543 browserWindow = new BrowserWindow(conn);
545 mainLeftRightSplitter.addWidget(leftSplitter1);
546 mainLeftRightSplitter.addWidget(browserIndexSplitter);
548 if (Global.getListView() == Global.View_List_Wide) {
549 browserIndexSplitter.addWidget(noteTableView);
550 browserIndexSplitter.addWidget(browserWindow);
552 mainLeftRightSplitter.addWidget(noteTableView);
553 mainLeftRightSplitter.addWidget(browserWindow);
556 // Setup the thumbnail viewer
557 thumbnailViewer = new ThumbnailViewer();
558 thumbnailViewer.upArrow.connect(this, "upAction()");
559 thumbnailViewer.downArrow.connect(this, "downAction()");
560 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
561 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
563 //Setup external browser manager
564 externalWindows = new HashMap<String, ExternalBrowse>();
566 listManager.loadNotesIndex();
567 initializeNotebookTree();
569 initializeSavedSearchTree();
570 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
571 attributeTreeSelected = null;
572 initializeNoteTable();
574 selectedNoteGUIDs = new ArrayList<String>();
575 statusBar = new QStatusBar();
576 setStatusBar(statusBar);
577 menuBar = new MainMenuBar(this);
578 emitLog = new ArrayList<String>();
580 tagTree.setDeleteAction(menuBar.tagDeleteAction);
581 tagTree.setMergeAction(menuBar.tagMergeAction);
582 tagTree.setEditAction(menuBar.tagEditAction);
583 tagTree.setAddAction(menuBar.tagAddAction);
584 tagTree.setIconAction(menuBar.tagIconAction);
585 tagTree.setVisible(Global.isWindowVisible("tagTree"));
586 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
587 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
588 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
589 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
591 if (!Global.isWindowVisible("zoom")) {
592 searchLayout.hideZoom();
593 menuBar.hideZoom.setChecked(false);
596 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
597 notebookTree.setEditAction(menuBar.notebookEditAction);
598 notebookTree.setAddAction(menuBar.notebookAddAction);
599 notebookTree.setIconAction(menuBar.notebookIconAction);
600 notebookTree.setStackAction(menuBar.notebookStackAction);
601 notebookTree.setPublishAction(menuBar.notebookPublishAction);
602 notebookTree.setShareAction(menuBar.notebookShareAction);
603 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
604 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
605 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
606 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
607 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
609 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
610 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
611 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
612 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
613 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
614 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
615 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
617 noteTableView.setAddAction(menuBar.noteAdd);
618 noteTableView.setDeleteAction(menuBar.noteDelete);
619 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
620 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
621 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
622 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
623 noteTableView.noteSignal.notePinned.connect(this, "notePinned()");
624 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
625 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
626 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
627 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
629 quotaBar.setMouseClickAction(menuBar.accountAction);
632 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
633 trashTree.setEmptyAction(menuBar.emptyTrashAction);
634 trashTree.setVisible(Global.isWindowVisible("trashTree"));
635 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
636 trashTree.updateCounts(listManager.getTrashCount());
637 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
638 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
640 noteTableView.setVisible(Global.isWindowVisible("noteList"));
641 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
643 if (!Global.isWindowVisible("editorButtonBar"))
644 toggleEditorButtonBar();
645 if (!Global.isWindowVisible("leftPanel"))
646 menuBar.hideLeftSide.setChecked(true);
647 if (Global.isWindowVisible("noteInformation"))
648 toggleNoteInformation();
649 quotaBar.setVisible(Global.isWindowVisible("quota"));
650 if (!quotaBar.isVisible())
651 menuBar.hideQuota.setChecked(false);
652 searchField.setVisible(Global.isWindowVisible("searchField"));
653 if (!searchField.isVisible())
654 menuBar.hideSearch.setChecked(false);
656 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
661 find = new FindDialog();
662 find.getOkButton().clicked.connect(this, "doFindText()");
664 // Setup the tray icon menu bar
665 trayShowAction = new QAction(tr("Show/Hide"), this);
666 trayExitAction = new QAction(tr("Exit"), this);
667 trayAddNoteAction = new QAction(tr("Add Note"), this);
669 trayExitAction.triggered.connect(this, "closeNeverNote()");
670 trayAddNoteAction.triggered.connect(this, "addNote()");
671 trayShowAction.triggered.connect(this, "trayToggleVisible()");
673 trayMenu = new QMenu(this);
674 trayMenu.addAction(trayAddNoteAction);
675 trayMenu.addAction(trayShowAction);
676 trayMenu.addAction(trayExitAction);
679 trayIcon = new QSystemTrayIcon(this);
680 trayIcon.setToolTip(tr("NixNote"));
681 trayIcon.setContextMenu(trayMenu);
682 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
685 currentNoteGuid = Global.getLastViewedNoteGuid();
686 historyGuids = new ArrayList<String>();
690 if (!currentNoteGuid.trim().equals("")) {
691 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
694 noteIndexUpdated(true);
696 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
697 if (menuBar.showEditorBar.isChecked())
698 showEditorButtons(browserWindow);
699 tagIndexUpdated(true);
700 savedSearchIndexUpdated();
701 notebookIndexUpdated();
703 setupSyncSignalListeners();
704 setupBrowserSignalListeners();
705 setupIndexListeners();
708 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
709 tagTree.showAllTags(true);
711 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
712 if (QSystemTrayIcon.isSystemTrayAvailable()) {
713 setWindowIcon(appIcon);
714 trayIcon.setIcon(appIcon);
715 if (Global.showTrayIcon() || Global.minimizeOnClose())
721 scrollToGuid(currentNoteGuid);
722 if (Global.automaticLogin()) {
724 if (Global.isConnected)
727 setupFolderImports();
730 restoreWindowState(true);
732 if (Global.mimicEvernoteInterface) {
733 notebookTree.selectGuid("");
736 threadMonitorTimer = new QTimer();
737 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
738 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
740 historyGuids.add(currentNoteGuid);
743 menuBar.blockSignals(true);
744 menuBar.narrowListView.blockSignals(true);
745 menuBar.wideListView.blockSignals(true);
746 if (Global.getListView() == Global.View_List_Narrow) {
747 menuBar.narrowListView.setChecked(true);
750 menuBar.wideListView.setChecked(true);
752 menuBar.blockSignals(false);
753 menuBar.narrowListView.blockSignals(false);
754 menuBar.wideListView.blockSignals(false);
756 if (Global.getListView() == Global.View_List_Wide) {
757 browserIndexSplitter.addWidget(noteTableView);
758 browserIndexSplitter.addWidget(browserWindow);
760 mainLeftRightSplitter.addWidget(noteTableView);
761 mainLeftRightSplitter.addWidget(browserWindow);
764 messageTimer = new QTimer();
765 messageTimer.timeout.connect(this, "clearMessage()");
766 messageTimer.setInterval(1000*15);
769 int sortCol = Global.getSortColumn();
770 int sortOrder = Global.getSortOrder();
771 noteTableView.proxyModel.blocked = true;
772 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
773 noteTableView.proxyModel.blocked = false;
774 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
776 // Set the startup notebook
777 String defaultNotebook = Global.getStartupNotebook();
778 if (!defaultNotebook.equals("AllNotebooks") && !defaultNotebook.equals("")) {
779 for (int k=0; k<listManager.getNotebookIndex().size(); k++) {
780 if (listManager.getNotebookIndex().get(k).isDefaultNotebook()) {
781 notebookTree.clearSelection();
782 notebookTree.selectGuid(listManager.getNotebookIndex().get(k).getGuid());
783 notebookTree.selectionSignal.emit();
788 if (Global.checkVersionUpgrade())
793 public static void main(String[] args) {
794 log.setLevel(Level.FATAL);
795 QApplication.initialize(args);
796 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
797 QSplashScreen splash = new QSplashScreen(pixmap);
800 DatabaseConnection dbConn;
803 initializeGlobalSettings(args);
805 showSplash = Global.isWindowVisible("SplashScreen");
809 dbConn = setupDatabaseConnection();
811 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
812 Global.getFileManager().purgeResDirectory(true);
814 } catch (InitializationException e) {
817 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
821 NeverNote application = new NeverNote(dbConn);
822 if (Global.syncOnly) {
823 System.out.println("Performing synchronization only.");
824 application.remoteConnect();
825 if (Global.isConnected) {
826 application.syncRunner.syncNeeded = true;
827 application.syncRunner.addWork("SYNC");
828 application.syncRunner.addWork("STOP");
829 while(!application.syncRunner.isIdle());
830 application.closeNeverNote();
835 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
836 if (Global.startMinimized())
837 application.showMinimized();
839 if (Global.wasWindowMaximized())
840 application.showMaximized();
846 splash.finish(application);
848 System.out.println("Goodbye.");
853 * Open the internal database, or create if not present
855 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
857 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
858 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
860 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
861 File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
862 File fi = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
864 Global.setDatabaseUrl("");
866 Global.setResourceDatabaseUrl("");
868 Global.setIndexDatabaseUrl("");
870 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
871 boolean goodCheck = false;
873 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
875 if (!dialog.okPressed())
877 Global.cipherPassword = dialog.getPassword();
878 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
879 Global.getDatabaseUserPassword(), Global.cipherPassword);
882 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
883 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
884 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
888 // Encrypt the database upon shutdown
889 private void encryptOnShutdown() {
890 String dbPath= Global.getFileManager().getDbDirPath("");
893 Statement st = conn.getConnection().createStatement();
894 st.execute("shutdown");
895 st = conn.getResourceConnection().createStatement();
896 st.execute("shutdown");
897 st = conn.getIndexConnection().createStatement();
898 st.execute("shutdown");
899 if (QMessageBox.question(this, tr("Are you sure"),
900 tr("Are you sure you wish to encrypt the database?"),
901 QMessageBox.StandardButton.Yes,
902 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
903 ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
904 ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
905 ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
906 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
907 Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
908 Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
910 QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
912 } catch (SQLException e) {
917 // Decrypt the database upon shutdown
918 private void decryptOnShutdown() {
919 String dbPath= Global.getFileManager().getDbDirPath("");
920 String dbName = "NeverNote";
922 Statement st = conn.getConnection().createStatement();
923 st.execute("shutdown");
924 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
925 encryptCipher = "AES";
927 encryptCipher = "XTEA";
928 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
929 "Are you sure you wish to decrypt the database?"),
930 QMessageBox.StandardButton.Yes,
931 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
933 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
934 Global.setDatabaseUrl("");
935 Global.setResourceDatabaseUrl("");
936 Global.setIndexDatabaseUrl("");
937 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
939 } catch (SQLException e) {
944 * Encrypt/Decrypt the local database
946 public void doDatabaseEncrypt() {
947 // The database is not currently encrypted
948 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
949 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
950 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
951 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
952 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
953 "Do you wish to proceed?"),
954 QMessageBox.StandardButton.Yes,
955 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
958 DBEncryptDialog dialog = new DBEncryptDialog();
960 if (dialog.okPressed()) {
961 Global.cipherPassword = dialog.getPassword();
962 encryptOnShutdown = true;
963 encryptCipher = dialog.getEncryptionMethod();
966 DBEncryptDialog dialog = new DBEncryptDialog();
967 dialog.setWindowTitle(tr("Database Decryption"));
968 dialog.hideEncryption();
970 if (dialog.okPressed()) {
971 if (!dialog.getPassword().equals(Global.cipherPassword)) {
972 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
975 decryptOnShutdown = true;
982 private static void initializeGlobalSettings(String[] args) throws InitializationException {
983 StartupConfig startupConfig = new StartupConfig();
985 for (String arg : args) {
986 String lower = arg.toLowerCase();
987 if (lower.startsWith("--name="))
988 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
989 if (lower.startsWith("--home="))
990 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
991 if (lower.startsWith("--disable-viewing"))
992 startupConfig.setDisableViewing(true);
993 if (lower.startsWith("--sync-only=true"))
994 startupConfig.setSyncOnly(true);
996 Global.setup(startupConfig);
1002 public void closeEvent(QCloseEvent event) {
1003 if (Global.minimizeOnClose() && !closeAction) {
1008 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
1011 if (currentNote!= null & browserWindow!=null) {
1012 if (currentNote.getTitle() != null && browserWindow != null
1013 && !currentNote.getTitle().equals(browserWindow.getTitle()))
1014 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
1017 setMessage(tr("Beginning shutdown."));
1019 // Close down external windows
1020 Collection<ExternalBrowse> windows = externalWindows.values();
1021 Iterator<ExternalBrowse> iterator = windows.iterator();
1022 while (iterator.hasNext()) {
1023 ExternalBrowse browser = iterator.next();
1024 browser.windowClosing.disconnect();
1029 externalFileEditedSaver();
1030 if (Global.isConnected && Global.synchronizeOnClose()) {
1031 setMessage(tr("Performing synchronization before closing."));
1032 syncRunner.syncNeeded = true;
1033 syncRunner.addWork("SYNC");
1035 syncRunner.keepRunning = false;
1037 syncRunner.addWork("STOP");
1038 setMessage("Closing Program.");
1039 threadMonitorTimer.stop();
1041 thumbnailRunner.addWork("STOP");
1042 indexRunner.addWork("STOP");
1047 if (tempFiles != null)
1050 browserWindow.noteSignal.tagsChanged.disconnect();
1051 browserWindow.noteSignal.titleChanged.disconnect();
1052 browserWindow.noteSignal.noteChanged.disconnect();
1053 browserWindow.noteSignal.notebookChanged.disconnect();
1054 browserWindow.noteSignal.createdDateChanged.disconnect();
1055 browserWindow.noteSignal.alteredDateChanged.disconnect();
1056 syncRunner.searchSignal.listChanged.disconnect();
1057 syncRunner.tagSignal.listChanged.disconnect();
1058 syncRunner.notebookSignal.listChanged.disconnect();
1059 syncRunner.noteIndexSignal.listChanged.disconnect();
1062 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1063 saveNoteColumnPositions();
1064 saveNoteIndexWidth();
1066 int width = notebookTree.columnWidth(0);
1067 Global.setColumnWidth("notebookTreeName", width);
1068 width = tagTree.columnWidth(0);
1069 Global.setColumnWidth("tagTreeName", width);
1071 Global.saveWindowMaximized(isMaximized());
1072 Global.saveCurrentNoteGuid(currentNoteGuid);
1074 int sortCol = noteTableView.proxyModel.sortColumn();
1075 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1076 Global.setSortColumn(sortCol);
1077 Global.setSortOrder(sortOrder);
1081 Global.keepRunning = false;
1083 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1084 if (indexRunner.thread().isAlive())
1085 indexRunner.thread().join(50);
1086 if (!indexRunner.thread().isAlive())
1087 logger.log(logger.MEDIUM, "Index thread has stopped");
1089 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1090 indexRunner.thread().interrupt();
1092 } catch (InterruptedException e1) {
1093 e1.printStackTrace();
1096 if (!syncRunner.thread().isAlive()) {
1097 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1098 if (syncRunner.thread().isAlive()) {
1099 System.out.println(tr("Synchronizing. Please be patient."));
1100 for(;syncRunner.thread().isAlive();) {
1103 } catch (InterruptedException e) {
1104 e.printStackTrace();
1108 logger.log(logger.MEDIUM, "Sync thread has stopped");
1111 if (encryptOnShutdown) {
1112 encryptOnShutdown();
1114 if (decryptOnShutdown) {
1115 decryptOnShutdown();
1118 Global.getFileManager().purgeResDirectory(false);
1119 } catch (InitializationException e) {
1120 System.out.println(tr("Empty res directory purge failed"));
1121 e.printStackTrace();
1123 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1127 private void closeNeverNote() {
1131 public void setMessage(String s) {
1132 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1135 logger.log(logger.HIGH, "Message: " +s);
1136 statusBar.showMessage(s);
1140 messageTimer.stop();
1141 messageTimer.setSingleShot(true);
1142 messageTimer.start();
1145 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1148 private void clearMessage() {
1149 statusBar.clearMessage();
1153 private void waitCursor(boolean wait) {
1155 if (QApplication.overrideCursor() == null)
1156 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1159 while (QApplication.overrideCursor() != null)
1160 QApplication.restoreOverrideCursor();
1162 listManager.refreshCounters();
1165 private void setupIndexListeners() {
1166 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1167 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1168 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1169 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1171 private void setupSyncSignalListeners() {
1172 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1173 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1174 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1175 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1176 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1178 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1179 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1180 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1182 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1183 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1184 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1185 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1186 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1188 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1191 private void setupBrowserSignalListeners() {
1192 setupBrowserWindowListeners(browserWindow, true);
1195 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1196 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1197 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1198 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1199 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1200 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1201 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1202 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1203 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1204 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1205 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1206 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1207 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1208 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1209 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1210 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1211 browser.unblockApplication.connect(this, "unblockApplication()");
1212 if (master) browser.focusLost.connect(this, "saveNote()");
1213 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1214 browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1217 //**************************************************
1219 //**************************************************
1220 private void setupShortcut(QShortcut action, String text) {
1221 if (!Global.shortcutKeys.containsAction(text))
1223 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1226 //***************************************************************
1227 //***************************************************************
1228 //* Settings and look & feel
1229 //***************************************************************
1230 //***************************************************************
1231 @SuppressWarnings("unused")
1232 private void settings() {
1233 logger.log(logger.HIGH, "Entering NeverNote.settings");
1234 saveNoteColumnPositions();
1235 saveNoteIndexWidth();
1237 ConfigDialog settings = new ConfigDialog(this);
1238 String dateFormat = Global.getDateFormat();
1239 String timeFormat = Global.getTimeFormat();
1241 indexTime = 1000*Global.getIndexThreadSleepInterval();
1242 indexTimer.start(indexTime); // reset indexing timer
1245 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1246 indexRunner.indexNoteBody = Global.indexNoteBody();
1247 indexRunner.indexNoteTitle = Global.indexNoteTitle();
1248 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1249 indexRunner.indexImageRecognition = Global.indexImageRecognition();
1250 if (Global.showTrayIcon() || Global.minimizeOnClose())
1255 if (menuBar.showEditorBar.isChecked())
1256 showEditorButtons(browserWindow);
1258 // Reset the save timer
1259 if (Global.getAutoSaveInterval() > 0)
1260 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1265 // Set special reloads
1266 if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1267 conn.executeSql("Delete from LinkedNotebook");
1268 conn.executeSql("delete from SharedNotebook");
1269 conn.executeSql("Delete from Notebook where linked=true");
1270 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1271 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1276 readOnlyCache.clear();
1277 inkNoteCache.clear();
1278 noteIndexUpdated(true);
1280 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1282 // Restore things to the way they were
1283 private void restoreWindowState(boolean mainWindow) {
1284 // We need to name things or this doesn't work.
1285 setObjectName("NeverNote");
1286 restoreState(Global.restoreState(objectName()));
1287 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1288 browserIndexSplitter.setObjectName("browserIndexSplitter");
1289 leftSplitter1.setObjectName("leftSplitter1");
1291 // Restore the actual positions.
1293 restoreGeometry(Global.restoreGeometry(objectName()));
1294 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1295 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1296 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1299 // Save window positions for the next start
1300 private void saveWindowState() {
1301 Global.saveGeometry(objectName(), saveGeometry());
1302 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1303 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1304 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1305 Global.saveState(objectName(), saveState());
1307 // Load the style sheet
1308 private void loadStyleSheet() {
1309 String styleSheetName = "default.qss";
1310 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1311 styleSheetName = "default-cleanlooks.qss";
1312 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1313 QFile file = new QFile(fileName);
1315 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1316 if (!file.exists()) {
1317 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1318 file = new QFile(fileName);
1320 file.open(OpenModeFlag.ReadOnly);
1321 String styleSheet = file.readAll().toString();
1323 setStyleSheet(styleSheet);
1325 // Save column positions for the next time
1326 private void saveNoteColumnPositions() {
1327 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1328 Global.setColumnPosition("noteTableCreationPosition", position);
1329 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1330 Global.setColumnPosition("noteTableTagPosition", position);
1331 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1332 Global.setColumnPosition("noteTableNotebookPosition", position);
1333 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1334 Global.setColumnPosition("noteTableChangedPosition", position);
1335 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1336 Global.setColumnPosition("noteTableAuthorPosition", position);
1337 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1338 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1339 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1340 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1341 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1342 Global.setColumnPosition("noteTableTitlePosition", position);
1343 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1344 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1345 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1346 Global.setColumnPosition("noteTableGuidPosition", position);
1347 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1348 Global.setColumnPosition("noteTableThumbnailPosition", position);
1349 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1350 Global.setColumnPosition("noteTablePinnedPosition", position);
1353 // Save column widths for the next time
1354 private void saveNoteIndexWidth() {
1356 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1357 Global.setColumnWidth("noteTableCreationPosition", width);
1358 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1359 Global.setColumnWidth("noteTableChangedPosition", width);
1360 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1361 Global.setColumnWidth("noteTableGuidPosition", width);
1362 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1363 Global.setColumnWidth("noteTableNotebookPosition", width);
1364 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1365 Global.setColumnWidth("noteTableTagPosition", width);
1366 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1367 Global.setColumnWidth("noteTableTitlePosition", width);
1368 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1369 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1370 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1371 Global.setColumnWidth("noteTableAuthorPosition", width);
1372 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1373 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1374 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1375 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1376 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1377 Global.setColumnWidth("noteTableThumbnailPosition", width);
1378 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1379 Global.setColumnWidth("noteTableGuidPosition", width);
1380 width = noteTableView.getColumnWidth(Global.noteTablePinnedPosition);
1381 Global.setColumnWidth("noteTablePinnedPosition", width);
1384 @SuppressWarnings("unused")
1385 private void toggleSearchWindow() {
1386 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1387 searchLayout.toggleSearchField();
1388 menuBar.hideSearch.setChecked(searchField.isVisible());
1389 Global.saveWindowVisible("searchField", searchField.isVisible());
1390 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1392 @SuppressWarnings("unused")
1393 private void toggleQuotaWindow() {
1394 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1395 searchLayout.toggleQuotaBar();
1396 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1397 Global.saveWindowVisible("quota", quotaBar.isVisible());
1398 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1400 @SuppressWarnings("unused")
1401 private void toggleZoomWindow() {
1402 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1403 searchLayout.toggleZoom();
1404 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1405 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1406 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1411 //***************************************************************
1412 //***************************************************************
1413 //** These functions deal with Notebook menu items
1414 //***************************************************************
1415 //***************************************************************
1416 // Setup the tree containing the user's notebooks.
1417 private void initializeNotebookTree() {
1418 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1419 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1420 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1421 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1422 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1424 // Listener when a notebook is selected
1425 private void notebookTreeSelection() {
1426 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1427 noteTableView.proxyModel.blocked = true;
1430 clearAttributeFilter();
1431 clearSavedSearchFilter();
1432 if (Global.mimicEvernoteInterface) {
1434 searchField.clear();
1436 menuBar.noteRestoreAction.setVisible(false);
1437 menuBar.notebookEditAction.setEnabled(true);
1438 menuBar.notebookDeleteAction.setEnabled(true);
1439 menuBar.notebookPublishAction.setEnabled(true);
1440 menuBar.notebookShareAction.setEnabled(true);
1441 menuBar.notebookIconAction.setEnabled(true);
1442 menuBar.notebookStackAction.setEnabled(true);
1443 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1444 selectedNotebookGUIDs.clear();
1446 String stackName = "";
1447 if (selections.size() > 0) {
1448 guid = (selections.get(0).text(2));
1449 stackName = selections.get(0).text(0);
1451 if (!Global.mimicEvernoteInterface) {
1452 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1453 if (selections.size()==0) {
1454 selectedNotebookGUIDs.clear();
1455 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1456 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1458 menuBar.notebookEditAction.setEnabled(false);
1459 menuBar.notebookDeleteAction.setEnabled(false);
1460 menuBar.notebookStackAction.setEnabled(false);
1461 menuBar.notebookIconAction.setEnabled(false);
1464 if (!guid.equals("") && !guid.equals("STACK")) {
1465 selectedNotebookGUIDs.add(guid);
1466 menuBar.notebookIconAction.setEnabled(true);
1468 menuBar.notebookIconAction.setEnabled(true);
1469 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1470 Notebook book = listManager.getNotebookIndex().get(j);
1471 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1472 selectedNotebookGUIDs.add(book.getGuid());
1475 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1476 listManager.loadNotesIndex();
1477 noteIndexUpdated(false);
1478 refreshEvernoteNote(true);
1479 listManager.refreshCounters = true;
1480 listManager.refreshCounters();
1481 if (selectedNotebookGUIDs.size() == 1) {
1482 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1483 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1485 noteTableView.proxyModel.blocked = true;
1487 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1489 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1492 noteTableView.proxyModel.blocked = false;
1493 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1496 private void clearNotebookFilter() {
1497 notebookTree.blockSignals(true);
1498 notebookTree.clearSelection();
1499 menuBar.noteRestoreAction.setVisible(false);
1500 menuBar.notebookEditAction.setEnabled(false);
1501 menuBar.notebookDeleteAction.setEnabled(false);
1502 selectedNotebookGUIDs.clear();
1503 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1504 notebookTree.blockSignals(false);
1506 // Triggered when the notebook DB has been updated
1507 private void notebookIndexUpdated() {
1508 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1510 // Get the possible icons
1511 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1512 notebookTree.setIcons(icons);
1514 if (selectedNotebookGUIDs == null)
1515 selectedNotebookGUIDs = new ArrayList<String>();
1516 List<Notebook> books = conn.getNotebookTable().getAll();
1517 for (int i=books.size()-1; i>=0; i--) {
1518 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1519 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1521 j=listManager.getArchiveNotebookIndex().size();
1527 listManager.countNotebookResults(listManager.getNoteIndex());
1528 notebookTree.blockSignals(true);
1529 notebookTree.load(books, listManager.getLocalNotebooks());
1530 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1531 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1533 selectedNotebookGUIDs.remove(i);
1535 listManager.refreshCounters = true;
1536 listManager.refreshCounters();
1537 notebookTree.blockSignals(false);
1539 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1541 // Show/Hide note information
1542 @SuppressWarnings("unused")
1543 private void toggleNotebookWindow() {
1544 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1545 searchLayout.toggleNotebook();
1546 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1547 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1548 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1550 // Add a new notebook
1551 @SuppressWarnings("unused")
1552 private void addNotebook() {
1553 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1554 NotebookEdit edit = new NotebookEdit();
1555 edit.setNotebooks(listManager.getNotebookIndex());
1558 if (!edit.okPressed())
1561 Calendar currentTime = new GregorianCalendar();
1562 Long l = new Long(currentTime.getTimeInMillis());
1563 String randint = new String(Long.toString(l));
1565 Notebook newBook = new Notebook();
1566 newBook.setUpdateSequenceNum(0);
1567 newBook.setGuid(randint);
1568 newBook.setName(edit.getNotebook());
1569 newBook.setServiceCreated(new Date().getTime());
1570 newBook.setServiceUpdated(new Date().getTime());
1571 newBook.setDefaultNotebook(false);
1572 newBook.setPublished(false);
1574 listManager.getNotebookIndex().add(newBook);
1576 listManager.getLocalNotebooks().add(newBook.getGuid());
1577 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1578 notebookIndexUpdated();
1579 listManager.countNotebookResults(listManager.getNoteIndex());
1580 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1581 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1583 // Edit an existing notebook
1584 @SuppressWarnings("unused")
1585 private void stackNotebook() {
1586 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1587 StackNotebook edit = new StackNotebook();
1589 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1590 QTreeWidgetItem currentSelection;
1591 for (int i=0; i<selections.size(); i++) {
1592 currentSelection = selections.get(0);
1593 String guid = currentSelection.text(2);
1594 if (guid.equalsIgnoreCase("")) {
1595 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1598 if (guid.equalsIgnoreCase("STACK")) {
1599 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1604 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1609 if (!edit.okPressed())
1612 String stack = edit.getStackName();
1614 for (int i=0; i<selections.size(); i++) {
1615 currentSelection = selections.get(i);
1616 String guid = currentSelection.text(2);
1617 listManager.updateNotebookStack(guid, stack);
1619 notebookIndexUpdated();
1620 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1622 // Edit an existing notebook
1623 @SuppressWarnings("unused")
1624 private void editNotebook() {
1625 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1626 NotebookEdit edit = new NotebookEdit();
1628 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1629 QTreeWidgetItem currentSelection;
1630 currentSelection = selections.get(0);
1631 edit.setNotebook(currentSelection.text(0));
1633 String guid = currentSelection.text(2);
1634 if (!guid.equalsIgnoreCase("STACK")) {
1635 edit.setTitle(tr("Edit Notebook"));
1636 edit.setNotebooks(listManager.getNotebookIndex());
1637 edit.setLocalCheckboxEnabled(false);
1638 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1639 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1640 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1641 i=listManager.getNotebookIndex().size();
1645 edit.setTitle(tr("Edit Stack"));
1646 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1647 edit.hideLocalCheckbox();
1648 edit.hideDefaultCheckbox();
1653 if (!edit.okPressed())
1657 if (guid.equalsIgnoreCase("STACK")) {
1658 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1659 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1660 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1661 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1662 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1664 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1665 currentSelection.setText(0, edit.getNotebook());
1669 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1670 currentSelection.setText(0, edit.getNotebook());
1672 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1673 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1674 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1675 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1676 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1677 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1678 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1679 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1681 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1682 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1683 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1684 linkedNotebook.setShareName(edit.getNotebook());
1685 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1687 i=listManager.getNotebookIndex().size();
1691 // Build a list of non-closed notebooks
1692 List<Notebook> nbooks = new ArrayList<Notebook>();
1693 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1694 boolean found=false;
1695 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1696 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1700 nbooks.add(listManager.getNotebookIndex().get(i));
1704 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1705 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1706 browserWindow.setNotebookList(filteredBooks);
1707 Iterator<String> set = externalWindows.keySet().iterator();
1708 while(set.hasNext())
1709 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1710 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1712 // Publish a notebook
1713 @SuppressWarnings("unused")
1714 private void publishNotebook() {
1715 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1716 QTreeWidgetItem currentSelection;
1717 currentSelection = selections.get(0);
1718 String guid = currentSelection.text(2);
1720 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1725 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1726 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1727 n = listManager.getNotebookIndex().get(i);
1729 i = listManager.getNotebookIndex().size();
1735 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1738 if (!publish.okClicked())
1741 Publishing p = publish.getPublishing();
1742 boolean isPublished = !publish.isStopPressed();
1743 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1744 n.setPublished(isPublished);
1746 listManager.getNotebookIndex().set(position, n);
1747 notebookIndexUpdated();
1749 // Publish a notebook
1750 @SuppressWarnings("unused")
1751 private void shareNotebook() {
1752 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1753 QTreeWidgetItem currentSelection;
1754 currentSelection = selections.get(0);
1755 String guid = currentSelection.text(2);
1757 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1761 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1762 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1763 n = listManager.getNotebookIndex().get(i);
1764 i = listManager.getNotebookIndex().size();
1768 String authToken = null;
1769 if (syncRunner.isConnected)
1770 authToken = syncRunner.authToken;
1771 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1776 // Delete an existing notebook
1777 @SuppressWarnings("unused")
1778 private void deleteNotebook() {
1779 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1780 boolean stacksFound = false;
1781 boolean notebooksFound = false;
1782 boolean assigned = false;
1783 // Check if any notes have this notebook
1784 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1785 for (int i=0; i<selections.size(); i++) {
1786 QTreeWidgetItem currentSelection;
1787 currentSelection = selections.get(i);
1788 String guid = currentSelection.text(2);
1789 if (!guid.equalsIgnoreCase("STACK")) {
1790 notebooksFound = true;
1791 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1792 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1793 if (noteGuid.equals(guid)) {
1795 j=listManager.getNoteIndex().size();
1796 i=selections.size();
1804 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1805 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1809 if (conn.getNotebookTable().getAll().size() == 1) {
1810 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1814 // If all notebooks are clear, verify the delete
1815 String msg1 = new String(tr("Delete selected notebooks?"));
1816 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1817 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1818 " not deleted unless selected?"));
1820 if (stacksFound && notebooksFound)
1822 if (!stacksFound && notebooksFound)
1824 if (stacksFound && !notebooksFound)
1826 if (QMessageBox.question(this, tr("Confirmation"), msg,
1827 QMessageBox.StandardButton.Yes,
1828 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1832 // If confirmed, delete the notebook
1833 for (int i=selections.size()-1; i>=0; i--) {
1834 QTreeWidgetItem currentSelection;
1835 currentSelection = selections.get(i);
1836 String guid = currentSelection.text(2);
1837 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1838 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1839 listManager.renameStack(currentSelection.text(0), "");
1841 conn.getNotebookTable().expungeNotebook(guid, true);
1842 listManager.deleteNotebook(guid);
1846 notebookIndexUpdated();
1847 // notebookTreeSelection();
1848 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1849 // listManager.countNotebookResults(listManager.getNoteIndex());
1850 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1852 // A note's notebook has been updated
1853 @SuppressWarnings("unused")
1854 private void updateNoteNotebook(String guid, String notebookGuid) {
1856 // Update the list manager
1857 listManager.updateNoteNotebook(guid, notebookGuid);
1858 listManager.countNotebookResults(listManager.getNoteIndex());
1859 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1861 // Find the name of the notebook
1862 String notebookName = null;
1863 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1864 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1865 notebookName = listManager.getNotebookIndex().get(i).getName();
1870 // If we found the name, update the browser window
1871 if (notebookName != null) {
1872 updateListNoteNotebook(guid, notebookName);
1873 if (guid.equals(currentNoteGuid)) {
1874 int pos = browserWindow.notebookBox.findText(notebookName);
1876 browserWindow.notebookBox.setCurrentIndex(pos);
1880 // If we're dealing with the current note, then we need to be sure and update the notebook there
1881 if (guid.equals(currentNoteGuid)) {
1882 if (currentNote != null) {
1883 currentNote.setNotebookGuid(notebookGuid);
1887 // Open/close notebooks
1888 @SuppressWarnings("unused")
1889 private void closeNotebooks() {
1890 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1892 if (!na.okClicked())
1896 listManager.getArchiveNotebookIndex().clear();
1898 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1899 String text = na.getClosedBookList().takeItem(i).text();
1900 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1901 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1902 Notebook n = listManager.getNotebookIndex().get(j);
1903 conn.getNotebookTable().setArchived(n.getGuid(),true);
1904 listManager.getArchiveNotebookIndex().add(n);
1905 j=listManager.getNotebookIndex().size();
1910 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1911 String text = na.getOpenBookList().takeItem(i).text();
1912 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1913 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1914 Notebook n = listManager.getNotebookIndex().get(j);
1915 conn.getNotebookTable().setArchived(n.getGuid(),false);
1916 j=listManager.getNotebookIndex().size();
1920 notebookTreeSelection();
1921 listManager.loadNotesIndex();
1922 notebookIndexUpdated();
1923 noteIndexUpdated(false);
1924 reloadTagTree(true);
1925 // noteIndexUpdated(false);
1927 // Build a list of non-closed notebooks
1928 List<Notebook> nbooks = new ArrayList<Notebook>();
1929 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1930 boolean found=false;
1931 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1932 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1936 nbooks.add(listManager.getNotebookIndex().get(i));
1939 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1940 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1941 browserWindow.setNotebookList(filteredBooks);
1943 // Update any external windows
1944 Iterator<String> set = externalWindows.keySet().iterator();
1945 while(set.hasNext())
1946 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1950 // Change the notebook's icon
1951 @SuppressWarnings("unused")
1952 private void setNotebookIcon() {
1953 boolean stackSelected = false;
1954 boolean allNotebookSelected = false;
1956 QTreeWidgetItem currentSelection;
1957 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1958 if (selections.size() == 0)
1961 currentSelection = selections.get(0);
1962 String guid = currentSelection.text(2);
1963 if (guid.equalsIgnoreCase(""))
1964 allNotebookSelected = true;
1965 if (guid.equalsIgnoreCase("STACK"))
1966 stackSelected = true;
1968 QIcon currentIcon = currentSelection.icon(0);
1972 if (!stackSelected && !allNotebookSelected) {
1973 icon = conn.getNotebookTable().getIcon(guid);
1975 dialog = new SetIcon(currentIcon, saveLastPath);
1976 dialog.setUseDefaultIcon(true);
1978 dialog = new SetIcon(icon, saveLastPath);
1979 dialog.setUseDefaultIcon(false);
1982 if (stackSelected) {
1983 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1985 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1988 dialog = new SetIcon(currentIcon, saveLastPath);
1989 dialog.setUseDefaultIcon(true);
1991 dialog = new SetIcon(icon, saveLastPath);
1992 dialog.setUseDefaultIcon(false);
1996 if (dialog.okPressed()) {
1997 saveLastPath = dialog.getPath();
1999 QIcon newIcon = dialog.getIcon();
2000 if (stackSelected) {
2001 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
2002 if (newIcon == null) {
2003 newIcon = new QIcon(iconPath+"books2.png");
2005 currentSelection.setIcon(0,newIcon);
2008 if (allNotebookSelected) {
2009 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
2010 if (newIcon == null) {
2011 newIcon = new QIcon(iconPath+"notebook-green.png");
2013 currentSelection.setIcon(0,newIcon);
2016 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
2017 if (newIcon == null) {
2018 boolean isPublished = false;;
2019 boolean found = false;
2020 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
2021 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
2022 isPublished = listManager.getNotebookIndex().get(i).isPublished();
2026 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
2028 currentSelection.setIcon(0, newIcon);
2034 //***************************************************************
2035 //***************************************************************
2036 //** These functions deal with Tag menu items
2037 //***************************************************************
2038 //***************************************************************
2039 // Add a new notebook
2040 @SuppressWarnings("unused")
2041 private void addTag() {
2042 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2043 TagEdit edit = new TagEdit();
2044 edit.setTagList(listManager.getTagIndex());
2046 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2047 QTreeWidgetItem currentSelection = null;
2048 if (selections.size() > 0) {
2049 currentSelection = selections.get(0);
2050 edit.setParentTag(currentSelection.text(0));
2055 if (!edit.okPressed())
2058 Calendar currentTime = new GregorianCalendar();
2059 Long l = new Long(currentTime.getTimeInMillis());
2060 String randint = new String(Long.toString(l));
2062 Tag newTag = new Tag();
2063 newTag.setUpdateSequenceNum(0);
2064 newTag.setGuid(randint);
2065 newTag.setName(edit.getTag());
2066 if (edit.getParentTag().isChecked()) {
2067 newTag.setParentGuid(currentSelection.text(2));
2068 newTag.setParentGuidIsSet(true);
2069 currentSelection.setExpanded(true);
2071 conn.getTagTable().addTag(newTag, true);
2072 listManager.getTagIndex().add(newTag);
2073 reloadTagTree(true);
2075 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2077 @SuppressWarnings("unused")
2078 private void reloadTagTree() {
2079 reloadTagTree(false);
2081 private void reloadTagTree(boolean reload) {
2082 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2083 tagIndexUpdated(reload);
2084 boolean filter = false;
2086 listManager.countTagResults(listManager.getNoteIndex());
2087 if (notebookTree.selectedItems().size() > 0
2088 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2090 if (tagTree.selectedItems().size() > 0)
2092 tagTree.showAllTags(!filter);
2093 tagIndexUpdated(false);
2094 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2096 // Edit an existing tag
2097 @SuppressWarnings("unused")
2098 private void editTag() {
2099 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2100 TagEdit edit = new TagEdit();
2101 edit.setTitle("Edit Tag");
2102 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2103 QTreeWidgetItem currentSelection;
2104 currentSelection = selections.get(0);
2105 edit.setTag(currentSelection.text(0));
2106 edit.setTagList(listManager.getTagIndex());
2109 if (!edit.okPressed())
2112 String guid = currentSelection.text(2);
2113 currentSelection.setText(0,edit.getTag());
2115 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2116 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2117 listManager.getTagIndex().get(i).setName(edit.getTag());
2118 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2119 updateListTagName(guid);
2120 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2121 browserWindow.setTag(getTagNamesForNote(currentNote));
2122 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2126 listManager.reloadNoteTagNames(guid, edit.getTag());
2127 noteIndexUpdated(true);
2128 refreshEvernoteNote(true);
2129 browserWindow.setTag(getTagNamesForNote(currentNote));
2130 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2132 // Delete an existing tag
2133 @SuppressWarnings("unused")
2134 private void deleteTag() {
2135 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2137 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2138 QMessageBox.StandardButton.Yes,
2139 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2143 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2144 for (int i=selections.size()-1; i>=0; i--) {
2145 QTreeWidgetItem currentSelection;
2146 currentSelection = selections.get(i);
2147 removeTagItem(currentSelection.text(2));
2149 tagIndexUpdated(true);
2151 listManager.countTagResults(listManager.getNoteIndex());
2152 // tagTree.updateCounts(listManager.getTagCounter());
2153 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2155 // Remove a tag tree item. Go recursively down & remove the children too
2156 private void removeTagItem(String guid) {
2157 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2158 String parent = listManager.getTagIndex().get(j).getParentGuid();
2159 if (parent != null && parent.equals(guid)) {
2160 //Remove this tag's children
2161 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2164 //Now, remove this tag
2165 removeListTagName(guid);
2166 conn.getTagTable().expungeTag(guid, true);
2167 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2168 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2169 listManager.getTagIndex().remove(a);
2174 // Setup the tree containing the user's tags
2175 private void initializeTagTree() {
2176 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2177 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2178 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2179 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2180 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2181 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2183 // Listener when a tag is selected
2184 private void tagTreeSelection() {
2185 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2188 clearAttributeFilter();
2189 clearSavedSearchFilter();
2191 menuBar.noteRestoreAction.setVisible(false);
2193 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2194 QTreeWidgetItem currentSelection;
2195 selectedTagGUIDs.clear();
2196 for (int i=0; i<selections.size(); i++) {
2197 currentSelection = selections.get(i);
2198 selectedTagGUIDs.add(currentSelection.text(2));
2200 if (selections.size() > 0) {
2201 menuBar.tagEditAction.setEnabled(true);
2202 menuBar.tagDeleteAction.setEnabled(true);
2203 menuBar.tagIconAction.setEnabled(true);
2206 menuBar.tagEditAction.setEnabled(false);
2207 menuBar.tagDeleteAction.setEnabled(false);
2208 menuBar.tagIconAction.setEnabled(true);
2210 if (selections.size() > 1)
2211 menuBar.tagMergeAction.setEnabled(true);
2213 menuBar.tagMergeAction.setEnabled(false);
2214 listManager.setSelectedTags(selectedTagGUIDs);
2215 listManager.loadNotesIndex();
2216 noteIndexUpdated(false);
2217 refreshEvernoteNote(true);
2218 listManager.refreshCounters = true;
2219 listManager.refreshCounters();
2220 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2222 // trigger the tag index to be refreshed
2223 @SuppressWarnings("unused")
2224 private void tagIndexUpdated() {
2225 tagIndexUpdated(true);
2227 private void tagIndexUpdated(boolean reload) {
2228 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2229 if (selectedTagGUIDs == null)
2230 selectedTagGUIDs = new ArrayList<String>();
2232 listManager.reloadTagIndex();
2234 tagTree.blockSignals(true);
2236 tagTree.setIcons(conn.getTagTable().getAllIcons());
2237 tagTree.load(listManager.getTagIndex());
2240 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2241 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2243 selectedTagGUIDs.remove(i);
2245 tagTree.blockSignals(false);
2247 browserWindow.setTag(getTagNamesForNote(currentNote));
2248 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2250 // Show/Hide note information
2251 @SuppressWarnings("unused")
2252 private void toggleTagWindow() {
2253 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2254 if (tagTree.isVisible())
2258 menuBar.hideTags.setChecked(tagTree.isVisible());
2259 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2260 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2262 // A note's tags have been updated
2263 @SuppressWarnings("unused")
2264 private void updateNoteTags(String guid, List<String> tags) {
2265 // Save any new tags. We'll need them later.
2266 List<String> newTags = new ArrayList<String>();
2267 for (int i=0; i<tags.size(); i++) {
2268 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2269 newTags.add(tags.get(i));
2272 listManager.saveNoteTags(guid, tags);
2273 listManager.countTagResults(listManager.getNoteIndex());
2274 StringBuffer names = new StringBuffer("");
2275 for (int i=0; i<tags.size(); i++) {
2276 names = names.append(tags.get(i));
2277 if (i<tags.size()-1) {
2278 names.append(Global.tagDelimeter + " ");
2281 browserWindow.setTag(names.toString());
2284 // Now, we need to add any new tags to the tag tree
2285 for (int i=0; i<newTags.size(); i++)
2286 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2288 // Get a string containing all tag names for a note
2289 private String getTagNamesForNote(Note n) {
2290 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2291 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2293 StringBuffer buffer = new StringBuffer(100);
2294 Vector<String> v = new Vector<String>();
2295 List<String> guids = n.getTagGuids();
2300 for (int i=0; i<guids.size(); i++) {
2301 v.add(listManager.getTagNameByGuid(guids.get(i)));
2303 Comparator<String> comparator = Collections.reverseOrder();
2304 Collections.sort(v,comparator);
2305 Collections.reverse(v);
2307 for (int i = 0; i<v.size(); i++) {
2309 buffer.append(", ");
2310 buffer.append(v.get(i));
2313 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2314 return buffer.toString();
2316 // Tags were added via dropping notes from the note list
2317 @SuppressWarnings("unused")
2318 private void tagsAdded(String noteGuid, String tagGuid) {
2319 String tagName = null;
2320 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2321 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2322 tagName = listManager.getTagIndex().get(i).getName();
2323 i=listManager.getTagIndex().size();
2326 if (tagName == null)
2329 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2330 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2331 List<String> tagNames = new ArrayList<String>();
2332 tagNames.add(new String(tagName));
2333 Note n = listManager.getMasterNoteIndex().get(i);
2334 for (int j=0; j<n.getTagNames().size(); j++) {
2335 tagNames.add(new String(n.getTagNames().get(j)));
2337 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2338 if (n.getGuid().equals(currentNoteGuid)) {
2339 Collections.sort(tagNames);
2340 String display = "";
2341 for (int j=0; j<tagNames.size(); j++) {
2342 display = display+tagNames.get(j);
2343 if (j+2<tagNames.size())
2344 display = display+Global.tagDelimeter+" ";
2346 browserWindow.setTag(display);
2348 i=listManager.getMasterNoteIndex().size();
2353 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2355 private void clearTagFilter() {
2356 tagTree.blockSignals(true);
2357 tagTree.clearSelection();
2358 menuBar.noteRestoreAction.setVisible(false);
2359 menuBar.tagEditAction.setEnabled(false);
2360 menuBar.tagMergeAction.setEnabled(false);
2361 menuBar.tagDeleteAction.setEnabled(false);
2362 menuBar.tagIconAction.setEnabled(false);
2363 selectedTagGUIDs.clear();
2364 listManager.setSelectedTags(selectedTagGUIDs);
2365 tagTree.blockSignals(false);
2367 // Change the icon for a tag
2368 @SuppressWarnings("unused")
2369 private void setTagIcon() {
2370 QTreeWidgetItem currentSelection;
2371 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2372 if (selections.size() == 0)
2375 currentSelection = selections.get(0);
2376 String guid = currentSelection.text(2);
2378 QIcon currentIcon = currentSelection.icon(0);
2379 QIcon icon = conn.getTagTable().getIcon(guid);
2382 dialog = new SetIcon(currentIcon, saveLastPath);
2383 dialog.setUseDefaultIcon(true);
2385 dialog = new SetIcon(icon, saveLastPath);
2386 dialog.setUseDefaultIcon(false);
2389 if (dialog.okPressed()) {
2390 saveLastPath = dialog.getPath();
2391 QIcon newIcon = dialog.getIcon();
2392 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2393 if (newIcon == null)
2394 newIcon = new QIcon(iconPath+"tag.png");
2395 currentSelection.setIcon(0, newIcon);
2400 @SuppressWarnings("unused")
2401 private void mergeTags() {
2402 List<Tag> tags = new ArrayList<Tag>();
2403 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2404 for (int i=0; i<selections.size(); i++) {
2405 Tag record = new Tag();
2406 record.setGuid(selections.get(i).text(2));
2407 record.setName(selections.get(i).text(0));
2411 TagMerge mergeDialog = new TagMerge(tags);
2413 if (!mergeDialog.okClicked())
2415 String newGuid = mergeDialog.getNewTagGuid();
2417 for (int i=0; i<tags.size(); i++) {
2418 if (!tags.get(i).getGuid().equals(newGuid)) {
2419 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2420 for (int j=0; j<noteGuids.size(); j++) {
2421 String noteGuid = noteGuids.get(j);
2422 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2423 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2424 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2428 listManager.reloadIndexes();
2431 //***************************************************************
2432 //***************************************************************
2433 //** These functions deal with Saved Search menu items
2434 //***************************************************************
2435 //***************************************************************
2436 // Add a new notebook
2437 @SuppressWarnings("unused")
2438 private void addSavedSearch() {
2439 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2440 SavedSearchEdit edit = new SavedSearchEdit();
2441 edit.setSearchList(listManager.getSavedSearchIndex());
2444 if (!edit.okPressed())
2447 Calendar currentTime = new GregorianCalendar();
2448 Long l = new Long(currentTime.getTimeInMillis());
2449 String randint = new String(Long.toString(l));
2451 SavedSearch search = new SavedSearch();
2452 search.setUpdateSequenceNum(0);
2453 search.setGuid(randint);
2454 search.setName(edit.getName());
2455 search.setQuery(edit.getQuery());
2456 search.setFormat(QueryFormat.USER);
2457 listManager.getSavedSearchIndex().add(search);
2458 conn.getSavedSearchTable().addSavedSearch(search, true);
2459 savedSearchIndexUpdated();
2460 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2462 // Edit an existing tag
2463 @SuppressWarnings("unused")
2464 private void editSavedSearch() {
2465 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2466 SavedSearchEdit edit = new SavedSearchEdit();
2467 edit.setTitle(tr("Edit Search"));
2468 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2469 QTreeWidgetItem currentSelection;
2470 currentSelection = selections.get(0);
2471 String guid = currentSelection.text(1);
2472 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2473 edit.setName(currentSelection.text(0));
2474 edit.setQuery(s.getQuery());
2475 edit.setSearchList(listManager.getSavedSearchIndex());
2478 if (!edit.okPressed())
2481 List<SavedSearch> list = listManager.getSavedSearchIndex();
2482 SavedSearch search = null;
2483 boolean found = false;
2484 for (int i=0; i<list.size(); i++) {
2485 search = list.get(i);
2486 if (search.getGuid().equals(guid)) {
2493 search.setName(edit.getName());
2494 search.setQuery(edit.getQuery());
2495 conn.getSavedSearchTable().updateSavedSearch(search, true);
2496 savedSearchIndexUpdated();
2497 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2499 // Delete an existing tag
2500 @SuppressWarnings("unused")
2501 private void deleteSavedSearch() {
2502 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2504 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2505 QMessageBox.StandardButton.Yes,
2506 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2510 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2511 for (int i=selections.size()-1; i>=0; i--) {
2512 QTreeWidgetItem currentSelection;
2513 currentSelection = selections.get(i);
2514 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2515 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2516 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2517 listManager.getSavedSearchIndex().remove(j);
2518 j=listManager.getSavedSearchIndex().size()+1;
2521 selections.remove(i);
2523 savedSearchIndexUpdated();
2524 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2526 // Setup the tree containing the user's tags
2527 private void initializeSavedSearchTree() {
2528 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2529 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2530 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2532 // Listener when a tag is selected
2533 @SuppressWarnings("unused")
2534 private void savedSearchTreeSelection() {
2535 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2537 clearNotebookFilter();
2540 clearAttributeFilter();
2542 String currentGuid = selectedSavedSearchGUID;
2543 menuBar.savedSearchEditAction.setEnabled(true);
2544 menuBar.savedSearchDeleteAction.setEnabled(true);
2545 menuBar.savedSearchIconAction.setEnabled(true);
2546 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2547 QTreeWidgetItem currentSelection;
2548 selectedSavedSearchGUID = "";
2549 for (int i=0; i<selections.size(); i++) {
2550 currentSelection = selections.get(i);
2551 if (currentSelection.text(1).equals(currentGuid)) {
2552 currentSelection.setSelected(false);
2554 selectedSavedSearchGUID = currentSelection.text(1);
2556 // i = selections.size() +1;
2559 // There is the potential for no notebooks to be selected if this
2560 // happens then we make it look like all notebooks were selecetd.
2561 // If that happens, just select the "all notebooks"
2562 if (selections.size()==0) {
2563 clearSavedSearchFilter();
2565 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2567 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2569 private void clearSavedSearchFilter() {
2570 menuBar.savedSearchEditAction.setEnabled(false);
2571 menuBar.savedSearchDeleteAction.setEnabled(false);
2572 menuBar.savedSearchIconAction.setEnabled(false);
2573 savedSearchTree.blockSignals(true);
2574 savedSearchTree.clearSelection();
2575 savedSearchTree.blockSignals(false);
2576 selectedSavedSearchGUID = "";
2577 searchField.setEditText("");
2578 searchPerformed = false;
2579 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2581 // trigger the tag index to be refreshed
2582 private void savedSearchIndexUpdated() {
2583 if (selectedSavedSearchGUID == null)
2584 selectedSavedSearchGUID = new String();
2585 savedSearchTree.blockSignals(true);
2586 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2587 savedSearchTree.load(listManager.getSavedSearchIndex());
2588 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2589 savedSearchTree.blockSignals(false);
2591 // trigger when the saved search selection changes
2592 @SuppressWarnings("unused")
2593 private void updateSavedSearchSelection() {
2594 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2596 menuBar.savedSearchEditAction.setEnabled(true);
2597 menuBar.savedSearchDeleteAction.setEnabled(true);
2598 menuBar.savedSearchIconAction.setEnabled(true);
2599 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2601 if (selections.size() > 0) {
2602 menuBar.savedSearchEditAction.setEnabled(true);
2603 menuBar.savedSearchDeleteAction.setEnabled(true);
2604 menuBar.savedSearchIconAction.setEnabled(true);
2605 selectedSavedSearchGUID = selections.get(0).text(1);
2606 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2607 searchField.setEditText(s.getQuery());
2609 menuBar.savedSearchEditAction.setEnabled(false);
2610 menuBar.savedSearchDeleteAction.setEnabled(false);
2611 menuBar.savedSearchIconAction.setEnabled(false);
2612 selectedSavedSearchGUID = "";
2613 searchField.setEditText("");
2615 searchFieldChanged();
2617 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2621 // Show/Hide note information
2622 @SuppressWarnings("unused")
2623 private void toggleSavedSearchWindow() {
2624 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2625 if (savedSearchTree.isVisible())
2626 savedSearchTree.hide();
2628 savedSearchTree.show();
2629 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2631 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2632 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2634 // Change the icon for a saved search
2635 @SuppressWarnings("unused")
2636 private void setSavedSearchIcon() {
2637 QTreeWidgetItem currentSelection;
2638 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2639 if (selections.size() == 0)
2642 currentSelection = selections.get(0);
2643 String guid = currentSelection.text(1);
2645 QIcon currentIcon = currentSelection.icon(0);
2646 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2649 dialog = new SetIcon(currentIcon, saveLastPath);
2650 dialog.setUseDefaultIcon(true);
2652 dialog = new SetIcon(icon, saveLastPath);
2653 dialog.setUseDefaultIcon(false);
2656 if (dialog.okPressed()) {
2657 saveLastPath = dialog.getPath();
2658 QIcon newIcon = dialog.getIcon();
2659 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2660 if (newIcon == null)
2661 newIcon = new QIcon(iconPath+"search.png");
2662 currentSelection.setIcon(0, newIcon);
2670 //***************************************************************
2671 //***************************************************************
2672 //** These functions deal with Help menu & tool menu items
2673 //***************************************************************
2674 //***************************************************************
2675 // Show database status
2676 @SuppressWarnings("unused")
2677 private void databaseStatus() {
2679 indexRunner.interrupt = true;
2680 int dirty = conn.getNoteTable().getDirtyCount();
2681 int unindexed = conn.getNoteTable().getUnindexedCount();
2682 DatabaseStatus status = new DatabaseStatus();
2683 status.setUnsynchronized(dirty);
2684 status.setUnindexed(unindexed);
2685 status.setNoteCount(conn.getNoteTable().getNoteCount());
2686 status.setNotebookCount(listManager.getNotebookIndex().size());
2687 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2688 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2689 status.setTagCount(listManager.getTagIndex().size());
2690 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2691 status.setWordCount(conn.getWordsTable().getWordCount());
2695 // Compact the database
2696 @SuppressWarnings("unused")
2697 private void compactDatabase() {
2698 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2699 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2700 "but please be aware that depending upon the size of your database this can be time consuming " +
2701 "and NixNote will be unresponsive until it is complete. Do you wish to continue?"),
2702 QMessageBox.StandardButton.Yes,
2703 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2706 setMessage("Compacting database.");
2708 listManager.compactDatabase();
2710 setMessage("Database compact is complete.");
2711 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2713 @SuppressWarnings("unused")
2714 private void accountInformation() {
2715 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2716 AccountDialog dialog = new AccountDialog();
2718 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2720 @SuppressWarnings("unused")
2721 private void releaseNotes() {
2722 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2723 QDialog dialog = new QDialog(this);
2724 QHBoxLayout layout = new QHBoxLayout();
2725 QTextEdit textBox = new QTextEdit();
2726 layout.addWidget(textBox);
2727 textBox.setReadOnly(true);
2728 QFile file = new QFile(Global.getFileManager().getProgramDirPath("release.txt"));
2729 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2730 QIODevice.OpenModeFlag.Text)))
2732 textBox.setText(file.readAll().toString());
2734 dialog.setWindowTitle(tr("Release Notes"));
2735 dialog.setLayout(layout);
2737 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2739 // Called when user picks Log from the help menu
2740 @SuppressWarnings("unused")
2741 private void logger() {
2742 logger.log(logger.HIGH, "Entering NeverNote.logger");
2743 LogFileDialog dialog = new LogFileDialog(emitLog);
2745 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2747 // Menu option "help/about" was selected
2748 @SuppressWarnings("unused")
2749 private void about() {
2750 logger.log(logger.HIGH, "Entering NeverNote.about");
2751 QMessageBox.about(this,
2752 tr("About NixNote"),
2753 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2757 +"Open Source Evernote Client.<br><br>"
2758 +"Licensed under GPL v2. <br><hr><br>"
2759 +"</center>Evernote is copyright 2001-2012 by Evernote Corporation<br>"
2760 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2761 +"PDFRenderer is licened under the LGPL<br>"
2762 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2763 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2764 +"Jazzy is licened under the LGPL<br>"
2765 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2766 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2767 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2768 logger.log(logger.HIGH, "Leaving NeverNote.about");
2770 // Hide the entire left hand side
2771 @SuppressWarnings("unused")
2772 private void toggleLeftSide() {
2775 hidden = !menuBar.hideLeftSide.isChecked();
2776 menuBar.hideLeftSide.setChecked(!hidden);
2779 leftSplitter1.setHidden(true);
2781 leftSplitter1.setHidden(false);
2783 Global.saveWindowVisible("leftPanel", hidden);
2786 public void checkForUpdates() {
2787 // Send off thread to check for a new version
2788 versionChecker = new QNetworkAccessManager(this);
2789 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2790 QNetworkRequest request = new QNetworkRequest();
2791 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2792 versionChecker.get(request);
2794 @SuppressWarnings("unused")
2795 private void upgradeFileRead(QNetworkReply reply) {
2796 if (!reply.isReadable())
2799 String winVersion = Global.version;
2800 String osxVersion = Global.version;
2801 String linuxVersion = Global.version;
2802 String linux64Version = Global.version;
2803 String version = Global.version;
2805 // Determine the versions available
2806 QByteArray data = reply.readLine();
2807 while (data != null && !reply.atEnd()) {
2808 String line = data.toString();
2810 if (line.contains(":"))
2811 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2814 if (line.toLowerCase().contains("windows"))
2815 winVersion = lineVersion;
2816 else if (line.toLowerCase().contains("os-x"))
2817 osxVersion = lineVersion;
2818 else if (line.toLowerCase().contains("linux amd64"))
2819 linux64Version = lineVersion;
2820 else if (line.toLowerCase().contains("linux i386"))
2821 linuxVersion = lineVersion;
2822 else if (line.toLowerCase().contains("default"))
2823 version = lineVersion;
2825 // Read the next line
2826 data = reply.readLine();
2829 // Now we need to determine what system we are on.
2830 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2831 version = winVersion;
2832 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2833 version = osxVersion;
2834 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2835 if (System.getProperty("os.arch").contains("amd64") ||
2836 System.getProperty("os.arch").contains("x86_64"))
2837 version = linux64Version;
2839 version = linuxVersion;
2843 for (String validVersion : Global.validVersions) {
2844 if (version.equals(validVersion))
2848 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2850 if (dialog.remindMe())
2851 Global.setCheckVersionUpgrade(true);
2853 Global.setCheckVersionUpgrade(false);
2857 //***************************************************************
2858 //***************************************************************
2859 //** These functions deal with the Toolbar
2860 //***************************************************************
2861 //***************************************************************
2862 @SuppressWarnings("unused")
2863 private void focusSearch() {
2864 searchField.setFocus();
2867 // Text in the search bar has been cleared
2868 private void searchFieldCleared() {
2871 // This is done because we want to force a reload of
2872 // images. Some images we may want to highlight the text.
2873 readOnlyCache.clear();
2874 inkNoteCache.clear();
2876 QWebSettings.setMaximumPagesInCache(0);
2877 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2879 searchField.setEditText("");
2880 saveNoteColumnPositions();
2881 saveNoteIndexWidth();
2882 noteIndexUpdated(true);
2883 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2884 currentNote = listManager.getNoteIndex().get(0);
2885 currentNoteGuid = currentNote.getGuid();
2887 refreshEvernoteNote(true);
2888 if (currentNote != null)
2889 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2891 // text in the search bar changed. We only use this to tell if it was cleared,
2892 // otherwise we trigger off searchFieldChanged.
2893 @SuppressWarnings("unused")
2894 private void searchFieldTextChanged(String text) {
2895 QWebSettings.setMaximumPagesInCache(0);
2896 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2898 if (text.trim().equals("")) {
2899 searchFieldCleared();
2900 if (searchPerformed) {
2902 // This is done because we want to force a reload of
2903 // images. Some images we may want to highlight the text.
2905 readOnlyCache.clear();
2906 inkNoteCache.clear();
2908 listManager.setEnSearch("");
2909 listManager.loadNotesIndex();
2910 refreshEvernoteNote(true);
2911 noteIndexUpdated(false);
2912 refreshEvernoteNote(true);
2914 searchPerformed = false;
2917 // Text in the toolbar has changed
2918 private void searchFieldChanged() {
2919 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2921 readOnlyCache.clear();
2922 inkNoteCache.clear();
2923 saveNoteColumnPositions();
2924 saveNoteIndexWidth();
2925 String text = searchField.currentText();
2926 listManager.setEnSearch(text.trim());
2927 listManager.loadNotesIndex();
2928 noteIndexUpdated(false);
2930 refreshEvernoteNote(true);
2931 searchPerformed = true;
2933 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2936 // Build the window tool bar
2937 private void setupToolBar() {
2938 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2939 toolBar = addToolBar(tr("Tool Bar"));
2940 toolBar.setObjectName("toolBar");
2941 menuBar.setupToolBarVisible();
2942 if (!Global.isWindowVisible("toolBar"))
2943 toolBar.setVisible(false);
2945 toolBar.setVisible(true);
2947 // toolBar.addWidget(menuBar);
2948 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2949 // toolBar.addSeparator();
2950 prevButton = toolBar.addAction(tr("Previous"));
2951 QIcon prevIcon = new QIcon(iconPath+"back.png");
2952 prevButton.setIcon(prevIcon);
2953 prevButton.triggered.connect(this, "previousViewedAction()");
2954 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2956 nextButton = toolBar.addAction(tr("Next"));
2957 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2958 nextButton.setIcon(nextIcon);
2959 nextButton.triggered.connect(this, "nextViewedAction()");
2960 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2962 upButton = toolBar.addAction(tr("Up"));
2963 QIcon upIcon = new QIcon(iconPath+"up.png");
2964 upButton.setIcon(upIcon);
2965 upButton.triggered.connect(this, "upAction()");
2966 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2969 downButton = toolBar.addAction(tr("Down"));
2970 QIcon downIcon = new QIcon(iconPath+"down.png");
2971 downButton.setIcon(downIcon);
2972 downButton.triggered.connect(this, "downAction()");
2973 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2975 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2976 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2977 synchronizeIconAngle = 0;
2978 synchronizeButton.triggered.connect(this, "evernoteSync()");
2979 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2981 printButton = toolBar.addAction(tr("Print"));
2982 QIcon printIcon = new QIcon(iconPath+"print.png");
2983 printButton.setIcon(printIcon);
2984 printButton.triggered.connect(this, "printNote()");
2985 togglePrintButton(Global.isToolbarButtonVisible("print"));
2987 tagButton = toolBar.addAction(tr("Tag"));
2988 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2989 tagButton.setIcon(tagIcon);
2990 tagButton.triggered.connect(browserWindow, "modifyTags()");
2991 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2993 attributeButton = toolBar.addAction(tr("Attributes"));
2994 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2995 attributeButton.setIcon(attributeIcon);
2996 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2997 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2999 emailButton = toolBar.addAction(tr("Email"));
3000 QIcon emailIcon = new QIcon(iconPath+"email.png");
3001 emailButton.setIcon(emailIcon);
3002 emailButton.triggered.connect(this, "emailNote()");
3003 toggleEmailButton(Global.isToolbarButtonVisible("email"));
3005 deleteButton = toolBar.addAction(tr("Delete"));
3006 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
3007 deleteButton.setIcon(deleteIcon);
3008 deleteButton.triggered.connect(this, "deleteNote()");
3009 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
3011 newButton = toolBar.addAction(tr("New"));
3012 QIcon newIcon = new QIcon(iconPath+"new.png");
3013 newButton.triggered.connect(this, "addNote()");
3014 newButton.setIcon(newIcon);
3015 toggleNewButton(Global.isToolbarButtonVisible("new"));
3017 allNotesButton = toolBar.addAction(tr("All Notes"));
3018 QIcon allIcon = new QIcon(iconPath+"books.png");
3019 allNotesButton.triggered.connect(this, "allNotes()");
3020 allNotesButton.setIcon(allIcon);
3021 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
3023 //toolBar.addSeparator();
3024 //toolBar.addWidget(new QLabel(tr("Quota:")));
3025 //toolBar.addWidget(quotaBar);
3026 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
3028 //toolBar.addSeparator();
3030 //toolBar.addWidget(new QLabel(tr("Zoom")));
3031 //toolBar.addWidget(zoomSpinner);
3033 //toolBar.addWidget(new QLabel(" "));
3034 //toolBar.addSeparator();
3035 //toolBar.addWidget(new QLabel(tr(" Search:")));
3036 //toolBar.addWidget(searchField);
3037 QSizePolicy sizePolicy = new QSizePolicy();
3038 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
3039 QLabel spacer = new QLabel("");
3040 spacer.setSizePolicy(sizePolicy);
3041 toolBar.addWidget(spacer);
3042 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3044 //searchClearButton = toolBar.addAction("Search Clear");
3045 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3046 //searchClearButton.setIcon(searchClearIcon);
3047 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3048 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3050 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3052 // Update the sychronize button picture
3054 public QMenu createPopupMenu() {
3055 QMenu contextMenu = super.createPopupMenu();
3057 contextMenu.addSeparator();
3058 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3059 contextMenu.addAction(prevAction);
3060 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3062 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3063 contextMenu.addAction(nextAction);
3064 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3066 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3067 contextMenu.addAction(upAction);
3068 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3070 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3071 contextMenu.addAction(downAction);
3072 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3074 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3075 contextMenu.addAction(synchronizeAction);
3076 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3078 QAction printAction = addContextAction("print", tr("Print"));
3079 contextMenu.addAction(printAction);
3080 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3082 QAction tagAction = addContextAction("tag", tr("Tag"));
3083 contextMenu.addAction(tagAction);
3084 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3086 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3087 contextMenu.addAction(attributeAction);
3088 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3090 QAction emailAction = addContextAction("email", tr("Email"));
3091 contextMenu.addAction(emailAction);
3092 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3094 QAction deleteAction = addContextAction("delete", tr("Delete"));
3095 contextMenu.addAction(deleteAction);
3096 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3098 QAction newAction = addContextAction("new", tr("Add"));
3099 contextMenu.addAction(newAction);
3100 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3102 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3103 contextMenu.addAction(allNotesAction);
3104 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3106 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3107 contextMenu.addAction(searchClearAction);
3108 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3113 private QAction addContextAction(String config, String name) {
3114 QAction newAction = new QAction(this);
3115 newAction.setText(name);
3116 newAction.setCheckable(true);
3117 newAction.setChecked(Global.isToolbarButtonVisible(config));
3120 private void togglePrevArrowButton(Boolean toggle) {
3121 prevButton.setVisible(toggle);
3122 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3124 private void toggleNextArrowButton(Boolean toggle) {
3125 nextButton.setVisible(toggle);
3126 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3128 private void toggleUpArrowButton(Boolean toggle) {
3129 upButton.setVisible(toggle);
3130 Global.saveToolbarButtonsVisible("upArrow", toggle);
3132 private void toggleDownArrowButton(Boolean toggle) {
3133 downButton.setVisible(toggle);
3134 Global.saveToolbarButtonsVisible("downArrow", toggle);
3136 private void toggleSynchronizeButton(Boolean toggle) {
3137 synchronizeButton.setVisible(toggle);
3138 Global.saveToolbarButtonsVisible("synchronize", toggle);
3140 private void togglePrintButton(Boolean toggle) {
3141 printButton.setVisible(toggle);
3142 Global.saveToolbarButtonsVisible("print", toggle);
3144 private void toggleTagButton(Boolean toggle) {
3145 tagButton.setVisible(toggle);
3146 Global.saveToolbarButtonsVisible("tag", toggle);
3148 private void toggleAttributeButton(Boolean toggle) {
3149 attributeButton.setVisible(toggle);
3150 Global.saveToolbarButtonsVisible("attribute", toggle);
3152 private void toggleEmailButton(Boolean toggle) {
3153 emailButton.setVisible(toggle);
3154 Global.saveToolbarButtonsVisible("email", toggle);
3156 private void toggleDeleteButton(Boolean toggle) {
3157 deleteButton.setVisible(toggle);
3158 Global.saveToolbarButtonsVisible("delete", toggle);
3160 private void toggleNewButton(Boolean toggle) {
3161 newButton.setVisible(toggle);
3162 Global.saveToolbarButtonsVisible("new", toggle);
3164 private void toggleAllNotesButton(Boolean toggle) {
3165 allNotesButton.setVisible(toggle);
3166 Global.saveToolbarButtonsVisible("allNotes", toggle);
3168 @SuppressWarnings("unused")
3169 private void toggleSearchClearButton(Boolean toggle) {
3170 searchClearButton.setVisible(toggle);
3171 Global.saveToolbarButtonsVisible("searchClear", toggle);
3178 @SuppressWarnings("unused")
3179 private void updateSyncButton() {
3181 if (syncIcons == null) {
3182 syncIcons = new ArrayList<QPixmap>();
3184 synchronizeIconAngle = 0;
3185 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3187 for (int i=0; i<=360; i++) {
3188 QPixmap rotatedPix = new QPixmap(pix.size());
3189 QPainter p = new QPainter(rotatedPix);
3190 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3191 QSize size = pix.size();
3192 p.translate(size.width()/2, size.height()/2);
3195 p.setBackgroundMode(BGMode.OpaqueMode);
3196 p.translate(-size.width()/2, -size.height()/2);
3197 p.drawPixmap(0,0, pix);
3199 syncIcons.add(rotatedPix);
3203 synchronizeIconAngle++;
3204 if (synchronizeIconAngle > 359)
3205 synchronizeIconAngle=0;
3206 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3209 // Synchronize with Evernote
3211 private void evernoteSync() {
3212 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3213 if (!Global.isConnected)
3215 if (Global.isConnected)
3216 synchronizeAnimationTimer.start(5);
3217 // synchronizeAnimationTimer.start(200);
3219 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3221 private void updateQuotaBar() {
3222 long limit = Global.getUploadLimit();
3223 long amount = Global.getUploadAmount();
3224 if (amount>0 && limit>0) {
3225 int percent =(int)(amount*100/limit);
3226 quotaBar.setValue(percent);
3228 quotaBar.setValue(0);
3231 @SuppressWarnings("unused")
3232 private void zoomChanged() {
3233 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3236 //****************************************************************
3237 //****************************************************************
3238 //* System Tray functions
3239 //****************************************************************
3240 //****************************************************************
3241 private void trayToggleVisible() {
3246 if (windowMaximized)
3253 @SuppressWarnings("unused")
3254 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3255 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3256 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3257 trayToggleVisible();
3262 //***************************************************************
3263 //***************************************************************
3264 //** These functions deal with the trash tree
3265 //***************************************************************
3266 //***************************************************************
3267 // Setup the tree containing the trash.
3268 @SuppressWarnings("unused")
3269 private void trashTreeSelection() {
3270 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3272 clearNotebookFilter();
3274 clearAttributeFilter();
3275 clearSavedSearchFilter();
3277 String tempGuid = currentNoteGuid;
3279 // currentNoteGuid = "";
3280 currentNote = new Note();
3281 selectedNoteGUIDs.clear();
3282 listManager.getSelectedNotebooks().clear();
3283 listManager.getSelectedTags().clear();
3284 listManager.setSelectedSavedSearch("");
3285 browserWindow.clear();
3287 // toggle the add buttons
3288 newButton.setEnabled(!newButton.isEnabled());
3289 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3290 menuBar.noteAdd.setVisible(true);
3292 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3293 if (selections.size() == 0) {
3294 currentNoteGuid = trashNoteGuid;
3295 trashNoteGuid = tempGuid;
3296 Global.showDeleted = false;
3297 menuBar.noteRestoreAction.setEnabled(false);
3298 menuBar.noteRestoreAction.setVisible(false);
3301 trashNoteGuid = tempGuid;
3302 currentNoteGuid = trashNoteGuid;
3303 menuBar.noteRestoreAction.setEnabled(true);
3304 menuBar.noteRestoreAction.setVisible(true);
3305 Global.showDeleted = true;
3307 listManager.loadNotesIndex();
3308 noteIndexUpdated(false);
3309 //// browserWindow.setEnabled(newButton.isEnabled());
3310 browserWindow.setReadOnly(!newButton.isEnabled());
3311 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3313 // Empty the trash file
3314 @SuppressWarnings("unused")
3315 private void emptyTrash() {
3316 // browserWindow.clear();
3317 logger.log(logger.EXTREME, "Emptying Trash");
3318 listManager.emptyTrash();
3319 logger.log(logger.EXTREME, "Resetting view after trash empty");
3320 if (trashTree.selectedItems().size() > 0) {
3321 listManager.getSelectedNotebooks().clear();
3322 listManager.getSelectedTags().clear();
3323 listManager.setSelectedSavedSearch("");
3324 newButton.setEnabled(!newButton.isEnabled());
3325 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3326 menuBar.noteAdd.setVisible(true);
3327 browserWindow.clear();
3330 clearNotebookFilter();
3331 clearSavedSearchFilter();
3332 clearAttributeFilter();
3334 Global.showDeleted = false;
3335 menuBar.noteRestoreAction.setEnabled(false);
3336 menuBar.noteRestoreAction.setVisible(false);
3338 listManager.loadNotesIndex();
3339 noteIndexUpdated(false);
3342 // Show/Hide trash window
3343 @SuppressWarnings("unused")
3344 private void toggleTrashWindow() {
3345 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3346 if (trashTree.isVisible())
3350 menuBar.hideTrash.setChecked(trashTree.isVisible());
3352 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3353 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3355 private void clearTrashFilter() {
3356 Global.showDeleted = false;
3357 newButton.setEnabled(true);
3358 menuBar.noteAdd.setEnabled(true);
3359 menuBar.noteAdd.setVisible(true);
3360 trashTree.blockSignals(true);
3361 trashTree.clearSelection();
3362 trashTree.blockSignals(false);
3367 //***************************************************************
3368 //***************************************************************
3369 //** These functions deal with connection settings
3370 //***************************************************************
3371 //***************************************************************
3372 // SyncRunner had a problem and things are disconnected
3373 @SuppressWarnings("unused")
3374 private void remoteErrorDisconnect() {
3375 menuBar.connectAction.setText(tr("Connect"));
3376 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3377 menuBar.synchronizeAction.setEnabled(false);
3378 Global.isConnected = false;
3379 synchronizeAnimationTimer.stop();
3382 // Do a manual connect/disconnect
3383 private void remoteConnect() {
3384 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3386 if (Global.isConnected) {
3387 Global.isConnected = false;
3388 syncRunner.enDisconnect();
3389 setupConnectMenuOptions();
3394 AESEncrypter aes = new AESEncrypter();
3396 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3397 } catch (FileNotFoundException e) {
3398 // File not found, so we'll just get empty strings anyway.
3401 if (Global.getProxyValue("url").equals("")) {
3402 System.setProperty("http.proxyHost","") ;
3403 System.setProperty("http.proxyPort", "") ;
3404 System.setProperty("https.proxyHost","") ;
3405 System.setProperty("https.proxyPort", "") ;
3408 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3409 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3410 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3411 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3413 if (Global.getProxyValue("userid").equals("")) {
3414 Authenticator.setDefault(new Authenticator() {
3416 protected PasswordAuthentication getPasswordAuthentication() {
3418 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3424 syncRunner.userStoreUrl = Global.userStoreUrl;
3425 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3426 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3428 String userid = aes.getUserid();
3429 String password = aes.getPassword();
3430 if (!userid.equals("") && !password.equals("")) {
3431 Global.username = userid;
3432 Global.password = password;
3433 syncRunner.username = Global.username;
3434 syncRunner.password = Global.password;
3435 syncRunner.enConnect();
3438 Global.isConnected = syncRunner.isConnected;
3440 if (!Global.isConnected) {
3441 // Show the login dialog box
3442 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3443 LoginDialog login = new LoginDialog();
3446 if (!login.okPressed()) {
3450 Global.username = login.getUserid();
3451 Global.password = login.getPassword();
3453 syncRunner.username = Global.username;
3454 syncRunner.password = Global.password;
3455 syncRunner.enConnect();
3456 Global.isConnected = syncRunner.isConnected;
3459 if (!Global.isConnected)
3462 setupConnectMenuOptions();
3463 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3465 private void setupConnectMenuOptions() {
3466 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3467 if (!Global.isConnected) {
3468 menuBar.connectAction.setText(tr("Connect"));
3469 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3470 menuBar.synchronizeAction.setEnabled(false);
3472 menuBar.connectAction.setText(tr("Disconnect"));
3473 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3474 menuBar.synchronizeAction.setEnabled(true);
3476 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3481 //***************************************************************
3482 //***************************************************************
3483 //** These functions deal with the GUI Attribute tree
3484 //***************************************************************
3485 //***************************************************************
3486 @SuppressWarnings("unused")
3487 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3489 // clearTagFilter();
3490 // clearNotebookFilter();
3492 // clearSavedSearchFilter();
3494 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3495 if (item.childCount() > 0) {
3496 item.setSelected(false);
3498 Global.createdBeforeFilter.reset();
3499 Global.createdSinceFilter.reset();
3500 Global.changedBeforeFilter.reset();
3501 Global.changedSinceFilter.reset();
3502 Global.containsFilter.reset();
3503 attributeTreeSelected = item;
3504 DateAttributeFilterTable f = null;
3505 f = findDateAttributeFilterTable(item.parent());
3507 f.select(item.parent().indexOfChild(item));
3509 Global.containsFilter.select(item.parent().indexOfChild(item));
3512 listManager.loadNotesIndex();
3513 noteIndexUpdated(false);
3516 attributeTreeSelected = null;
3517 item.setSelected(false);
3518 Global.createdBeforeFilter.reset();
3519 Global.createdSinceFilter.reset();
3520 Global.changedBeforeFilter.reset();
3521 Global.changedSinceFilter.reset();
3522 Global.containsFilter.reset();
3523 listManager.loadNotesIndex();
3524 noteIndexUpdated(false);
3526 // This determines what attribute filter we need, depending upon the selection
3527 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3528 if (w.parent() != null && w.childCount() > 0) {
3529 QTreeWidgetItem parent = w.parent();
3530 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3531 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3532 return Global.createdSinceFilter;
3533 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3534 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3535 return Global.createdBeforeFilter;
3536 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3537 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3538 return Global.changedSinceFilter;
3539 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3540 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3541 return Global.changedBeforeFilter;
3546 // Show/Hide attribute search window
3547 @SuppressWarnings("unused")
3548 private void toggleAttributesWindow() {
3549 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3550 if (attributeTree.isVisible())
3551 attributeTree.hide();
3553 attributeTree.show();
3554 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3556 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3557 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3559 private void clearAttributeFilter() {
3560 Global.createdBeforeFilter.reset();
3561 Global.createdSinceFilter.reset();
3562 Global.changedBeforeFilter.reset();
3563 Global.changedSinceFilter.reset();
3564 Global.containsFilter.reset();
3565 attributeTreeSelected = null;
3566 attributeTree.blockSignals(true);
3567 attributeTree.clearSelection();
3568 attributeTree.blockSignals(false);
3572 //***************************************************************
3573 //***************************************************************
3574 //** These functions deal with the GUI Note index table
3575 //***************************************************************
3576 //***************************************************************
3577 // Initialize the note list table
3578 private void initializeNoteTable() {
3579 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3580 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3581 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3582 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3584 // Show/Hide trash window
3585 @SuppressWarnings("unused")
3586 private void toggleNoteListWindow() {
3587 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3588 if (noteTableView.isVisible())
3589 noteTableView.hide();
3591 noteTableView.show();
3592 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3594 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3595 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3597 // Handle the event that a user selects a note from the table
3598 @SuppressWarnings("unused")
3599 private void noteTableSelection() {
3600 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3604 // If we have more than one selection, then set the merge note action to true.
3605 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3606 if (selections.size() > 1)
3607 menuBar.noteMergeAction.setEnabled(true);
3609 menuBar.noteMergeAction.setEnabled(false);
3611 // If the ctrl key is pressed, then they are selecting multiple
3612 // entries and we don't want to change the currently viewed note.
3613 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3614 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3617 if (historyGuids.size() == 0) {
3618 historyGuids.add(currentNoteGuid);
3619 historyPosition = 1;
3621 noteTableView.showColumn(Global.noteTableGuidPosition);
3623 if (!Global.isColumnVisible("guid"))
3624 noteTableView.hideColumn(Global.noteTableGuidPosition);
3626 if (selections.size() > 0) {
3628 menuBar.noteDuplicateAction.setEnabled(true);
3629 menuBar.noteOnlineHistoryAction.setEnabled(true);
3630 menuBar.noteMergeAction.setEnabled(true);
3631 selectedNoteGUIDs.clear();
3632 if (selections.size() != 1 || Global.showDeleted) {
3633 menuBar.noteDuplicateAction.setEnabled(false);
3635 if (selections.size() != 1 || !Global.isConnected) {
3636 menuBar.noteOnlineHistoryAction.setEnabled(false);
3638 if (selections.size() == 1) {
3639 menuBar.noteMergeAction.setEnabled(false);
3641 for (int i=0; i<selections.size(); i++) {
3642 int row = selections.get(i).row();
3644 upButton.setEnabled(false);
3646 upButton.setEnabled(true);
3647 if (row < listManager.getNoteTableModel().rowCount()-1)
3648 downButton.setEnabled(true);
3650 downButton.setEnabled(false);
3651 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3652 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3653 currentNoteGuid = (String)ix.values().toArray()[0];
3654 selectedNoteGUIDs.add(currentNoteGuid);
3658 nextButton.setEnabled(true);
3659 prevButton.setEnabled(true);
3661 int endPosition = historyGuids.size()-1;
3662 for (int j=historyPosition; j<=endPosition; j++) {
3663 historyGuids.remove(historyGuids.size()-1);
3665 historyGuids.add(currentNoteGuid);
3666 historyPosition = historyGuids.size();
3668 if (historyPosition <= 1)
3669 prevButton.setEnabled(false);
3670 if (historyPosition == historyGuids.size())
3671 nextButton.setEnabled(false);
3673 fromHistory = false;
3674 scrollToGuid(currentNoteGuid);
3675 refreshEvernoteNote(true);
3676 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3678 // Trigger a refresh when the note db has been updated
3679 private void noteIndexUpdated(boolean reload) {
3680 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3682 refreshEvernoteNoteList();
3683 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3684 noteTableView.load(reload);
3685 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3687 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3688 pos = noteTableView.proxyModel.rowCount();
3691 if (noteTableView.proxyModel.rowCount() == 0)
3694 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3696 currentNoteGuid = (String)i.data();
3700 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3702 scrollToGuid(currentNoteGuid);
3703 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3705 // Called when the list of notes is updated
3706 private void refreshEvernoteNoteList() {
3707 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3708 browserWindow.setDisabled(false);
3709 if (selectedNoteGUIDs == null)
3710 selectedNoteGUIDs = new ArrayList<String>();
3711 selectedNoteGUIDs.clear(); // clear out old entries
3713 String saveCurrentNoteGuid = new String();
3714 String tempNoteGuid = new String();
3716 historyGuids.clear();
3717 historyPosition = 0;
3718 prevButton.setEnabled(false);
3719 nextButton.setEnabled(false);
3721 if (currentNoteGuid == null)
3722 currentNoteGuid = new String();
3724 //determine current note guid
3725 for (Note note : listManager.getNoteIndex()) {
3726 tempNoteGuid = note.getGuid();
3727 if (currentNoteGuid.equals(tempNoteGuid)) {
3728 saveCurrentNoteGuid = tempNoteGuid;
3732 if (listManager.getNoteIndex().size() == 0) {
3733 currentNoteGuid = "";
3735 browserWindow.clear();
3736 browserWindow.setDisabled(true);
3739 if (Global.showDeleted && listManager.getNotebookIndex().size() > 0 && saveCurrentNoteGuid.equals("")) {
3740 currentNoteGuid = listManager.getNoteIndex().get(0).getGuid();
3741 saveCurrentNoteGuid = currentNoteGuid;
3742 refreshEvernoteNote(true);
3745 if (!saveCurrentNoteGuid.equals("")) {
3746 refreshEvernoteNote(false);
3748 currentNoteGuid = "";
3750 reloadTagTree(false);
3752 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3754 // Called when the previous arrow button is clicked
3755 @SuppressWarnings("unused")
3756 private void previousViewedAction() {
3757 if (!prevButton.isEnabled())
3759 if (historyPosition == 0)
3762 if (historyPosition <= 0)
3764 String historyGuid = historyGuids.get(historyPosition-1);
3766 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3767 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3768 if (modelIndex != null) {
3769 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3770 String tableGuid = (String)ix.values().toArray()[0];
3771 if (tableGuid.equals(historyGuid)) {
3772 noteTableView.selectRow(i);
3778 @SuppressWarnings("unused")
3779 private void nextViewedAction() {
3780 if (!nextButton.isEnabled())
3782 String historyGuid = historyGuids.get(historyPosition);
3785 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3786 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3787 if (modelIndex != null) {
3788 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3789 String tableGuid = (String)ix.values().toArray()[0];
3790 if (tableGuid.equals(historyGuid)) {
3791 noteTableView.selectRow(i);
3797 // Called when the up arrow is clicked
3798 @SuppressWarnings("unused")
3799 private void upAction() {
3800 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3801 int row = selections.get(0).row();
3803 noteTableView.selectRow(row-1);
3806 // Called when the down arrow is clicked
3807 @SuppressWarnings("unused")
3808 private void downAction() {
3809 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3810 int row = selections.get(0).row();
3811 int max = listManager.getNoteTableModel().rowCount();
3813 noteTableView.selectRow(row+1);
3816 // Update a tag string for a specific note in the list
3817 @SuppressWarnings("unused")
3818 private void updateListTags(String guid, List<String> tags) {
3819 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3820 StringBuffer tagBuffer = new StringBuffer();
3821 for (int i=0; i<tags.size(); i++) {
3822 tagBuffer.append(tags.get(i));
3823 if (i<tags.size()-1)
3824 tagBuffer.append(", ");
3827 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3828 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3829 if (modelIndex != null) {
3830 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3831 String tableGuid = (String)ix.values().toArray()[0];
3832 if (tableGuid.equals(guid)) {
3833 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3834 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3835 noteTableView.proxyModel.invalidate();
3840 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3842 // Update a title for a specific note in the list
3843 @SuppressWarnings("unused")
3844 private void updateListAuthor(String guid, String author) {
3845 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3847 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3848 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
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.noteTableAuthorPosition,author);
3855 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3856 noteTableView.proxyModel.invalidate();
3862 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3864 private void updateListNoteNotebook(String guid, String notebook) {
3865 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3866 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3867 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3869 // Update a title for a specific note in the list
3870 @SuppressWarnings("unused")
3871 private void updateListSourceUrl(String guid, String url) {
3872 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3874 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3875 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3876 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3877 if (modelIndex != null) {
3878 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3879 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3880 String tableGuid = (String)ix.values().toArray()[0];
3881 if (tableGuid.equals(guid)) {
3882 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3883 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3884 noteTableView.proxyModel.invalidate();
3889 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3891 @SuppressWarnings("unused")
3892 private void updateListGuid(String oldGuid, String newGuid) {
3893 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3895 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3896 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3897 if (modelIndex != null) {
3898 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3899 String tableGuid = (String)ix.values().toArray()[0];
3900 if (tableGuid.equals(oldGuid)) {
3901 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3902 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3907 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3909 private void updateListTagName(String guid) {
3910 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3912 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3913 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3914 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
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 noteGuid = (String)ix.values().toArray()[0];
3921 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3922 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3923 i=listManager.getNoteTableModel().rowCount();
3929 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3931 private void removeListTagName(String guid) {
3932 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3934 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3935 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3936 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3937 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3938 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3941 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3942 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3943 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3944 if (modelIndex != null) {
3945 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3946 String noteGuid = (String)ix.values().toArray()[0];
3947 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3948 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3949 i=listManager.getNoteTableModel().rowCount();
3955 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3957 private void updateListNotebookName(String oldName, String newName) {
3958 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3960 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3961 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3962 if (modelIndex != null) {
3963 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3964 String tableName = (String)ix.values().toArray()[0];
3965 if (tableName.equalsIgnoreCase(oldName)) {
3966 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3970 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3972 @SuppressWarnings("unused")
3973 private void updateListDateCreated(String guid, QDateTime date) {
3974 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3976 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3977 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3978 if (modelIndex != null) {
3979 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3980 String tableGuid = (String)ix.values().toArray()[0];
3981 if (tableGuid.equals(guid)) {
3982 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3983 noteTableView.proxyModel.invalidate();
3988 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3990 @SuppressWarnings("unused")
3991 private void updateListDateSubject(String guid, QDateTime date) {
3992 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3994 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3995 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3996 if (modelIndex != null) {
3997 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3998 String tableGuid = (String)ix.values().toArray()[0];
3999 if (tableGuid.equals(guid)) {
4000 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4001 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4002 noteTableView.proxyModel.invalidate();
4007 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
4009 private void updateListDateChanged(String guid, QDateTime date) {
4010 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
4012 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4013 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4014 if (modelIndex != null) {
4015 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4016 String tableGuid = (String)ix.values().toArray()[0];
4017 if (tableGuid.equals(guid)) {
4018 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4019 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4024 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4026 private void updateListDateChanged() {
4027 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
4028 QDateTime date = new QDateTime(QDateTime.currentDateTime());
4029 updateListDateChanged(currentNoteGuid, date);
4030 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4033 private void scrollToCurrentGuid() {
4034 //scrollToGuid(currentNoteGuid);
4035 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
4036 if (selections.size() == 0)
4038 QModelIndex index = selections.get(0);
4039 int row = selections.get(0).row();
4040 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
4043 // Scroll to the current GUID in tthe list.
4044 // Scroll to a particular index item
4045 private void scrollToGuid(String guid) {
4046 if (currentNote == null || guid == null)
4048 if (currentNote.isActive() && Global.showDeleted) {
4049 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4050 if (!listManager.getNoteIndex().get(i).isActive()) {
4051 currentNote = listManager.getNoteIndex().get(i);
4052 currentNoteGuid = currentNote.getGuid();
4053 i = listManager.getNoteIndex().size();
4057 if (!currentNote.isActive() && !Global.showDeleted) {
4058 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4059 if (listManager.getNoteIndex().get(i).isActive()) {
4060 currentNote = listManager.getNoteIndex().get(i);
4061 currentNoteGuid = currentNote.getGuid();
4062 i = listManager.getNoteIndex().size();
4067 for (int i=0; i<noteTableView.model().rowCount(); i++) {
4068 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4069 if (currentNoteGuid.equals(index.data())) {
4070 // noteTableView.selectionModel().blockSignals(true);
4071 noteTableView.selectRow(i);
4072 // noteTableView.selectionModel().blockSignals(false);
4073 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
4074 i=listManager.getNoteTableModel().rowCount();
4077 noteTableView.repaint();
4079 // Show/Hide columns
4080 private void showColumns() {
4081 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4082 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4083 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4084 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4085 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4086 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4087 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4088 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4089 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4090 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4091 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4092 noteTableView.setColumnHidden(Global.noteTablePinnedPosition, !Global.isColumnVisible("pinned"));
4094 // Title color has changed
4095 @SuppressWarnings("unused")
4096 private void titleColorChanged(Integer color) {
4097 logger.log(logger.HIGH, "Entering NeverNote.titleColorChanged");
4100 QColor backgroundColor = new QColor();
4101 QColor foregroundColor = new QColor(QColor.black);
4102 backgroundColor.setRgb(color);
4104 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4105 foregroundColor.setRgb(QColor.white.rgb());
4107 if (selectedNoteGUIDs.size() == 0)
4108 selectedNoteGUIDs.add(currentNoteGuid);
4110 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4111 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4112 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4113 if (modelIndex != null) {
4114 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4115 String tableGuid = (String)ix.values().toArray()[0];
4116 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4117 for (int k=0; k<Global.noteTableColumnCount; k++) {
4118 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4119 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4120 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4122 i=listManager.getNoteTableModel().rowCount();
4127 logger.log(logger.HIGH, "Leaving NeverNote.titleColorChanged");
4129 // A note has been pinned or unpinned
4130 @SuppressWarnings("unused")
4131 private void notePinned() {
4132 logger.log(logger.EXTREME, "Entering NeverNote.notePinned()");
4135 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4136 NoteMetadata meta = listManager.getNoteMetadata().get(selectedNoteGUIDs.get(j));
4137 boolean pinned = !meta.isPinned();
4138 meta.setPinned(pinned); // Toggle the pinned/unpinned
4140 // Update the list & table
4141 listManager.updateNoteMetadata(meta);
4142 noteTableView.proxyModel.addGuid(selectedNoteGUIDs.get(j), meta);
4145 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4147 // Wide list was chosen
4148 public void narrowListView() {
4149 saveNoteColumnPositions();
4150 saveNoteIndexWidth();
4152 int sortCol = noteTableView.proxyModel.sortColumn();
4153 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4154 Global.setSortColumn(sortCol);
4155 Global.setSortOrder(sortOrder);
4157 Global.setListView(Global.View_List_Narrow);
4159 menuBar.wideListView.blockSignals(true);
4160 menuBar.narrowListView.blockSignals(true);
4162 menuBar.wideListView.setChecked(false);
4163 menuBar.narrowListView.setChecked(true);
4165 menuBar.wideListView.blockSignals(false);
4166 menuBar.narrowListView.blockSignals(false);
4168 mainLeftRightSplitter.addWidget(noteTableView);
4169 mainLeftRightSplitter.addWidget(browserWindow);
4170 restoreWindowState(false);
4171 noteTableView.repositionColumns();
4172 noteTableView.resizeColumnWidths();
4173 noteTableView.resizeRowHeights();
4175 sortCol = Global.getSortColumn();
4176 sortOrder = Global.getSortOrder();
4177 noteTableView.proxyModel.blocked = true;
4178 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4179 noteTableView.proxyModel.blocked = false;
4183 noteTableView.load(false);
4184 refreshEvernoteNote(true);
4185 scrollToCurrentGuid();
4187 public void wideListView() {
4188 int sortCol = noteTableView.proxyModel.sortColumn();
4189 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4190 Global.setSortColumn(sortCol);
4191 Global.setSortOrder(sortOrder);
4194 saveNoteColumnPositions();
4195 saveNoteIndexWidth();
4196 Global.setListView(Global.View_List_Wide);
4198 menuBar.wideListView.blockSignals(true);
4199 menuBar.narrowListView.blockSignals(true);
4201 menuBar.wideListView.setChecked(true);
4202 menuBar.narrowListView.setChecked(false);
4204 menuBar.wideListView.blockSignals(false);
4205 menuBar.narrowListView.blockSignals(false);
4206 browserIndexSplitter.setVisible(true);
4207 browserIndexSplitter.addWidget(noteTableView);
4208 browserIndexSplitter.addWidget(browserWindow);
4209 restoreWindowState(false);
4210 noteTableView.repositionColumns();
4211 noteTableView.resizeColumnWidths();
4212 noteTableView.resizeRowHeights();
4214 sortCol = Global.getSortColumn();
4215 sortOrder = Global.getSortOrder();
4216 noteTableView.proxyModel.blocked = true;
4217 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4218 noteTableView.proxyModel.blocked = false;
4221 noteTableView.load(false);
4222 scrollToCurrentGuid();
4224 // Sort order for the notebook has changed
4225 public void tableSortOrderChanged(Integer column, Integer order) {
4227 // Find what notebook (if any) is selected. We ignore stacks & the "All Notebooks".
4228 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4229 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4230 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4232 notebook = currentSelectedNotebook.text(2);
4233 conn.getNotebookTable().setSortOrder(notebook, column, order);
4237 //***************************************************************
4238 @SuppressWarnings("unused")
4239 private void evernoteLinkClick(String syncGuid, String locGuid) {
4241 if (conn.getNoteTable().guidExists(syncGuid)) {
4244 // If we didn't find it via the synchronized guid, look under the local guid
4245 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4246 // later synchronized (that causes the guid to change so we need to find the new one).
4247 if (conn.getNoteTable().guidExists(locGuid))
4250 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4253 openExternalEditor(guid);
4257 //If we've gotten this far, we can't find the note
4258 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4259 " seem to find that note."));
4261 //***************************************************************
4262 //***************************************************************
4263 //** External editor window functions
4264 //***************************************************************
4265 //***************************************************************
4266 private void listDoubleClick() {
4268 openExternalEditor(currentNoteGuid);
4270 private void openExternalEditor(String guid) {
4272 if (externalWindows.containsKey(guid)) {
4273 externalWindows.get(guid).raise();
4276 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4277 // We have a new external editor to create
4278 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4279 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4280 newBrowser.setWindowIcon(appIcon);
4281 externalWindows.put(guid, newBrowser);
4282 showEditorButtons(newBrowser.getBrowserWindow());
4283 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4284 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4285 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4286 //newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4287 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4288 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4289 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4290 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4292 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4293 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4294 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4298 @SuppressWarnings({ "rawtypes", "unused" })
4299 private void externalWindowTagsEdited(String guid, List values) {
4300 StringBuffer line = new StringBuffer(100);
4301 for (int i=0; i<values.size(); i++) {
4303 line.append(Global.tagDelimeter+" ");
4304 line.append(values.get(i));
4306 if (guid.equals(currentNoteGuid)) {
4307 browserWindow.setTag(line.toString());
4310 @SuppressWarnings("unused")
4311 private void externalWindowClosing(String guid) {
4312 externalWindows.remove(guid);
4317 //***************************************************************
4318 //***************************************************************
4319 //** These functions deal with Note specific things
4320 //***************************************************************
4321 //***************************************************************
4322 private void setNoteDirty() {
4323 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4325 // Find if the note is being edited externally. If it is, update it.
4326 if (externalWindows.containsKey(currentNoteGuid)) {
4327 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4328 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4329 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4330 window.getBrowserWindow().setContent(unicode);
4333 // If the note is dirty, then it is unsynchronized by default.
4337 // Set the note as dirty and check if its status is synchronized in the display table
4339 if (listManager.getNoteMetadata().containsKey(currentNoteGuid) &&
4340 listManager.getNoteMetadata().get(currentNoteGuid).isDirty()) {
4344 // If this wasn't already marked as unsynchronized, then we need to update the table
4345 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4346 // listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4347 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4348 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4349 if (modelIndex != null) {
4350 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4351 String tableGuid = (String)ix.values().toArray()[0];
4352 if (tableGuid.equals(currentNoteGuid)) {
4353 listManager.getNoteTableModel().proxyModel.setData(i, Global.noteTableSynchronizedPosition, "false");
4359 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4361 @SuppressWarnings("unused")
4362 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4363 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4364 QByteArray unicode = codec.fromUnicode(content);
4365 noteCache.remove(guid);
4366 noteCache.put(guid, unicode.toString());
4367 if (guid.equals(currentNoteGuid)) {
4369 browserWindow.setContent(unicode);
4372 thumbnailRunner.addWork("GENERATE "+ guid);
4373 saveNote(guid, browser);
4377 private void saveNote() {
4379 saveNote(currentNoteGuid, browserWindow);
4380 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4384 private void saveNote(String guid, BrowserWindow window) {
4385 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4388 logger.log(logger.EXTREME, "Saving to cache");
4389 QTextCodec codec = QTextCodec.codecForLocale();
4390 // QTextDecoder decoder = codec.makeDecoder();
4391 codec = QTextCodec.codecForName("UTF-8");
4392 QByteArray unicode = codec.fromUnicode(window.getContent());
4393 noteCache.put(guid, unicode.toString());
4395 logger.log(logger.EXTREME, "updating list manager");
4396 listManager.updateNoteContent(guid, window.getContent());
4397 logger.log(logger.EXTREME, "Updating title");
4398 listManager.updateNoteTitle(guid, window.getTitle());
4399 updateListDateChanged();
4401 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4402 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4403 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4404 currentNote = listManager.getNoteIndex().get(i);
4405 i = listManager.getNoteIndex().size();
4410 // Get a note from Evernote (and put it in the browser)
4411 private void refreshEvernoteNote(boolean reload) {
4412 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4414 if (Global.disableViewing) {
4415 browserWindow.setEnabled(false);
4420 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4422 Global.cryptCounter =0;
4424 browserWindow.setReadOnly(true);
4431 browserWindow.loadingData(true);
4433 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4434 if (currentNote == null)
4436 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4439 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4440 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4441 formatter.setNote(note, Global.pdfPreview());
4442 formatter.setHighlight(listManager.getEnSearch());
4444 if (!noteCache.containsKey(guid)) {
4445 js = new QByteArray();
4446 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4447 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4448 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>");
4449 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4450 js.append("<style> img { height:auto; width:auto; max-height:auto; max-width:100%; }</style>");
4451 if (Global.displayRightToLeft())
4452 js.append("<style> body { direction:rtl; }</style>");
4453 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4454 js.append("</head>");
4455 formatter.setNote(note, Global.pdfPreview());
4456 js.append(formatter.rebuildNoteHTML());
4457 js.append("</HTML>");
4458 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4459 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4460 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4461 // if (Global.enableHTMLEntitiesFix) {
4462 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4464 browser.setContent(js);
4465 noteCache.put(guid, js.toString());
4467 if (formatter.resourceError)
4468 resourceErrorMessage();
4469 if (formatter.formatError) {
4471 QMessageBox.information(this, tr("Error"),
4472 tr("NixNote had issues formatting this note." +
4473 " To protect your data this note is being marked as read-only."));
4476 readOnly = formatter.readOnly;
4477 inkNote = formatter.inkNote;
4479 readOnlyCache.put(guid, true);
4481 inkNoteCache.put(guid, true);
4483 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4484 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4485 js = new QByteArray(cachedContent);
4486 browser.setContent(js);
4487 if (readOnlyCache.containsKey(guid))
4489 if (inkNoteCache.containsKey(guid))
4492 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4493 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4495 if (readOnly || inkNote ||
4496 (note.getAttributes() != null && note.getAttributes().getContentClass() != null && note.getAttributes().getContentClass() != ""))
4497 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4499 browser.getBrowser().page().setContentEditable(true);
4500 browser.setReadOnly(readOnly);
4501 deleteButton.setEnabled(!readOnly);
4502 tagButton.setEnabled(!readOnly);
4503 menuBar.noteDelete.setEnabled(!readOnly);
4504 menuBar.noteTags.setEnabled(!readOnly);
4505 browser.setNote(note);
4507 if (note != null && note.getNotebookGuid() != null &&
4508 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4509 deleteButton.setEnabled(false);
4510 menuBar.notebookDeleteAction.setEnabled(false);
4512 deleteButton.setEnabled(true);
4513 menuBar.notebookDeleteAction.setEnabled(true);
4516 // Build a list of non-closed notebooks
4517 List<Notebook> nbooks = new ArrayList<Notebook>();
4518 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4519 boolean found=false;
4520 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4521 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4525 nbooks.add(listManager.getNotebookIndex().get(i));
4528 browser.setTitle(note.getTitle());
4529 browser.setTag(getTagNamesForNote(note));
4530 browser.setAuthor(note.getAttributes().getAuthor());
4532 browser.setAltered(note.getUpdated());
4533 browser.setCreation(note.getCreated());
4534 if (note.getAttributes().getSubjectDate() > 0)
4535 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4537 browser.setSubjectDate(note.getCreated());
4538 browser.setUrl(note.getAttributes().getSourceURL());
4540 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4541 List<Tag> tagList = tagFilter.getValidTags(note);
4542 browser.setAllTags(tagList);
4544 browser.setCurrentTags(note.getTagNames());
4548 browser.loadingData(false);
4549 if (thumbnailViewer.isActiveWindow())
4552 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4553 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4556 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4558 // Save a generated thumbnail
4559 private void toggleNoteInformation() {
4560 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4561 browserWindow.toggleInformation();
4562 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4563 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4564 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4566 // Listener triggered when a print button is pressed
4567 @SuppressWarnings("unused")
4568 private void printNote() {
4569 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4571 QPrintDialog dialog = new QPrintDialog();
4572 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4573 QPrinter printer = dialog.printer();
4574 browserWindow.getBrowser().print(printer);
4576 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4579 // Listener triggered when the email button is pressed
4580 @SuppressWarnings("unused")
4581 private void emailNote() {
4582 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4584 if (Desktop.isDesktopSupported()) {
4585 Desktop desktop = Desktop.getDesktop();
4587 String text2 = browserWindow.getContentsToEmail();
4588 QUrl url = new QUrl("mailto:");
4589 url.addQueryItem("subject", currentNote.getTitle());
4590 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4591 url.addQueryItem("body", text2);
4592 QDesktopServices.openUrl(url);
4596 if (desktop.isSupported(Desktop.Action.MAIL)) {
4597 URI uriMailTo = null;
4599 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4600 String text = browserWindow.getContentsToEmail();
4601 //text = "<b>" +text +"</b>";
4602 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4603 +"&BODY=" +text, null);
4604 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4605 +"&ATTACHMENT=d:/test.pdf", null);
4606 desktop.mail(uriMailTo);
4607 } catch (URISyntaxException e) {
4608 e.printStackTrace();
4609 } catch (IOException e) {
4610 e.printStackTrace();
4617 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4619 // Reindex all notes
4620 @SuppressWarnings("unused")
4621 private void fullReindex() {
4622 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4623 indexRunner.addWork("REINDEXALL");
4624 setMessage(tr("Database will be reindexed."));
4625 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4627 // Listener when a user wants to reindex a specific note
4628 @SuppressWarnings("unused")
4629 private void reindexNote() {
4630 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4631 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4632 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4634 if (selectedNotebookGUIDs.size() > 1)
4635 setMessage(tr("Notes will be reindexed."));
4637 setMessage(tr("Note will be reindexed."));
4638 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4641 @SuppressWarnings("unused")
4642 private void deleteNote() {
4643 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4644 if (currentNote == null)
4646 if (currentNoteGuid.equals(""))
4648 String title = null;
4649 if (selectedNoteGUIDs.size() == 1)
4650 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4652 // If we are deleting non-trash notes
4653 if (currentNote.isActive()) {
4654 if (Global.verifyDelete()) {
4656 if (selectedNoteGUIDs.size() > 1) {
4657 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4660 msg = new String(tr("Delete note \"") +title +"\"?");
4662 msg = new String(tr("Delete note selected note?"));
4664 if (QMessageBox.question(this, tr("Confirmation"), msg,
4665 QMessageBox.StandardButton.Yes,
4666 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4670 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4671 selectedNoteGUIDs.add(currentNoteGuid);
4672 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4673 listManager.deleteNote(selectedNoteGUIDs.get(i));
4676 // If we are deleting from the trash.
4677 if (Global.verifyDelete()) {
4679 if (selectedNoteGUIDs.size() > 1) {
4680 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4683 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4685 msg = new String(tr("Permanently delete note selected note?"));
4687 if (QMessageBox.question(this, "Confirmation", msg,
4688 QMessageBox.StandardButton.Yes,
4689 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4693 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4694 selectedNoteGUIDs.add(currentNoteGuid);
4695 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4696 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4697 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4698 if (modelIndex != null) {
4699 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4700 String tableGuid = (String)ix.values().toArray()[0];
4701 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4702 listManager.getNoteTableModel().removeRow(j);
4707 listManager.expungeNote(selectedNoteGUIDs.get(i));
4710 currentNoteGuid = "";
4711 listManager.loadNotesIndex();
4712 noteIndexUpdated(false);
4713 refreshEvernoteNote(true);
4714 scrollToGuid(currentNoteGuid);
4715 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4718 @SuppressWarnings("unused")
4719 private void addNote() {
4720 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4721 // browserWindow.setEnabled(true);
4722 browserWindow.setReadOnly(false);
4724 Calendar currentTime = new GregorianCalendar();
4725 StringBuffer noteString = new StringBuffer(100);
4726 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4727 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4730 if (Global.overrideDefaultFont()) {
4731 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4732 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4733 noteString.append("<br clear=\"none\" />\n");
4734 noteString.append("</span>\n</font>\n");
4736 noteString.append("<br clear=\"none\" />\n");
4737 noteString.append("</en-note>");
4739 Long l = new Long(currentTime.getTimeInMillis());
4740 String randint = new String(Long.toString(l));
4742 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4744 // for the first non-archived notebook. Finally, if nothing else we
4745 // pick the first notebook in the list.
4746 String notebook = null;
4747 listManager.getNotebookIndex().get(0).getGuid();
4748 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4749 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4750 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4751 notebook = currentSelectedNotebook.text(2);
4753 boolean found = false;
4754 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4755 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4756 boolean match = false;
4757 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4758 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4760 j = listManager.getArchiveNotebookIndex().size();
4764 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4765 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4767 // Now we have a list of good notebooks, so we can look for the default
4769 for (int i=0; i<goodNotebooks.size(); i++) {
4770 if (goodNotebooks.get(i).isDefaultNotebook()) {
4771 notebook = goodNotebooks.get(i).getGuid();
4773 i = goodNotebooks.size();
4777 if (goodNotebooks.size() > 0 && !found)
4778 notebook = goodNotebooks.get(0).getGuid();
4781 notebook = listManager.getNotebookIndex().get(0).getGuid();
4784 Note newNote = new Note();
4785 newNote.setUpdateSequenceNum(0);
4786 newNote.setGuid(randint);
4787 newNote.setNotebookGuid(notebook);
4788 newNote.setTitle("Untitled Note");
4789 newNote.setContent(noteString.toString());
4790 newNote.setDeleted(0);
4791 newNote.setCreated(System.currentTimeMillis());
4792 newNote.setUpdated(System.currentTimeMillis());
4793 newNote.setActive(true);
4794 NoteAttributes na = new NoteAttributes();
4795 na.setLatitude(0.0);
4796 na.setLongitude(0.0);
4797 na.setAltitude(0.0);
4798 newNote.setAttributes(new NoteAttributes());
4799 newNote.setTagGuids(new ArrayList<String>());
4800 newNote.setTagNames(new ArrayList<String>());
4802 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4803 if (Global.newNoteWithSelectedTags()) {
4804 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4805 QTreeWidgetItem currentSelection;
4806 for (int i=0; i<selections.size(); i++) {
4807 currentSelection = selections.get(i);
4808 newNote.getTagGuids().add(currentSelection.text(2));
4809 newNote.getTagNames().add(currentSelection.text(0));
4813 conn.getNoteTable().addNote(newNote, true);
4814 NoteMetadata metadata = new NoteMetadata();
4815 metadata.setGuid(newNote.getGuid());
4816 metadata.setDirty(true);
4817 listManager.addNote(newNote, metadata);
4818 // noteTableView.insertRow(newNote, true, -1);
4820 currentNote = newNote;
4821 currentNoteGuid = currentNote.getGuid();
4822 noteTableView.clearSelection();
4823 refreshEvernoteNote(true);
4824 listManager.countNotebookResults(listManager.getNoteIndex());
4825 browserWindow.titleLabel.setFocus();
4826 browserWindow.titleLabel.selectAll();
4827 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4829 // If the window is hidden, then we want to popup this in an external window &
4833 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4835 // Restore a note from the trash;
4836 @SuppressWarnings("unused")
4837 private void restoreNote() {
4839 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4840 selectedNoteGUIDs.add(currentNoteGuid);
4841 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4842 listManager.restoreNote(selectedNoteGUIDs.get(i));
4844 currentNoteGuid = "";
4845 listManager.loadNotesIndex();
4846 noteIndexUpdated(false);
4849 // Search a note for specific txt
4850 @SuppressWarnings("unused")
4851 private void findText() {
4853 find.setFocusOnTextField();
4855 @SuppressWarnings("unused")
4856 private void doFindText() {
4857 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4860 @SuppressWarnings("unused")
4861 private void updateNoteTitle(String guid, String title) {
4862 listManager.setNoteSynchronized(guid, false);
4864 // We do this manually because if we've edited the note in an
4865 // external window we run into the possibility of signal recursion
4867 if (guid.equals(currentNoteGuid)) {
4868 browserWindow.titleLabel.blockSignals(true);
4869 browserWindow.titleLabel.setText(title);
4870 browserWindow.titleLabel.blockSignals(false);
4873 // Signal received that note content has changed. Normally we just need the guid to remove
4874 // it from the cache.
4875 @SuppressWarnings("unused")
4876 private void invalidateNoteCache(String guid, String content) {
4877 noteCache.remove(guid);
4878 refreshEvernoteNote(true);
4880 // Signal received that a note guid has changed
4881 @SuppressWarnings("unused")
4882 private void noteGuidChanged(String oldGuid, String newGuid) {
4883 if (noteCache.containsKey(oldGuid)) {
4884 if (!oldGuid.equals(currentNoteGuid)) {
4885 String cache = noteCache.get(oldGuid);
4886 noteCache.put(newGuid, cache);
4887 noteCache.remove(oldGuid);
4889 noteCache.remove(oldGuid);
4890 noteCache.put(newGuid, browserWindow.getContent());
4894 listManager.updateNoteGuid(oldGuid, newGuid, false);
4895 if (currentNoteGuid.equals(oldGuid)) {
4896 if (currentNote != null)
4897 currentNote.setGuid(newGuid);
4898 currentNoteGuid = newGuid;
4901 if (externalWindows.containsKey(oldGuid)) {
4902 ExternalBrowse b = externalWindows.get(oldGuid);
4903 externalWindows.remove(oldGuid);
4904 b.getBrowserWindow().getNote().setGuid(newGuid);
4905 externalWindows.put(newGuid, b);
4908 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4909 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4910 noteTableView.proxyModel.addGuid(newGuid, listManager.getNoteMetadata().get(newGuid));
4911 i=listManager.getNoteIndex().size();
4915 if (listManager.getNoteTableModel().metaData.containsKey(oldGuid)) {
4916 NoteMetadata meta = listManager.getNoteTableModel().metaData.get(oldGuid);
4917 listManager.getNoteTableModel().metaData.put(newGuid, meta);
4918 listManager.getNoteTableModel().metaData.remove(oldGuid);
4922 // Toggle the note editor button bar
4923 private void toggleEditorButtonBar() {
4924 if (browserWindow.buttonsVisible) {
4925 browserWindow.hideButtons();
4926 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4927 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4929 browserWindow.buttonsVisible = true;
4930 showEditorButtons(browserWindow);
4932 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4934 // Show editor buttons
4935 private void showEditorButtons(BrowserWindow browser) {
4936 browser.buttonLayout.setVisible(true);
4937 browser.undoAction.setVisible(false);
4939 browser.undoButton.setVisible(false);
4941 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4942 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4943 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4944 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4945 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4946 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4947 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4948 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4949 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4950 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4951 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4952 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4953 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4954 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4955 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4956 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4957 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4958 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4959 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4960 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4961 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4962 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4963 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4965 private void duplicateNote(String guid) {
4967 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4968 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4969 oldNote.setContent(conn.getNoteTable().getNoteContentNoUTFConversion(guid));
4970 oldNote.setResources(resList);
4971 duplicateNote(oldNote);
4973 private void duplicateNote(Note oldNote) {
4975 // Now that we have a good notebook guid, we need to move the conflicting note
4976 // to the local notebook
4977 Calendar currentTime = new GregorianCalendar();
4978 Long l = new Long(currentTime.getTimeInMillis());
4979 String newGuid = new String(Long.toString(l));
4981 // Note newNote = oldNote.deepCopy();
4982 Note newNote = (Note)Global.deepCopy(oldNote);
4983 newNote.setUpdateSequenceNum(0);
4984 newNote.setGuid(newGuid);
4985 newNote.setDeleted(0);
4986 newNote.setActive(true);
4989 List<String> tagNames = new ArrayList<String>();
4990 List<String> tagGuids = new ArrayList<String>();;
4991 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4992 tagNames.add(oldNote.getTagNames().get(i));
4993 tagGuids.add(oldNote.getTagGuids().get(i));
4996 // Sort note Tags to make them look nice
4997 for (int i=0; i<tagNames.size()-1; i++) {
4998 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4999 String n1 = tagNames.get(i);
5000 String n2 = tagNames.get(i+1);
5001 tagNames.set(i, n2);
5002 tagNames.set(i+1, n1);
5005 newNote.setTagGuids(tagGuids);
5006 newNote.setTagNames(tagNames);
5008 // Add tag guids to note
5011 // Duplicate resources
5012 List<Resource> resList = oldNote.getResources();
5013 if (resList == null)
5014 resList = new ArrayList<Resource>();
5016 for (int i=0; i<resList.size(); i++) {
5018 while (l == prevGuid) {
5019 currentTime = new GregorianCalendar();
5020 l = new Long(currentTime.getTimeInMillis());
5023 String newResGuid = new String(Long.toString(l));
5024 resList.get(i).setNoteGuid(newGuid);
5025 resList.get(i).setGuid(newResGuid);
5026 resList.get(i).setUpdateSequenceNum(0);
5027 resList.get(i).setActive(true);
5028 conn.getNoteTable().noteResourceTable.saveNoteResource(
5029 (Resource)Global.deepCopy(resList.get(i)), true);
5031 newNote.setResources(resList);
5033 // Add note to the database
5034 conn.getNoteTable().addNote(newNote, true);
5035 NoteMetadata metaData = new NoteMetadata();
5036 NoteMetadata oldMeta = listManager.getNoteMetadata().get(oldNote.getGuid());
5037 metaData.copy(oldMeta);
5038 metaData.setGuid(newNote.getGuid());
5039 listManager.addNote(newNote, metaData);
5040 noteTableView.insertRow(newNote, metaData, true, -1);
5041 currentNoteGuid = newNote.getGuid();
5042 currentNote = newNote;
5043 refreshEvernoteNote(true);
5044 listManager.countNotebookResults(listManager.getNoteIndex());
5048 @SuppressWarnings("unused")
5049 private void allNotes() {
5050 clearAttributeFilter();
5051 clearNotebookFilter();
5052 clearSavedSearchFilter();
5055 searchField.clear();
5056 if (Global.mimicEvernoteInterface) {
5057 notebookTree.selectGuid("");
5059 notebookTreeSelection();
5060 refreshEvernoteNote(true);
5063 @SuppressWarnings("unused")
5064 private void mergeNotes() {
5065 logger.log(logger.HIGH, "Merging notes");
5068 String masterGuid = null;
5069 List<String> sources = new ArrayList<String>();
5071 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
5072 int r = noteTableView.selectionModel().selectedRows().get(i).row();
5073 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
5074 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5076 masterGuid = (String)ix.values().toArray()[0];
5078 sources.add((String)ix.values().toArray()[0]);
5081 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
5082 logger.log(logger.EXTREME, "Children count: "+sources.size());
5083 mergeNoteContents(masterGuid, sources);
5084 currentNoteGuid = masterGuid;
5085 noteIndexUpdated(false);
5086 refreshEvernoteNote(true);
5089 private void mergeNoteContents(String targetGuid, List<String> sources) {
5090 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
5091 String newContent = target.getContent();
5092 newContent = newContent.replace("</en-note>", "<br></br>");
5094 for (int i=0; i<sources.size(); i++) {
5095 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
5096 if (source.isSetTitle()) {
5097 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
5099 String sourceContent = source.getContent();
5100 logger.log(logger.EXTREME, "Merging contents into note");
5101 logger.log(logger.EXTREME, sourceContent);
5102 logger.log(logger.EXTREME, "End of content");
5103 int startOfNote = sourceContent.indexOf("<en-note>");
5104 sourceContent = sourceContent.substring(startOfNote+9);
5105 int endOfNote = sourceContent.indexOf("</en-note>");
5106 sourceContent = sourceContent.substring(0,endOfNote);
5107 newContent = newContent + sourceContent;
5108 logger.log(logger.EXTREME, "New note content");
5109 logger.log(logger.EXTREME, newContent);
5110 logger.log(logger.EXTREME, "End of content");
5111 for (int j=0; j<source.getResourcesSize(); j++) {
5112 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
5113 Resource r = source.getResources().get(j);
5114 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
5116 Calendar currentTime = new GregorianCalendar();
5117 Long l = new Long(currentTime.getTimeInMillis());
5121 while (l == prevGuid) {
5122 currentTime = new GregorianCalendar();
5123 l = new Long(currentTime.getTimeInMillis());
5125 String newResGuid = new String(Long.toString(l));
5126 newRes.setNoteGuid(targetGuid);
5127 newRes.setGuid(newResGuid);
5128 newRes.setUpdateSequenceNum(0);
5129 newRes.setActive(true);
5130 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5133 logger.log(logger.EXTREME, "Updating note");
5134 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5135 for (int i=0; i<sources.size(); i++) {
5136 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5137 listManager.deleteNote(sources.get(i));
5139 logger.log(logger.EXTREME, "Exiting merge note");
5141 // A resource within a note has had a guid change
5142 @SuppressWarnings("unused")
5143 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5144 if (oldGuid != null && !oldGuid.equals(newGuid))
5145 Global.resourceMap.put(oldGuid, newGuid);
5147 // View a thumbnail of the note
5148 public void thumbnailView() {
5150 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5151 QFile thumbnail = new QFile(thumbnailName);
5152 if (!thumbnail.exists()) {
5154 QImage img = new QImage();
5155 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5156 thumbnailViewer.setThumbnail(img);
5158 thumbnailViewer.setThumbnail(thumbnailName);
5159 if (!thumbnailViewer.isVisible())
5160 thumbnailViewer.showFullScreen();
5162 // An error happened while saving a note. Inform the user
5163 @SuppressWarnings("unused")
5164 private void saveRunnerError(String guid, String msg) {
5166 String title = "*Unknown*";
5167 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5168 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5169 title = listManager.getMasterNoteIndex().get(i).getTitle();
5170 i=listManager.getMasterNoteIndex().size();
5173 msg = tr("An error has happened while saving the note \"") +title+
5174 tr("\".\n\nThis is probably due to a document that is too complex for NixNote to process. "+
5175 "As a result, changes to the note may not be saved properly in the database."+
5176 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5177 "\nbe lost. Please review the note to recover any critical data before restarting.");
5179 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5182 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5183 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5184 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5185 // Find an idle preview object
5186 for (int i=0; i<thumbGenerators.size(); i++) {
5187 if (thumbGenerators.get(i).mutex.tryLock()) {
5188 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5189 thumbGenerators.get(i).loadContent(guid, html, zoom);
5193 if (thumbGenerators.size() >= 1) {
5194 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5198 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5199 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5200 thumbGenerators.add(preview);
5202 if (preview.mutex.tryLock()) {
5203 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5204 preview.loadContent(guid, html, zoom);
5206 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5211 //**********************************************************
5212 //**********************************************************
5213 //* Online user actions
5214 //**********************************************************
5215 //**********************************************************
5216 private void setupOnlineMenu() {
5217 if (!Global.isConnected) {
5218 menuBar.noteOnlineHistoryAction.setEnabled(false);
5219 menuBar.selectiveSyncAction.setEnabled(false);
5222 menuBar.noteOnlineHistoryAction.setEnabled(true);
5223 menuBar.selectiveSyncAction.setEnabled(true);
5226 @SuppressWarnings("unused")
5227 private void viewNoteHistory() {
5228 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5230 if (currentNote.getUpdateSequenceNum() == 0) {
5231 setMessage(tr("Note has never been synchronized."));
5232 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5236 setMessage(tr("Getting Note History"));
5238 Note currentOnlineNote = null;
5241 if (Global.isPremium())
5242 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5244 versions = new ArrayList<NoteVersionId>();
5245 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5246 } catch (EDAMUserException e) {
5247 setMessage("EDAMUserException: " +e.getMessage());
5249 } catch (EDAMSystemException e) {
5250 setMessage("EDAMSystemException: " +e.getMessage());
5252 } catch (EDAMNotFoundException e) {
5253 setMessage(tr("Note not found on server."));
5254 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5256 } catch (TException e) {
5257 setMessage("EDAMTransactionException: " +e.getMessage());
5261 // If we've gotten this far, we have a good note.
5262 if (historyWindow == null) {
5263 historyWindow = new OnlineNoteHistory(logger, conn);
5264 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5265 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5266 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5268 historyWindow.historyCombo.clear();
5270 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5271 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5273 historyWindow.setCurrent(isDirty);
5275 loadHistoryWindowContent(currentOnlineNote);
5276 historyWindow.load(versions);
5277 setMessage(tr("History retrieved"));
5279 historyWindow.exec();
5281 private Note reloadHistoryWindow(String selection) {
5283 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5284 String dateTimeFormat = new String(fmt);
5285 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5289 for (int i=0; i<versions.size(); i++) {
5290 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5291 if (versionDate.toString().equals(selection))
5295 if (index > -1 || selection.indexOf("Current") > -1) {
5296 Note historyNote = null;
5299 usn = versions.get(index).getUpdateSequenceNum();
5300 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5302 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5303 } catch (EDAMUserException e) {
5304 setMessage("EDAMUserException: " +e.getMessage());
5307 } catch (EDAMSystemException e) {
5308 setMessage("EDAMSystemException: " +e.getMessage());
5311 } catch (EDAMNotFoundException e) {
5312 setMessage("EDAMNotFoundException: " +e.getMessage());
5315 } catch (TException e) {
5316 setMessage("EDAMTransactionException: " +e.getMessage());
5322 if (historyNote != null)
5323 historyWindow.setContent(historyNote);
5329 private void loadHistoryWindowContent(Note note) {
5330 note.setUpdateSequenceNum(0);
5331 historyWindow.setContent(note);
5333 @SuppressWarnings("unused")
5334 private void restoreHistoryNoteAsNew() {
5335 setMessage(tr("Restoring as new note."));
5336 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5337 setMessage(tr("Note has been restored as a new note."));
5339 @SuppressWarnings("unused")
5340 private void restoreHistoryNote() {
5341 setMessage(tr("Restoring note."));
5342 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5343 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5346 for (int i=0; i<n.getResourcesSize(); i++) {
5347 n.getResources().get(i).setActive(true);
5348 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5350 NoteMetadata metadata = new NoteMetadata();
5351 metadata.setGuid(n.getGuid());
5352 listManager.addNote(n, metadata);
5353 conn.getNoteTable().addNote(n, true);
5354 refreshEvernoteNote(true);
5355 setMessage(tr("Note has been restored."));
5357 @SuppressWarnings("unused")
5358 private void setupSelectiveSync() {
5360 // Get a list of valid notebooks
5361 List<Notebook> notebooks = null;
5362 List<Tag> tags = null;
5363 List<LinkedNotebook> linkedNotebooks = null;
5365 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5366 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5367 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5368 } catch (EDAMUserException e) {
5369 setMessage("EDAMUserException: " +e.getMessage());
5371 } catch (EDAMSystemException e) {
5372 setMessage("EDAMSystemException: " +e.getMessage());
5374 } catch (TException e) {
5375 setMessage("EDAMTransactionException: " +e.getMessage());
5377 } catch (EDAMNotFoundException e) {
5378 setMessage("EDAMNotFoundException: " +e.getMessage());
5382 // Split up notebooks into synchronized & non-synchronized
5383 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5384 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5386 for (int i=notebooks.size()-1; i>=0; i--) {
5387 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5388 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5389 ignoredBooks.add(notebooks.get(i));
5390 j=dbIgnoredNotebooks.size();
5395 // split up tags into synchronized & non-synchronized
5396 List<Tag> ignoredTags = new ArrayList<Tag>();
5397 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5399 for (int i=tags.size()-1; i>=0; i--) {
5400 for (int j=0; j<dbIgnoredTags.size(); j++) {
5401 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5402 ignoredTags.add(tags.get(i));
5403 j=dbIgnoredTags.size();
5408 // split up linked notebooks into synchronized & non-synchronized
5409 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5410 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5411 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5412 String notebookGuid = linkedNotebooks.get(i).getGuid();
5413 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5414 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5415 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5416 j=dbIgnoredLinkedNotebooks.size();
5421 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5423 if (!ignore.okClicked())
5428 // Clear out old notebooks & add the new ones
5429 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5430 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5431 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5434 List<String> newNotebooks = new ArrayList<String>();
5435 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5436 String text = ignore.getIgnoredBookList().takeItem(i).text();
5437 for (int j=0; j<notebooks.size(); j++) {
5438 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5439 Notebook n = notebooks.get(j);
5440 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5442 newNotebooks.add(n.getGuid());
5447 // Clear out old tags & add new ones
5448 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5449 for (int i=0; i<oldIgnoreTags.size(); i++) {
5450 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5453 List<String> newTags = new ArrayList<String>();
5454 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5455 String text = ignore.getIgnoredTagList().takeItem(i).text();
5456 for (int j=0; j<tags.size(); j++) {
5457 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5458 Tag t = tags.get(j);
5459 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5460 newTags.add(t.getGuid());
5466 // Clear out old tags & add new ones
5467 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5468 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5469 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5472 List<String> newLinked = new ArrayList<String>();
5473 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5474 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5475 for (int j=0; j<linkedNotebooks.size(); j++) {
5476 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5477 LinkedNotebook t = linkedNotebooks.get(j);
5478 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5479 newLinked.add(t.getGuid());
5480 j=linkedNotebooks.size();
5485 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5491 //**********************************************************
5492 //**********************************************************
5493 //* XML Modifying methods
5494 //**********************************************************
5495 //**********************************************************
5496 // An error has happended fetching a resource. let the user know
5497 private void resourceErrorMessage() {
5501 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5502 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5503 "In a perfect world this wouldn't happen, but it has.\n" +
5504 "It is embarasing when a program like me, designed to save all your\n"+
5505 "precious data, has a problem finding data.\n\n" +
5506 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5507 "In the mean time, I'm not going to let you make changes to this note.\n" +
5508 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5509 "this note on the Evernote servers. Sorry."+
5510 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5512 browserWindow.setReadOnly(true);
5519 //**********************************************************
5520 //**********************************************************
5522 //**********************************************************
5523 //**********************************************************
5524 // We should now do a sync with Evernote
5525 private void syncTimer() {
5526 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5527 syncRunner.syncNeeded = true;
5528 syncRunner.disableUploads = Global.disableUploads;
5530 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5532 private void syncStart() {
5533 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5535 if (!syncRunning && Global.isConnected) {
5536 syncRunner.setConnected(true);
5537 syncRunner.setKeepRunning(Global.keepRunning);
5538 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5540 if (syncThreadsReady > 0) {
5541 thumbnailRunner.interrupt = true;
5542 saveNoteIndexWidth();
5543 saveNoteColumnPositions();
5544 if (syncRunner.addWork("SYNC")) {
5546 syncRunner.syncNeeded = true;
5551 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5553 @SuppressWarnings("unused")
5554 private void syncThreadComplete(Boolean refreshNeeded) {
5555 setMessage(tr("Finalizing Synchronization"));
5557 syncRunning = false;
5558 syncRunner.syncNeeded = false;
5559 synchronizeAnimationTimer.stop();
5560 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5562 if (currentNote == null) {
5563 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5565 listManager.refreshNoteMetadata();
5566 noteIndexUpdated(true);
5567 noteTableView.selectionModel().blockSignals(true);
5568 scrollToGuid(currentNoteGuid);
5569 noteTableView.selectionModel().blockSignals(false);
5570 refreshEvernoteNote(false);
5571 scrollToGuid(currentNoteGuid);
5574 // Check to see if there were any shared notebook errors
5575 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5576 String guid = syncRunner.errorSharedNotebooks.get(0);
5577 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5578 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5579 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5581 if (syncDialog.okPressed()) {
5582 if (syncDialog.doNothing.isChecked()) {
5583 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5586 if (syncDialog.deleteNotebook.isChecked()) {
5587 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5588 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5589 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5590 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5598 // Finalize the synchronization
5599 if (!syncRunner.error)
5600 setMessage(tr("Synchronization Complete"));
5602 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5603 logger.log(logger.MEDIUM, "Sync complete.");
5605 public void saveUploadAmount(long t) {
5606 Global.saveUploadAmount(t);
5608 public void saveUserInformation(User user) {
5609 Global.saveUserInformation(user);
5611 public void saveEvernoteUpdateCount(int i) {
5612 Global.saveEvernoteUpdateCount(i);
5614 public void refreshLists() {
5615 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5617 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5618 tagIndexUpdated(true);
5619 notebookIndexUpdated();
5620 savedSearchIndexUpdated();
5621 listManager.loadNotesIndex();
5623 noteTableView.selectionModel().blockSignals(true);
5624 noteIndexUpdated(true);
5625 noteTableView.selectionModel().blockSignals(false);
5626 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5630 @SuppressWarnings("unused")
5631 private void authTimer() {
5632 Calendar cal = Calendar.getInstance();
5634 // If we are not connected let's get out of here
5635 if (!Global.isConnected)
5638 // If this is the first time through, then we need to set this
5639 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5640 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5642 // long now = new Date().getTime();
5643 // if (now > Global.authRefreshTime && Global.isConnected) {
5644 syncRunner.authRefreshNeeded = true;
5648 @SuppressWarnings("unused")
5649 private void authRefreshComplete(boolean goodSync) {
5650 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5651 Global.isConnected = syncRunner.isConnected;
5653 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5654 authTimer.start(1000*60*15);
5655 logger.log(logger.LOW, "Authentication token has been renewed");
5656 // setMessage("Authentication token has been renewed.");
5658 authTimer.start(1000*60*5);
5659 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5660 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5662 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5666 @SuppressWarnings("unused")
5667 private synchronized void indexTimer() {
5668 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5671 if (!indexDisabled && indexRunner.idle) {
5672 thumbnailRunner.interrupt = true;
5673 indexRunner.addWork("SCAN");
5675 logger.log(logger.EXTREME, "Leaving NixNote index timer");
5678 @SuppressWarnings("unused")
5679 private void indexStarted() {
5680 setMessage(tr("Indexing notes"));
5682 @SuppressWarnings("unused")
5683 private void indexComplete() {
5684 setMessage(tr("Index complete"));
5686 @SuppressWarnings("unused")
5687 private synchronized void toggleNoteIndexing() {
5688 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5689 indexDisabled = !indexDisabled;
5691 setMessage(tr("Indexing is now enabled."));
5693 setMessage(tr("Indexing is now disabled."));
5694 menuBar.disableIndexing.setChecked(indexDisabled);
5695 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5698 @SuppressWarnings("unused")
5699 private void threadMonitorCheck() {
5704 alive = listManager.threadCheck(Global.tagCounterThreadId);
5707 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5708 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died. I recommend "+
5709 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5710 disableTagThreadCheck = true;
5715 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5717 notebookThreadDeadCount++;
5718 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5719 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died. I recommend "+
5720 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5721 disableNotebookThreadCheck=true;
5724 notebookThreadDeadCount=0;
5726 alive = listManager.threadCheck(Global.trashCounterThreadId);
5729 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5730 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died. I recommend "+
5731 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5732 disableTrashThreadCheck = true;
5737 alive = listManager.threadCheck(Global.saveThreadId);
5739 saveThreadDeadCount++;
5740 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5741 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died. I recommend "+
5742 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5743 disableSaveThreadCheck = true;
5746 saveThreadDeadCount=0;
5748 if (!syncThread.isAlive()) {
5749 syncThreadDeadCount++;
5750 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5751 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died. I recommend "+
5752 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5753 disableSyncThreadCheck = true;
5756 syncThreadDeadCount=0;
5758 if (!indexThread.isAlive()) {
5759 indexThreadDeadCount++;
5760 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5761 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died. I recommend "+
5762 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5763 disableIndexThreadCheck = true;
5766 indexThreadDeadCount=0;
5771 private void thumbnailTimer() {
5772 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5773 thumbnailRunner.addWork("SCAN");
5777 //**************************************************
5778 //* Backup & Restore
5779 //**************************************************
5780 @SuppressWarnings("unused")
5781 private void databaseBackup() {
5782 QFileDialog fd = new QFileDialog(this);
5783 fd.setFileMode(FileMode.AnyFile);
5784 fd.setConfirmOverwrite(true);
5785 fd.setWindowTitle(tr("Backup Database"));
5786 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5787 fd.setAcceptMode(AcceptMode.AcceptSave);
5788 if (saveLastPath == null || saveLastPath.equals(""))
5789 fd.setDirectory(System.getProperty("user.home"));
5791 fd.setDirectory(saveLastPath);
5792 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5798 saveLastPath = fd.selectedFiles().get(0);
5799 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5800 setMessage(tr("Backing up database"));
5802 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5804 ExportData noteWriter = new ExportData(conn, true);
5805 String fileName = fd.selectedFiles().get(0);
5807 if (!fileName.endsWith(".nnex"))
5808 fileName = fileName +".nnex";
5809 noteWriter.exportData(fileName);
5810 setMessage(tr("Database backup completed."));
5815 @SuppressWarnings("unused")
5816 private void databaseRestore() {
5817 if (QMessageBox.question(this, tr("Confirmation"),
5818 tr("This is used to restore a database from backups.\n" +
5819 "It is HIGHLY recommened that this only be used to populate\n" +
5820 "an empty database. Restoring into a database that\n already has data" +
5821 " can cause problems.\n\nAre you sure you want to continue?"),
5822 QMessageBox.StandardButton.Yes,
5823 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5828 QFileDialog fd = new QFileDialog(this);
5829 fd.setFileMode(FileMode.ExistingFile);
5830 fd.setConfirmOverwrite(true);
5831 fd.setWindowTitle(tr("Restore Database"));
5832 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5833 fd.setAcceptMode(AcceptMode.AcceptOpen);
5834 if (saveLastPath == null || saveLastPath.equals(""))
5835 fd.setDirectory(System.getProperty("user.home"));
5837 fd.setDirectory(saveLastPath);
5838 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5844 saveLastPath = fd.selectedFiles().get(0);
5845 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5847 setMessage(tr("Restoring database"));
5848 ImportData noteReader = new ImportData(conn, true);
5849 noteReader.importData(fd.selectedFiles().get(0));
5851 if (noteReader.lastError != 0) {
5852 setMessage(noteReader.getErrorMessage());
5853 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5858 listManager.loadNoteTitleColors();
5860 refreshEvernoteNote(true);
5861 setMessage(tr("Database has been restored."));
5864 @SuppressWarnings("unused")
5865 private void exportNotes() {
5866 QFileDialog fd = new QFileDialog(this);
5867 fd.setFileMode(FileMode.AnyFile);
5868 fd.setConfirmOverwrite(true);
5869 fd.setWindowTitle(tr("Backup Database"));
5870 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5871 fd.setAcceptMode(AcceptMode.AcceptSave);
5872 fd.setDirectory(System.getProperty("user.home"));
5873 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5879 setMessage(tr("Exporting Notes"));
5882 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5883 selectedNoteGUIDs.add(currentNoteGuid);
5885 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5886 String fileName = fd.selectedFiles().get(0);
5888 if (!fileName.endsWith(".nnex"))
5889 fileName = fileName +".nnex";
5890 noteWriter.exportData(fileName);
5891 setMessage(tr("Export completed."));
5897 @SuppressWarnings("unused")
5898 private void importNotes() {
5899 QFileDialog fd = new QFileDialog(this);
5900 fd.setFileMode(FileMode.ExistingFile);
5901 fd.setConfirmOverwrite(true);
5902 fd.setWindowTitle(tr("Import Notes"));
5903 fd.setFilter(tr("NixNote Export (*.nnex);;Evernote Export (*.enex);;All Files (*.*)"));
5904 fd.setAcceptMode(AcceptMode.AcceptOpen);
5905 if (saveLastPath == null || saveLastPath.equals(""))
5906 fd.setDirectory(System.getProperty("user.home"));
5908 fd.setDirectory(saveLastPath);
5909 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5915 setMessage(tr("Importing Notes"));
5918 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5919 selectedNoteGUIDs.add(currentNoteGuid);
5921 String fileName = fd.selectedFiles().get(0);
5922 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5924 if (fileName.endsWith(".nnex")) {
5925 ImportData noteReader = new ImportData(conn, false);
5926 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5927 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5929 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5931 noteReader.importData(fileName);
5933 if (noteReader.lastError != 0) {
5934 setMessage(noteReader.getErrorMessage());
5935 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5940 if (fileName.endsWith(".enex")) {
5941 ImportEnex noteReader = new ImportEnex(conn, false);
5942 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5943 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5945 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5948 if (QMessageBox.question(this, tr("Confirmation"),
5949 tr("Create new tags from import?"),
5950 QMessageBox.StandardButton.Yes,
5951 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
5952 noteReader.createNewTags = true;
5954 noteReader.createNewTags = false;
5956 noteReader.importData(fileName);
5958 if (noteReader.lastError != 0) {
5959 setMessage(noteReader.getErrorMessage());
5960 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5967 listManager.loadNoteTitleColors();
5969 refreshEvernoteNote(false);
5970 setMessage(tr("Notes have been imported."));
5973 setMessage(tr("Import completed."));
5980 //**************************************************
5981 //* Duplicate a note
5982 //**************************************************
5983 @SuppressWarnings("unused")
5984 private void duplicateNote() {
5986 duplicateNote(currentNoteGuid);
5989 //**************************************************
5990 //* Action from when a user clicks Copy As URL
5991 //**************************************************
5992 @SuppressWarnings("unused")
5993 private void copyAsUrlClicked() {
5994 QClipboard clipboard = QApplication.clipboard();
5995 QMimeData mime = new QMimeData();
5997 mime.setText(currentNoteGuid);
5998 List<QUrl> urls = new ArrayList<QUrl>();
6000 // Start building the URL
6001 User user = Global.getUserInformation();
6003 // Check that we have everything we need
6004 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
6005 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
6007 if (!warning.neverSynchronize())
6010 Global.setBypassSynchronizationWarning(true);
6011 user.setShardId("s0");
6017 // Start building a list of URLs based upon the selected notes
6018 noteTableView.showColumn(Global.noteTableGuidPosition);
6020 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
6021 if (!Global.isColumnVisible("guid"))
6022 noteTableView.hideColumn(Global.noteTableGuidPosition);
6024 // Check that the note is either synchronized, or in a local notebook
6025 for (int i=0; i<selections.size(); i++) {
6027 int row = selections.get(i).row();
6028 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
6029 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6030 String selectedGuid = (String)ix.values().toArray()[0];
6032 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6033 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
6034 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
6035 "new notes to a local notebook."));
6040 // Start building the URLs
6041 for (int i=0; i<selections.size(); i++) {
6043 int row = selections.get(i).row();
6044 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
6045 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6046 String selectedGuid = (String)ix.values().toArray()[0];
6047 mime.setText(selectedGuid);
6051 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6052 if (selectedNote.getUpdateSequenceNum() > 0) {
6056 gid = "00000000-0000-0000-0000-000000000000";
6059 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
6061 urls.add(new QUrl(url));
6064 clipboard.setMimeData(mime);
6068 //**************************************************
6070 //**************************************************
6071 public void setupFolderImports() {
6072 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
6074 if (importKeepWatcher == null)
6075 importKeepWatcher = new QFileSystemWatcher();
6076 if (importDeleteWatcher == null) {
6077 importDeleteWatcher = new QFileSystemWatcher();
6078 for (int i=0; i<records.size(); i++) {
6079 if (!records.get(i).keep)
6080 folderImportDelete(records.get(i).folder);
6086 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
6087 for (int i=0; i<records.size(); i++) {
6088 if (records.get(i).keep)
6089 importKeepWatcher.addPath(records.get(i).folder);
6091 importDeleteWatcher.addPath(records.get(i).folder);
6094 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
6095 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
6097 // Look at the files already there so we don't import them again if a new file is created
6098 if (importedFiles == null) {
6099 importedFiles = new ArrayList<String>();
6100 for (int j=0; j<records.size(); j++) {
6101 QDir dir = new QDir(records.get(j).folder);
6102 List<QFileInfo> list = dir.entryInfoList();
6103 for (int k=0; k<list.size(); k++) {
6104 if (list.get(k).isFile())
6105 importedFiles.add(list.get(k).absoluteFilePath());
6110 public void folderImport() {
6111 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
6112 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
6114 if (!dialog.okClicked())
6117 // We have some sort of update.
6118 if (importKeepWatcher.directories().size() > 0)
6119 importKeepWatcher.removePaths(importKeepWatcher.directories());
6120 if (importDeleteWatcher.directories().size() > 0)
6121 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
6123 conn.getWatchFolderTable().expungeAll();
6124 // Start building from the table
6125 for (int i=0; i<dialog.table.rowCount(); i++) {
6126 QTableWidgetItem item = dialog.table.item(i, 0);
6127 String dir = item.text();
6128 item = dialog.table.item(i, 1);
6129 String notebook = item.text();
6130 item = dialog.table.item(i, 2);
6132 if (item.text().equalsIgnoreCase("Keep"))
6137 String guid = conn.getNotebookTable().findNotebookByName(notebook);
6138 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
6140 setupFolderImports();
6143 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
6145 String whichOS = System.getProperty("os.name");
6146 if (whichOS.contains("Windows"))
6147 dirName = dirName.replace('/','\\');
6149 FileImporter importer = new FileImporter(logger, conn);
6151 QDir dir = new QDir(dirName);
6152 List<QFileInfo> list = dir.entryInfoList();
6153 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6155 for (int i=0; i<list.size(); i++){
6157 boolean redundant = false;
6158 // Check if we've already imported this one or if it existed before
6159 for (int j=0; j<importedFiles.size(); j++) {
6160 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6165 importer.setFileInfo(list.get(i));
6166 importer.setFileName(list.get(i).absoluteFilePath());
6169 if (list.get(i).isFile() && importer.isValidType()) {
6171 if (!importer.importFile()) {
6172 // If we can't get to the file, it is probably locked. We'll try again later.
6173 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6174 importFilesKeep.add(list.get(i).absoluteFilePath());
6178 Note newNote = importer.getNote();
6179 newNote.setNotebookGuid(notebook);
6180 newNote.setTitle(dir.at(i));
6181 NoteMetadata metadata = new NoteMetadata();
6182 metadata.setDirty(true);
6183 metadata.setGuid(newNote.getGuid());
6184 listManager.addNote(newNote, metadata);
6185 conn.getNoteTable().addNote(newNote, true);
6186 noteTableView.insertRow(newNote, metadata, true, -1);
6187 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6188 listManager.countNotebookResults(listManager.getNoteIndex());
6189 importedFiles.add(list.get(i).absoluteFilePath());
6197 public void folderImportDelete(String dirName) {
6199 String whichOS = System.getProperty("os.name");
6200 if (whichOS.contains("Windows"))
6201 dirName = dirName.replace('/','\\');
6203 FileImporter importer = new FileImporter(logger, conn);
6204 QDir dir = new QDir(dirName);
6205 List<QFileInfo> list = dir.entryInfoList();
6206 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6208 for (int i=0; i<list.size(); i++){
6209 importer.setFileInfo(list.get(i));
6210 importer.setFileName(list.get(i).absoluteFilePath());
6212 if (list.get(i).isFile() && importer.isValidType()) {
6214 if (!importer.importFile()) {
6215 // If we can't get to the file, it is probably locked. We'll try again later.
6216 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6217 importFilesKeep.add(list.get(i).absoluteFilePath());
6221 Note newNote = importer.getNote();
6222 newNote.setNotebookGuid(notebook);
6223 newNote.setTitle(dir.at(i));
6224 NoteMetadata metadata = new NoteMetadata();
6225 metadata.setDirty(true);
6226 metadata.setGuid(newNote.getGuid());
6227 listManager.addNote(newNote, metadata);
6228 conn.getNoteTable().addNote(newNote, true);
6229 noteTableView.insertRow(newNote, metadata, true, -1);
6230 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6231 listManager.countNotebookResults(listManager.getNoteIndex());
6232 dir.remove(dir.at(i));
6238 //**************************************************
6240 //**************************************************
6241 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6242 logger.log(logger.HIGH, "Entering exernalFileEdited");
6244 // Strip URL prefix and base dir path
6245 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6246 String name = fileName.replace(dPath, "");
6247 int pos = name.lastIndexOf('.');
6250 guid = guid.substring(0,pos);
6252 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6254 guid = name.substring(0, pos);
6257 QFile file = new QFile(fileName);
6258 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6259 // If we can't get to the file, it is probably locked. We'll try again later.
6260 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6261 externalFiles.add(fileName);
6264 QByteArray binData = file.readAll();
6266 if (binData.size() == 0) {
6267 // If we can't get to the file, it is probably locked. We'll try again later.
6268 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6269 externalFiles.add(fileName);
6273 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6275 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6276 if (r == null || r.getData() == null || r.getData().getBody() == null)
6278 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6279 MessageDigest md = MessageDigest.getInstance("MD5");
6280 md.update(binData.toByteArray());
6281 byte[] hash = md.digest();
6282 String newHash = Global.byteArrayToHexString(hash);
6283 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6284 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6286 if (externalWindows.containsKey(r.getNoteGuid())) {
6287 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6288 r.getGuid(), oldHash, newHash);
6290 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6291 Data data = r.getData();
6292 data.setBody(binData.toByteArray());
6293 data.setBodyHash(hash);
6294 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6296 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6298 if (r.getNoteGuid().equals(currentNoteGuid)) {
6299 QWebSettings.setMaximumPagesInCache(0);
6300 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6301 refreshEvernoteNote(true);
6302 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6305 if (externalWindows.containsKey(r.getNoteGuid())) {
6306 QWebSettings.setMaximumPagesInCache(0);
6307 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6308 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6312 logger.log(logger.HIGH, "Exiting externalFielEdited");
6314 // This is a timer event that tries to save any external files that were edited. This
6315 // is only needed if we couldn't save a file earlier.
6316 public void externalFileEditedSaver() {
6317 for (int i=externalFiles.size()-1; i>=0; i--) {
6319 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6320 externalFileEdited(externalFiles.get(i));
6321 externalFiles.remove(i);
6322 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6324 for (int i=0; i<importFilesKeep.size(); i++) {
6326 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6327 folderImportKeep(importFilesKeep.get(i));
6328 importFilesKeep.remove(i);
6329 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6331 for (int i=0; i<importFilesDelete.size(); i++) {
6332 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6333 folderImportDelete(importFilesDelete.get(i));
6334 importFilesDelete.remove(i);
6341 // If an attachment on the current note was edited, we need to update the current notes's hash
6342 // Update a note content's hash. This happens if a resource is edited outside of NN
6343 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6344 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6346 for (;position>-1;) {
6347 endPos = browser.getContent().indexOf(">", position+1);
6348 String oldSegment = browser.getContent().substring(position,endPos);
6349 int hashPos = oldSegment.indexOf("hash=\"");
6350 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6351 String hash = oldSegment.substring(hashPos+6, hashEnd);
6352 if (hash.equalsIgnoreCase(oldHash)) {
6353 String newSegment = oldSegment.replace(oldHash, newHash);
6354 String content = browser.getContent().substring(0,position) +
6356 browser.getContent().substring(endPos);
6357 browser.setContent(new QByteArray(content));;
6360 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6365 //*************************************************
6366 //* Minimize to tray
6367 //*************************************************
6369 public void changeEvent(QEvent e) {
6370 if (e.type() == QEvent.Type.WindowStateChange) {
6371 if (QSystemTrayIcon.isSystemTrayAvailable()) {
6372 if (isMinimized() && (Global.showTrayIcon() || Global.showTrayIcon())) {
6374 QTimer.singleShot(10, this, "hide()");
6378 windowMaximized = true;
6380 windowMaximized = false;
6385 //*************************************************
6386 //* Check database userid & passwords
6387 //*************************************************
6388 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6389 Connection connection;
6392 Class.forName("org.h2.Driver");
6393 } catch (ClassNotFoundException e1) {
6394 e1.printStackTrace();
6399 String passwordString = null;
6400 if (cypherPassword==null || cypherPassword.trim().equals(""))
6401 passwordString = userPassword;
6403 passwordString = cypherPassword+" "+userPassword;
6404 connection = DriverManager.getConnection(url,userid,passwordString);
6405 } catch (SQLException e) {
6410 } catch (SQLException e) {
6411 e.printStackTrace();
6416 //*************************************************
6417 //* View / Hide source HTML for a note
6418 //*************************************************
6419 public void viewSource() {
6420 browserWindow.showSource(menuBar.viewSource.isChecked());
6422 //*************************************************
6423 // Block the program. This is used for things
6424 // like async web calls.
6425 //*************************************************
6426 @SuppressWarnings("unused")
6427 private void blockApplication(BrowserWindow b) {
6428 // Block all signals
6432 blockTimer = new QTimer();
6433 blockTimer.setSingleShot(true);
6434 blockTimer.setInterval(15000);
6435 blockTimer.timeout.connect(this, "unblockApplication()");
6440 @SuppressWarnings("unused")
6441 private void unblockApplication() {
6443 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6444 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6445 blockingWindow.unblockTime = -1;
6446 blockingWindow.awaitingHttpResponse = false;
6448 blockingWindow = null;
6449 blockSignals(false);