2 * This file is part of NixNote
3 * Copyright 2009 Randy Baumgarte
5 * This file may be licensed under the terms of of the
6 * GNU General Public License Version 2 (the ``GPL'').
8 * Software distributed under the License is distributed
9 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10 * express or implied. See the GPL for the specific language
11 * governing rights and limitations.
13 * You should have received a copy of the GPL along with this
14 * program. If not, go to http://www.gnu.org/licenses/gpl.html
15 * or write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 package cx.fbn.nevernote;
20 import java.awt.Desktop;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.net.Authenticator;
25 import java.net.PasswordAuthentication;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.SQLException;
31 import java.sql.Statement;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.SortedMap;
44 import java.util.Vector;
46 import org.apache.log4j.Level;
47 import org.apache.log4j.Logger;
48 import org.apache.thrift.TException;
49 import org.h2.tools.ChangeFileEncryption;
51 import com.evernote.edam.error.EDAMNotFoundException;
52 import com.evernote.edam.error.EDAMSystemException;
53 import com.evernote.edam.error.EDAMUserException;
54 import com.evernote.edam.notestore.NoteFilter;
55 import com.evernote.edam.notestore.NoteVersionId;
56 import com.evernote.edam.type.Data;
57 import com.evernote.edam.type.LinkedNotebook;
58 import com.evernote.edam.type.Note;
59 import com.evernote.edam.type.NoteAttributes;
60 import com.evernote.edam.type.Notebook;
61 import com.evernote.edam.type.Publishing;
62 import com.evernote.edam.type.QueryFormat;
63 import com.evernote.edam.type.Resource;
64 import com.evernote.edam.type.SavedSearch;
65 import com.evernote.edam.type.Tag;
66 import com.evernote.edam.type.User;
67 import com.trolltech.qt.QThread;
68 import com.trolltech.qt.core.QByteArray;
69 import com.trolltech.qt.core.QDateTime;
70 import com.trolltech.qt.core.QDir;
71 import com.trolltech.qt.core.QEvent;
72 import com.trolltech.qt.core.QFile;
73 import com.trolltech.qt.core.QFileInfo;
74 import com.trolltech.qt.core.QFileSystemWatcher;
75 import com.trolltech.qt.core.QIODevice;
76 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
77 import com.trolltech.qt.core.QLocale;
78 import com.trolltech.qt.core.QMimeData;
79 import com.trolltech.qt.core.QModelIndex;
80 import com.trolltech.qt.core.QSize;
81 import com.trolltech.qt.core.QTemporaryFile;
82 import com.trolltech.qt.core.QTextCodec;
83 import com.trolltech.qt.core.QThreadPool;
84 import com.trolltech.qt.core.QTimer;
85 import com.trolltech.qt.core.QTranslator;
86 import com.trolltech.qt.core.QUrl;
87 import com.trolltech.qt.core.Qt;
88 import com.trolltech.qt.core.Qt.BGMode;
89 import com.trolltech.qt.core.Qt.ItemDataRole;
90 import com.trolltech.qt.core.Qt.KeyboardModifier;
91 import com.trolltech.qt.core.Qt.MouseButton;
92 import com.trolltech.qt.core.Qt.SortOrder;
93 import com.trolltech.qt.core.Qt.WidgetAttribute;
94 import com.trolltech.qt.gui.QAbstractItemView;
95 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
96 import com.trolltech.qt.gui.QAction;
97 import com.trolltech.qt.gui.QApplication;
98 import com.trolltech.qt.gui.QClipboard;
99 import com.trolltech.qt.gui.QCloseEvent;
100 import com.trolltech.qt.gui.QColor;
101 import com.trolltech.qt.gui.QComboBox;
102 import com.trolltech.qt.gui.QCursor;
103 import com.trolltech.qt.gui.QDesktopServices;
104 import com.trolltech.qt.gui.QDialog;
105 import com.trolltech.qt.gui.QFileDialog;
106 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
107 import com.trolltech.qt.gui.QFileDialog.FileMode;
108 import com.trolltech.qt.gui.QGridLayout;
109 import com.trolltech.qt.gui.QHBoxLayout;
110 import com.trolltech.qt.gui.QIcon;
111 import com.trolltech.qt.gui.QImage;
112 import com.trolltech.qt.gui.QKeySequence;
113 import com.trolltech.qt.gui.QLabel;
114 import com.trolltech.qt.gui.QMainWindow;
115 import com.trolltech.qt.gui.QMenu;
116 import com.trolltech.qt.gui.QMessageBox;
117 import com.trolltech.qt.gui.QMessageBox.StandardButton;
118 import com.trolltech.qt.gui.QPainter;
119 import com.trolltech.qt.gui.QPalette.ColorRole;
120 import com.trolltech.qt.gui.QPixmap;
121 import com.trolltech.qt.gui.QPrintDialog;
122 import com.trolltech.qt.gui.QPrinter;
123 import com.trolltech.qt.gui.QShortcut;
124 import com.trolltech.qt.gui.QSizePolicy;
125 import com.trolltech.qt.gui.QSizePolicy.Policy;
126 import com.trolltech.qt.gui.QSpinBox;
127 import com.trolltech.qt.gui.QSplashScreen;
128 import com.trolltech.qt.gui.QSplitter;
129 import com.trolltech.qt.gui.QStatusBar;
130 import com.trolltech.qt.gui.QSystemTrayIcon;
131 import com.trolltech.qt.gui.QTableWidgetItem;
132 import com.trolltech.qt.gui.QTextEdit;
133 import com.trolltech.qt.gui.QToolBar;
134 import com.trolltech.qt.gui.QTreeWidgetItem;
135 import com.trolltech.qt.network.QNetworkAccessManager;
136 import com.trolltech.qt.network.QNetworkReply;
137 import com.trolltech.qt.network.QNetworkRequest;
138 import com.trolltech.qt.webkit.QWebPage.WebAction;
139 import com.trolltech.qt.webkit.QWebSettings;
141 import cx.fbn.nevernote.config.InitializationException;
142 import cx.fbn.nevernote.config.StartupConfig;
143 import cx.fbn.nevernote.dialog.AccountDialog;
144 import cx.fbn.nevernote.dialog.ConfigDialog;
145 import cx.fbn.nevernote.dialog.DBEncryptDialog;
146 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
147 import cx.fbn.nevernote.dialog.DatabaseStatus;
148 import cx.fbn.nevernote.dialog.FindDialog;
149 import cx.fbn.nevernote.dialog.IgnoreSync;
150 import cx.fbn.nevernote.dialog.LogFileDialog;
151 import cx.fbn.nevernote.dialog.LoginDialog;
152 import cx.fbn.nevernote.dialog.NotebookArchive;
153 import cx.fbn.nevernote.dialog.NotebookEdit;
154 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
155 import cx.fbn.nevernote.dialog.PublishNotebook;
156 import cx.fbn.nevernote.dialog.SavedSearchEdit;
157 import cx.fbn.nevernote.dialog.SetIcon;
158 import cx.fbn.nevernote.dialog.ShareNotebook;
159 import cx.fbn.nevernote.dialog.SharedNotebookSyncError;
160 import cx.fbn.nevernote.dialog.StackNotebook;
161 import cx.fbn.nevernote.dialog.SynchronizationRequiredWarning;
162 import cx.fbn.nevernote.dialog.TagEdit;
163 import cx.fbn.nevernote.dialog.TagMerge;
164 import cx.fbn.nevernote.dialog.ThumbnailViewer;
165 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
166 import cx.fbn.nevernote.dialog.WatchFolder;
167 import cx.fbn.nevernote.evernote.NoteMetadata;
168 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
169 import cx.fbn.nevernote.filters.FilterEditorTags;
170 import cx.fbn.nevernote.gui.AttributeTreeWidget;
171 import cx.fbn.nevernote.gui.BrowserWindow;
172 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
173 import cx.fbn.nevernote.gui.ExternalBrowse;
174 import cx.fbn.nevernote.gui.MainMenuBar;
175 import cx.fbn.nevernote.gui.NotebookTreeWidget;
176 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
177 import cx.fbn.nevernote.gui.SearchPanel;
178 import cx.fbn.nevernote.gui.TableView;
179 import cx.fbn.nevernote.gui.TagTreeWidget;
180 import cx.fbn.nevernote.gui.Thumbnailer;
181 import cx.fbn.nevernote.gui.TrashTreeWidget;
182 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
183 import cx.fbn.nevernote.sql.DatabaseConnection;
184 import cx.fbn.nevernote.sql.WatchFolderRecord;
185 import cx.fbn.nevernote.threads.IndexRunner;
186 import cx.fbn.nevernote.threads.SyncRunner;
187 import cx.fbn.nevernote.threads.ThumbnailRunner;
188 import cx.fbn.nevernote.utilities.AESEncrypter;
189 import cx.fbn.nevernote.utilities.ApplicationLogger;
190 import cx.fbn.nevernote.utilities.FileImporter;
191 import cx.fbn.nevernote.utilities.FileUtils;
192 import cx.fbn.nevernote.utilities.ListManager;
193 import cx.fbn.nevernote.utilities.SyncTimes;
194 import cx.fbn.nevernote.xml.ExportData;
195 import cx.fbn.nevernote.xml.ImportData;
196 import cx.fbn.nevernote.xml.ImportEnex;
197 import cx.fbn.nevernote.xml.NoteFormatter;
200 public class NeverNote extends QMainWindow{
202 QStatusBar statusBar; // Application status bar
204 DatabaseConnection conn;
206 MainMenuBar menuBar; // Main menu bar
207 FindDialog find; // Text search in note dialog
208 List<String> emitLog; // Messages displayed in the status bar;
209 QSystemTrayIcon trayIcon; // little tray icon
210 QMenu trayMenu; // System tray menu
211 QAction trayExitAction; // Exit the application
212 QAction trayShowAction; // toggle the show/hide action
213 QAction trayAddNoteAction; // Add a note from the system tray
214 QNetworkAccessManager versionChecker; // Used when checking for new versions
216 NotebookTreeWidget notebookTree; // List of notebooks
217 AttributeTreeWidget attributeTree; // List of note attributes
218 TagTreeWidget tagTree; // list of user created tags
219 SavedSearchTreeWidget savedSearchTree; // list of saved searches
220 TrashTreeWidget trashTree; // Trashcan
221 TableView noteTableView; // List of notes (the widget).
223 public BrowserWindow browserWindow; // Window containing browser & labels
224 public QToolBar toolBar; // The tool bar under the menu
225 QComboBox searchField; // search filter bar on the toolbar;
226 QShortcut searchShortcut; // Shortcut to search bar
227 boolean searchPerformed = false; // Search was done?
228 QuotaProgressBar quotaBar; // The current quota usage
230 ApplicationLogger logger;
231 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
232 List<String> selectedTagGUIDs; // List of selected tag GUIDs
233 List<String> selectedNoteGUIDs; // List of selected notes
234 String selectedSavedSearchGUID; // Currently selected saved searches
235 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
237 NoteFilter filter; // Note filter
238 String currentNoteGuid; // GUID of the current note
239 Note currentNote; // The currently viewed note
240 boolean noteDirty; // Has the note been changed?
241 boolean inkNote; // if this is an ink note, it is read only
242 boolean readOnly; // Is this note read-only?
245 ListManager listManager; // DB runnable task
247 List<QTemporaryFile> tempFiles; // Array of temporary files;
249 QTimer indexTimer; // timer to start the index thread
250 IndexRunner indexRunner; // thread to index notes
253 QTimer syncTimer; // Sync on an interval
254 QTimer syncDelayTimer; // Sync delay to free up database
255 SyncRunner syncRunner; // thread to do a sync.
256 QThread syncThread; // Thread which talks to evernote
257 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
258 QThread thumbnailThread; // Thread that generates pretty pictures
259 QTimer saveTimer; // Timer to save note contents
261 QTimer authTimer; // Refresh authentication
262 QTimer externalFileSaveTimer; // Save files altered externally
263 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
264 List<String> externalFiles; // External files to save later
265 List<String> importFilesKeep; // Auto-import files to save later
266 List<String> importFilesDelete; // Auto-import files to save later
268 int indexTime; // how often to try and index
269 boolean indexRunning; // Is indexing running?
270 boolean indexDisabled; // Is indexing disabled?
272 int syncThreadsReady; // number of sync threads that are free
273 int syncTime; // Sync interval
274 boolean syncRunning; // Is sync running?
275 boolean automaticSync; // do sync automatically?
276 QTreeWidgetItem attributeTreeSelected;
278 QAction prevButton; // Go to the previous item viewed
279 QAction nextButton; // Go to the next item in the history
280 QAction downButton; // Go to the next item in the list
281 QAction upButton; // Go to the prev. item in the list;
282 QAction synchronizeButton; // Synchronize with Evernote
283 QAction allNotesButton; // Reset & view all notes
284 QTimer synchronizeAnimationTimer; // Timer to change animation button
285 int synchronizeIconAngle; // Used to rotate sync icon
286 QAction printButton; // Print Button
287 QAction tagButton; // Tag edit button
288 QAction attributeButton; // Attribute information button
289 QAction emailButton; // Email button
290 QAction deleteButton; // Delete button
291 QAction newButton; // new Note Button;
292 QSpinBox zoomSpinner; // Zoom zoom
293 QAction searchClearButton; // Clear the search field
295 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
297 QSplitter mainLeftRightSplitter; // main splitter for left/right side
298 QSplitter leftSplitter1; // first left hand splitter
299 QSplitter browserIndexSplitter; // splitter between note index & note text
301 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
302 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
303 List<String> importedFiles; // History of imported files (so we don't import twice)
305 OnlineNoteHistory historyWindow; // online history window
306 List<NoteVersionId> versions; // history versions
308 QTimer threadMonitorTimer; // Timer to watch threads.
309 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
310 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
311 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
312 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
313 int tagDeadCount=0; // number of consecutive dead times for the tag thread
314 int trashDeadCount=0; // number of consecutive dead times for the trash thread
315 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
316 boolean disableTagThreadCheck=false;
317 boolean disableNotebookThreadCheck=false;
318 boolean disableTrashThreadCheck=false;
319 boolean disableSaveThreadCheck=false;
320 boolean disableSyncThreadCheck=false;
321 boolean disableIndexThreadCheck=false;
323 HashMap<String, String> noteCache; // Cash of note content
324 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
325 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
326 List<String> historyGuids; // GUIDs of previously viewed items
327 int historyPosition; // Position within the viewed items
328 boolean fromHistory; // Is this from the history queue?
329 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
330 List<Thumbnailer> thumbGenerators; // generate preview image
331 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
332 boolean encryptOnShutdown; // should I encrypt when I close?
333 boolean decryptOnShutdown; // should I decrypt on shutdown;
334 String encryptCipher; // What cipher should I use?
335 Signal0 minimizeToTray;
336 boolean windowMaximized = false; // Keep track of the window state for restores
337 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
338 List<QPixmap> syncIcons; // Array of icons used in sync animation
339 private boolean closeAction = false; // Used to say when to close or when to minimize
340 private static Logger log = Logger.getLogger(NeverNote.class);
341 private String saveLastPath; // last path we used
342 private final QTimer messageTimer; // Timer to clear the status message.
343 private QTimer blockTimer;
344 BrowserWindow blockingWindow;
346 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
349 //***************************************************************
350 //***************************************************************
351 //** Constructor & main entry point
352 //***************************************************************
353 //***************************************************************
354 // Application Constructor
355 @SuppressWarnings("static-access")
356 public NeverNote(DatabaseConnection dbConn) {
358 if (conn.getConnection() == null) {
359 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
360 "is accessing the database or NixNote is already running.\n\n" +
361 "Please end any other process or shutdown the other NixNote before starting.\n\nExiting program."));
363 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
366 setObjectName("mainWindow");
367 // thread().setPriority(Thread.MAX_PRIORITY);
369 logger = new ApplicationLogger("nevernote.log");
370 logger.log(logger.HIGH, "Starting Application");
372 decryptOnShutdown = false;
373 encryptOnShutdown = false;
374 conn.checkDatabaseVersion();
378 // Start building the invalid XML tables
379 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
380 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
382 for (int i=0; i<elements.size(); i++) {
383 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
386 logger.log(logger.EXTREME, "Starting GUI build");
388 QTranslator nevernoteTranslator = new QTranslator();
389 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
390 QApplication.instance().installTranslator(nevernoteTranslator);
392 Global.originalPalette = QApplication.palette();
393 QApplication.setStyle(Global.getStyle());
394 if (Global.useStandardPalette())
395 QApplication.setPalette(QApplication.style().standardPalette());
396 setWindowTitle(tr("NixNote"));
398 mainLeftRightSplitter = new QSplitter();
399 setCentralWidget(mainLeftRightSplitter);
400 leftSplitter1 = new QSplitter();
401 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
403 browserIndexSplitter = new QSplitter();
404 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
406 //* Setup threads & thread timers
407 // int indexRunnerCount = Global.getIndexThreads();
408 // indexRunnerCount = 1;
409 QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount); // increase max thread count
411 logger.log(logger.EXTREME, "Building list manager");
412 listManager = new ListManager(conn, logger);
414 logger.log(logger.EXTREME, "Building index runners & timers");
415 indexRunner = new IndexRunner("indexRunner.log",
416 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
417 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
418 indexThread = new QThread(indexRunner, "Index Thread");
419 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
420 indexRunner.indexImageRecognition = Global.indexImageRecognition();
421 indexRunner.indexNoteBody = Global.indexNoteBody();
422 indexRunner.indexNoteTitle = Global.indexNoteTitle();
423 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
426 synchronizeAnimationTimer = new QTimer();
427 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
429 indexTimer = new QTimer();
430 indexTime = 1000*Global.getIndexThreadSleepInterval();
431 indexTimer.start(indexTime); // Start indexing timer
432 indexTimer.timeout.connect(this, "indexTimer()");
433 indexDisabled = false;
434 indexRunning = false;
436 logger.log(logger.EXTREME, "Setting sync thread & timers");
438 syncRunner = new SyncRunner("syncRunner.log",
439 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
440 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
441 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
442 syncTimer = new QTimer();
443 syncTimer.timeout.connect(this, "syncTimer()");
444 syncRunner.status.message.connect(this, "setMessage(String)");
445 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
446 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
449 automaticSync = true;
450 syncTimer.start(syncTime*60*1000);
452 automaticSync = false;
455 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
456 syncThread = new QThread(syncRunner, "Synchronization Thread");
460 logger.log(logger.EXTREME, "Starting thumnail thread");
461 pdfReadyQueue = new ArrayList<String>();
462 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
463 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
464 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
465 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
466 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
467 thumbnailThread.start();
468 thumbGenerators = new ArrayList<Thumbnailer>();
469 thumbnailTimer = new QTimer();
470 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
472 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
473 thumbnailTimer.start();
475 logger.log(logger.EXTREME, "Starting authentication timer");
476 authTimer = new QTimer();
477 authTimer.timeout.connect(this, "authTimer()");
478 authTimer.start(1000*60*15);
479 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
481 logger.log(logger.EXTREME, "Setting save note timer");
482 saveTimer = new QTimer();
483 saveTimer.timeout.connect(this, "saveNote()");
484 if (Global.getAutoSaveInterval() > 0) {
485 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
488 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
490 logger.log(logger.EXTREME, "Starting external file monitor timer");
491 externalFileSaveTimer = new QTimer();
492 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
493 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
494 externalFiles = new ArrayList<String>();
495 importFilesDelete = new ArrayList<String>();
496 importFilesKeep = new ArrayList<String>();
497 externalFileSaveTimer.start();
499 notebookTree = new NotebookTreeWidget(conn);
500 attributeTree = new AttributeTreeWidget();
501 tagTree = new TagTreeWidget(conn);
502 savedSearchTree = new SavedSearchTreeWidget();
503 trashTree = new TrashTreeWidget();
504 noteTableView = new TableView(logger, listManager);
506 searchField = new QComboBox();
507 searchField.setObjectName("searchField");
508 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
509 searchField.setEditable(true);
510 searchField.activatedIndex.connect(this, "searchFieldChanged()");
511 searchField.setDuplicatesEnabled(false);
512 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
513 searchShortcut = new QShortcut(this);
514 setupShortcut(searchShortcut, "Focus_Search");
515 searchShortcut.activated.connect(this, "focusSearch()");
517 quotaBar = new QuotaProgressBar();
519 zoomSpinner = new QSpinBox();
520 zoomSpinner.setMinimum(10);
521 zoomSpinner.setMaximum(1000);
522 zoomSpinner.setAccelerated(true);
523 zoomSpinner.setSingleStep(10);
524 zoomSpinner.setValue(100);
525 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
527 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
530 QGridLayout leftGrid = new QGridLayout();
531 leftSplitter1.setContentsMargins(5, 0, 0, 7);
532 leftSplitter1.setLayout(leftGrid);
533 leftGrid.addWidget(searchLayout,1,1);
534 leftGrid.addWidget(tagTree,2,1);
535 leftGrid.addWidget(attributeTree,3,1);
536 leftGrid.addWidget(savedSearchTree,4,1);
537 leftGrid.addWidget(trashTree,5, 1);
539 // Setup the browser window
540 noteCache = new HashMap<String,String>();
541 readOnlyCache = new HashMap<String, Boolean>();
542 inkNoteCache = new HashMap<String, Boolean>();
543 browserWindow = new BrowserWindow(conn);
545 mainLeftRightSplitter.addWidget(leftSplitter1);
546 mainLeftRightSplitter.addWidget(browserIndexSplitter);
548 if (Global.getListView() == Global.View_List_Wide) {
549 browserIndexSplitter.addWidget(noteTableView);
550 browserIndexSplitter.addWidget(browserWindow);
552 mainLeftRightSplitter.addWidget(noteTableView);
553 mainLeftRightSplitter.addWidget(browserWindow);
556 // Setup the thumbnail viewer
557 thumbnailViewer = new ThumbnailViewer();
558 thumbnailViewer.upArrow.connect(this, "upAction()");
559 thumbnailViewer.downArrow.connect(this, "downAction()");
560 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
561 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
563 //Setup external browser manager
564 externalWindows = new HashMap<String, ExternalBrowse>();
566 listManager.loadNotesIndex();
567 initializeNotebookTree();
569 initializeSavedSearchTree();
570 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
571 attributeTreeSelected = null;
572 initializeNoteTable();
574 selectedNoteGUIDs = new ArrayList<String>();
575 statusBar = new QStatusBar();
576 setStatusBar(statusBar);
577 menuBar = new MainMenuBar(this);
578 emitLog = new ArrayList<String>();
580 tagTree.setDeleteAction(menuBar.tagDeleteAction);
581 tagTree.setMergeAction(menuBar.tagMergeAction);
582 tagTree.setEditAction(menuBar.tagEditAction);
583 tagTree.setAddAction(menuBar.tagAddAction);
584 tagTree.setIconAction(menuBar.tagIconAction);
585 tagTree.setVisible(Global.isWindowVisible("tagTree"));
586 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
587 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
588 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
589 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
591 if (!Global.isWindowVisible("zoom")) {
592 searchLayout.hideZoom();
593 menuBar.hideZoom.setChecked(false);
596 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
597 notebookTree.setEditAction(menuBar.notebookEditAction);
598 notebookTree.setAddAction(menuBar.notebookAddAction);
599 notebookTree.setIconAction(menuBar.notebookIconAction);
600 notebookTree.setStackAction(menuBar.notebookStackAction);
601 notebookTree.setPublishAction(menuBar.notebookPublishAction);
602 notebookTree.setShareAction(menuBar.notebookShareAction);
603 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
604 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
605 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
606 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
607 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
609 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
610 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
611 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
612 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
613 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
614 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
615 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
617 noteTableView.setAddAction(menuBar.noteAdd);
618 noteTableView.setDeleteAction(menuBar.noteDelete);
619 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
620 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
621 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
622 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
623 noteTableView.noteSignal.notePinned.connect(this, "notePinned()");
624 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
625 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
626 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
627 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
629 quotaBar.setMouseClickAction(menuBar.accountAction);
632 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
633 trashTree.setEmptyAction(menuBar.emptyTrashAction);
634 trashTree.setVisible(Global.isWindowVisible("trashTree"));
635 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
636 trashTree.updateCounts(listManager.getTrashCount());
637 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
638 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
640 noteTableView.setVisible(Global.isWindowVisible("noteList"));
641 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
643 if (!Global.isWindowVisible("editorButtonBar"))
644 toggleEditorButtonBar();
645 if (!Global.isWindowVisible("leftPanel"))
646 menuBar.hideLeftSide.setChecked(true);
647 if (Global.isWindowVisible("noteInformation"))
648 toggleNoteInformation();
649 quotaBar.setVisible(Global.isWindowVisible("quota"));
650 if (!quotaBar.isVisible())
651 menuBar.hideQuota.setChecked(false);
652 searchField.setVisible(Global.isWindowVisible("searchField"));
653 if (!searchField.isVisible())
654 menuBar.hideSearch.setChecked(false);
656 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
661 find = new FindDialog();
662 find.getOkButton().clicked.connect(this, "doFindText()");
664 // Setup the tray icon menu bar
665 trayShowAction = new QAction(tr("Show/Hide"), this);
666 trayExitAction = new QAction(tr("Exit"), this);
667 trayAddNoteAction = new QAction(tr("Add Note"), this);
669 trayExitAction.triggered.connect(this, "closeNeverNote()");
670 trayAddNoteAction.triggered.connect(this, "addNote()");
671 trayShowAction.triggered.connect(this, "trayToggleVisible()");
673 trayMenu = new QMenu(this);
674 trayMenu.addAction(trayAddNoteAction);
675 trayMenu.addAction(trayShowAction);
676 trayMenu.addAction(trayExitAction);
679 trayIcon = new QSystemTrayIcon(this);
680 trayIcon.setToolTip(tr("NixNote"));
681 trayIcon.setContextMenu(trayMenu);
682 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
685 currentNoteGuid = Global.getLastViewedNoteGuid();
686 historyGuids = new ArrayList<String>();
690 if (!currentNoteGuid.trim().equals("")) {
691 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
694 noteIndexUpdated(true);
696 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
697 if (menuBar.showEditorBar.isChecked())
698 showEditorButtons(browserWindow);
699 tagIndexUpdated(true);
700 savedSearchIndexUpdated();
701 notebookIndexUpdated();
703 setupSyncSignalListeners();
704 setupBrowserSignalListeners();
705 setupIndexListeners();
708 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
709 tagTree.showAllTags(true);
711 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
712 setWindowIcon(appIcon);
713 trayIcon.setIcon(appIcon);
714 if (Global.showTrayIcon())
719 scrollToGuid(currentNoteGuid);
720 if (Global.automaticLogin()) {
722 if (Global.isConnected)
725 setupFolderImports();
728 restoreWindowState(true);
730 if (Global.mimicEvernoteInterface) {
731 notebookTree.selectGuid("");
734 threadMonitorTimer = new QTimer();
735 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
736 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
738 historyGuids.add(currentNoteGuid);
741 menuBar.blockSignals(true);
742 menuBar.narrowListView.blockSignals(true);
743 menuBar.wideListView.blockSignals(true);
744 if (Global.getListView() == Global.View_List_Narrow) {
745 menuBar.narrowListView.setChecked(true);
748 menuBar.wideListView.setChecked(true);
750 menuBar.blockSignals(false);
751 menuBar.narrowListView.blockSignals(false);
752 menuBar.wideListView.blockSignals(false);
754 if (Global.getListView() == Global.View_List_Wide) {
755 browserIndexSplitter.addWidget(noteTableView);
756 browserIndexSplitter.addWidget(browserWindow);
758 mainLeftRightSplitter.addWidget(noteTableView);
759 mainLeftRightSplitter.addWidget(browserWindow);
762 messageTimer = new QTimer();
763 messageTimer.timeout.connect(this, "clearMessage()");
764 messageTimer.setInterval(1000*15);
767 int sortCol = Global.getSortColumn();
768 int sortOrder = Global.getSortOrder();
769 noteTableView.proxyModel.blocked = true;
770 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
771 noteTableView.proxyModel.blocked = false;
772 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
774 // Set the startup notebook
775 String defaultNotebook = Global.getStartupNotebook();
776 if (!defaultNotebook.equals("AllNotebooks") && !defaultNotebook.equals("")) {
777 for (int k=0; k<listManager.getNotebookIndex().size(); k++) {
778 if (listManager.getNotebookIndex().get(k).isDefaultNotebook()) {
779 notebookTree.clearSelection();
780 notebookTree.selectGuid(listManager.getNotebookIndex().get(k).getGuid());
781 notebookTree.selectionSignal.emit();
786 if (Global.checkVersionUpgrade())
791 public static void main(String[] args) {
792 log.setLevel(Level.FATAL);
793 QApplication.initialize(args);
794 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
795 QSplashScreen splash = new QSplashScreen(pixmap);
798 DatabaseConnection dbConn;
801 initializeGlobalSettings(args);
803 showSplash = Global.isWindowVisible("SplashScreen");
807 dbConn = setupDatabaseConnection();
809 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
810 Global.getFileManager().purgeResDirectory(true);
812 } catch (InitializationException e) {
815 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
819 NeverNote application = new NeverNote(dbConn);
821 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
822 if (Global.startMinimized())
823 application.showMinimized();
825 if (Global.wasWindowMaximized())
826 application.showMaximized();
832 splash.finish(application);
834 System.out.println("Goodbye.");
839 * Open the internal database, or create if not present
841 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
843 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
844 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
846 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
847 File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
848 File fi = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
850 Global.setDatabaseUrl("");
852 Global.setResourceDatabaseUrl("");
854 Global.setIndexDatabaseUrl("");
856 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
857 boolean goodCheck = false;
859 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
861 if (!dialog.okPressed())
863 Global.cipherPassword = dialog.getPassword();
864 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
865 Global.getDatabaseUserPassword(), Global.cipherPassword);
868 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
869 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
870 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
874 // Encrypt the database upon shutdown
875 private void encryptOnShutdown() {
876 String dbPath= Global.getFileManager().getDbDirPath("");
879 Statement st = conn.getConnection().createStatement();
880 st.execute("shutdown");
881 st = conn.getResourceConnection().createStatement();
882 st.execute("shutdown");
883 st = conn.getIndexConnection().createStatement();
884 st.execute("shutdown");
885 if (QMessageBox.question(this, tr("Are you sure"),
886 tr("Are you sure you wish to encrypt the database?"),
887 QMessageBox.StandardButton.Yes,
888 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
889 ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
890 ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
891 ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
892 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
893 Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
894 Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
896 QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
898 } catch (SQLException e) {
903 // Decrypt the database upon shutdown
904 private void decryptOnShutdown() {
905 String dbPath= Global.getFileManager().getDbDirPath("");
906 String dbName = "NeverNote";
908 Statement st = conn.getConnection().createStatement();
909 st.execute("shutdown");
910 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
911 encryptCipher = "AES";
913 encryptCipher = "XTEA";
914 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
915 "Are you sure you wish to decrypt the database?"),
916 QMessageBox.StandardButton.Yes,
917 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
919 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
920 Global.setDatabaseUrl("");
921 Global.setResourceDatabaseUrl("");
922 Global.setIndexDatabaseUrl("");
923 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
925 } catch (SQLException e) {
930 * Encrypt/Decrypt the local database
932 public void doDatabaseEncrypt() {
933 // The database is not currently encrypted
934 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
935 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
936 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
937 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
938 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
939 "Do you wish to proceed?"),
940 QMessageBox.StandardButton.Yes,
941 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
944 DBEncryptDialog dialog = new DBEncryptDialog();
946 if (dialog.okPressed()) {
947 Global.cipherPassword = dialog.getPassword();
948 encryptOnShutdown = true;
949 encryptCipher = dialog.getEncryptionMethod();
952 DBEncryptDialog dialog = new DBEncryptDialog();
953 dialog.setWindowTitle(tr("Database Decryption"));
954 dialog.hideEncryption();
956 if (dialog.okPressed()) {
957 if (!dialog.getPassword().equals(Global.cipherPassword)) {
958 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
961 decryptOnShutdown = true;
968 private static void initializeGlobalSettings(String[] args) throws InitializationException {
969 StartupConfig startupConfig = new StartupConfig();
971 for (String arg : args) {
972 String lower = arg.toLowerCase();
973 if (lower.startsWith("--name="))
974 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
975 if (lower.startsWith("--home="))
976 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
977 if (lower.startsWith("--disable-viewing"))
978 startupConfig.setDisableViewing(true);
980 Global.setup(startupConfig);
985 public void closeEvent(QCloseEvent event) {
986 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
991 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
994 if (currentNote!= null & browserWindow!=null) {
995 if (currentNote.getTitle() != null && browserWindow != null
996 && !currentNote.getTitle().equals(browserWindow.getTitle()))
997 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
1000 setMessage(tr("Beginning shutdown."));
1002 // Close down external windows
1003 Collection<ExternalBrowse> windows = externalWindows.values();
1004 Iterator<ExternalBrowse> iterator = windows.iterator();
1005 while (iterator.hasNext()) {
1006 ExternalBrowse browser = iterator.next();
1007 browser.windowClosing.disconnect();
1012 externalFileEditedSaver();
1013 if (Global.isConnected && Global.synchronizeOnClose()) {
1014 setMessage(tr("Performing synchronization before closing."));
1015 syncRunner.syncNeeded = true;
1016 syncRunner.addWork("SYNC");
1018 syncRunner.keepRunning = false;
1020 syncRunner.addWork("STOP");
1021 setMessage("Closing Program.");
1022 threadMonitorTimer.stop();
1024 thumbnailRunner.addWork("STOP");
1025 indexRunner.addWork("STOP");
1030 if (tempFiles != null)
1033 browserWindow.noteSignal.tagsChanged.disconnect();
1034 browserWindow.noteSignal.titleChanged.disconnect();
1035 browserWindow.noteSignal.noteChanged.disconnect();
1036 browserWindow.noteSignal.notebookChanged.disconnect();
1037 browserWindow.noteSignal.createdDateChanged.disconnect();
1038 browserWindow.noteSignal.alteredDateChanged.disconnect();
1039 syncRunner.searchSignal.listChanged.disconnect();
1040 syncRunner.tagSignal.listChanged.disconnect();
1041 syncRunner.notebookSignal.listChanged.disconnect();
1042 syncRunner.noteIndexSignal.listChanged.disconnect();
1045 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1046 saveNoteColumnPositions();
1047 saveNoteIndexWidth();
1049 int width = notebookTree.columnWidth(0);
1050 Global.setColumnWidth("notebookTreeName", width);
1051 width = tagTree.columnWidth(0);
1052 Global.setColumnWidth("tagTreeName", width);
1054 Global.saveWindowMaximized(isMaximized());
1055 Global.saveCurrentNoteGuid(currentNoteGuid);
1057 int sortCol = noteTableView.proxyModel.sortColumn();
1058 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1059 Global.setSortColumn(sortCol);
1060 Global.setSortOrder(sortOrder);
1064 Global.keepRunning = false;
1066 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1067 if (indexRunner.thread().isAlive())
1068 indexRunner.thread().join(50);
1069 if (!indexRunner.thread().isAlive())
1070 logger.log(logger.MEDIUM, "Index thread has stopped");
1072 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1073 indexRunner.thread().interrupt();
1075 } catch (InterruptedException e1) {
1076 e1.printStackTrace();
1079 if (!syncRunner.thread().isAlive()) {
1080 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1081 if (syncRunner.thread().isAlive()) {
1082 System.out.println(tr("Synchronizing. Please be patient."));
1083 for(;syncRunner.thread().isAlive();) {
1086 } catch (InterruptedException e) {
1087 e.printStackTrace();
1091 logger.log(logger.MEDIUM, "Sync thread has stopped");
1094 if (encryptOnShutdown) {
1095 encryptOnShutdown();
1097 if (decryptOnShutdown) {
1098 decryptOnShutdown();
1101 Global.getFileManager().purgeResDirectory(false);
1102 } catch (InitializationException e) {
1103 System.out.println(tr("Empty res directory purge failed"));
1104 e.printStackTrace();
1106 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1109 @SuppressWarnings("unused")
1110 private void closeNeverNote() {
1114 public void setMessage(String s) {
1115 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1118 logger.log(logger.HIGH, "Message: " +s);
1119 statusBar.showMessage(s);
1123 messageTimer.stop();
1124 messageTimer.setSingleShot(true);
1125 messageTimer.start();
1128 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1131 private void clearMessage() {
1132 statusBar.clearMessage();
1136 private void waitCursor(boolean wait) {
1138 if (QApplication.overrideCursor() == null)
1139 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1142 while (QApplication.overrideCursor() != null)
1143 QApplication.restoreOverrideCursor();
1145 listManager.refreshCounters();
1148 private void setupIndexListeners() {
1149 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1150 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1151 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1152 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1154 private void setupSyncSignalListeners() {
1155 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1156 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1157 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1158 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1159 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1161 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1162 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1163 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1165 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1166 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1167 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1168 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1169 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1171 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1174 private void setupBrowserSignalListeners() {
1175 setupBrowserWindowListeners(browserWindow, true);
1178 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1179 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1180 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1181 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1182 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1183 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1184 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1185 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1186 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1187 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1188 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1189 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1190 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1191 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1192 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1193 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1194 browser.unblockApplication.connect(this, "unblockApplication()");
1195 if (master) browser.focusLost.connect(this, "saveNote()");
1196 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1197 browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1200 //**************************************************
1202 //**************************************************
1203 private void setupShortcut(QShortcut action, String text) {
1204 if (!Global.shortcutKeys.containsAction(text))
1206 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1209 //***************************************************************
1210 //***************************************************************
1211 //* Settings and look & feel
1212 //***************************************************************
1213 //***************************************************************
1214 @SuppressWarnings("unused")
1215 private void settings() {
1216 logger.log(logger.HIGH, "Entering NeverNote.settings");
1217 saveNoteColumnPositions();
1218 saveNoteIndexWidth();
1220 ConfigDialog settings = new ConfigDialog(this);
1221 String dateFormat = Global.getDateFormat();
1222 String timeFormat = Global.getTimeFormat();
1224 indexTime = 1000*Global.getIndexThreadSleepInterval();
1225 indexTimer.start(indexTime); // reset indexing timer
1228 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1229 indexRunner.indexNoteBody = Global.indexNoteBody();
1230 indexRunner.indexNoteTitle = Global.indexNoteTitle();
1231 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1232 indexRunner.indexImageRecognition = Global.indexImageRecognition();
1233 if (Global.showTrayIcon())
1238 if (menuBar.showEditorBar.isChecked())
1239 showEditorButtons(browserWindow);
1241 // Reset the save timer
1242 if (Global.getAutoSaveInterval() > 0)
1243 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1248 // Set special reloads
1249 if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1250 conn.executeSql("Delete from LinkedNotebook");
1251 conn.executeSql("delete from SharedNotebook");
1252 conn.executeSql("Delete from Notebook where linked=true");
1253 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1254 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1259 readOnlyCache.clear();
1260 inkNoteCache.clear();
1261 noteIndexUpdated(true);
1263 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1265 // Restore things to the way they were
1266 private void restoreWindowState(boolean mainWindow) {
1267 // We need to name things or this doesn't work.
1268 setObjectName("NeverNote");
1269 restoreState(Global.restoreState(objectName()));
1270 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1271 browserIndexSplitter.setObjectName("browserIndexSplitter");
1272 leftSplitter1.setObjectName("leftSplitter1");
1274 // Restore the actual positions.
1276 restoreGeometry(Global.restoreGeometry(objectName()));
1277 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1278 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1279 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1282 // Save window positions for the next start
1283 private void saveWindowState() {
1284 Global.saveGeometry(objectName(), saveGeometry());
1285 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1286 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1287 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1288 Global.saveState(objectName(), saveState());
1290 // Load the style sheet
1291 private void loadStyleSheet() {
1292 String styleSheetName = "default.qss";
1293 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1294 styleSheetName = "default-cleanlooks.qss";
1295 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1296 QFile file = new QFile(fileName);
1298 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1299 if (!file.exists()) {
1300 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1301 file = new QFile(fileName);
1303 file.open(OpenModeFlag.ReadOnly);
1304 String styleSheet = file.readAll().toString();
1306 setStyleSheet(styleSheet);
1308 // Save column positions for the next time
1309 private void saveNoteColumnPositions() {
1310 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1311 Global.setColumnPosition("noteTableCreationPosition", position);
1312 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1313 Global.setColumnPosition("noteTableTagPosition", position);
1314 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1315 Global.setColumnPosition("noteTableNotebookPosition", position);
1316 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1317 Global.setColumnPosition("noteTableChangedPosition", position);
1318 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1319 Global.setColumnPosition("noteTableAuthorPosition", position);
1320 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1321 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1322 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1323 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1324 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1325 Global.setColumnPosition("noteTableTitlePosition", position);
1326 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1327 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1328 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1329 Global.setColumnPosition("noteTableGuidPosition", position);
1330 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1331 Global.setColumnPosition("noteTableThumbnailPosition", position);
1332 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1333 Global.setColumnPosition("noteTablePinnedPosition", position);
1336 // Save column widths for the next time
1337 private void saveNoteIndexWidth() {
1339 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1340 Global.setColumnWidth("noteTableCreationPosition", width);
1341 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1342 Global.setColumnWidth("noteTableChangedPosition", width);
1343 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1344 Global.setColumnWidth("noteTableGuidPosition", width);
1345 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1346 Global.setColumnWidth("noteTableNotebookPosition", width);
1347 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1348 Global.setColumnWidth("noteTableTagPosition", width);
1349 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1350 Global.setColumnWidth("noteTableTitlePosition", width);
1351 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1352 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1353 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1354 Global.setColumnWidth("noteTableAuthorPosition", width);
1355 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1356 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1357 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1358 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1359 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1360 Global.setColumnWidth("noteTableThumbnailPosition", width);
1361 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1362 Global.setColumnWidth("noteTableGuidPosition", width);
1363 width = noteTableView.getColumnWidth(Global.noteTablePinnedPosition);
1364 Global.setColumnWidth("noteTablePinnedPosition", width);
1367 @SuppressWarnings("unused")
1368 private void toggleSearchWindow() {
1369 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1370 searchLayout.toggleSearchField();
1371 menuBar.hideSearch.setChecked(searchField.isVisible());
1372 Global.saveWindowVisible("searchField", searchField.isVisible());
1373 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1375 @SuppressWarnings("unused")
1376 private void toggleQuotaWindow() {
1377 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1378 searchLayout.toggleQuotaBar();
1379 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1380 Global.saveWindowVisible("quota", quotaBar.isVisible());
1381 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1383 @SuppressWarnings("unused")
1384 private void toggleZoomWindow() {
1385 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1386 searchLayout.toggleZoom();
1387 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1388 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1389 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1394 //***************************************************************
1395 //***************************************************************
1396 //** These functions deal with Notebook menu items
1397 //***************************************************************
1398 //***************************************************************
1399 // Setup the tree containing the user's notebooks.
1400 private void initializeNotebookTree() {
1401 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1402 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1403 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1404 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1405 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1407 // Listener when a notebook is selected
1408 private void notebookTreeSelection() {
1409 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1410 noteTableView.proxyModel.blocked = true;
1413 clearAttributeFilter();
1414 clearSavedSearchFilter();
1415 if (Global.mimicEvernoteInterface) {
1417 searchField.clear();
1419 menuBar.noteRestoreAction.setVisible(false);
1420 menuBar.notebookEditAction.setEnabled(true);
1421 menuBar.notebookDeleteAction.setEnabled(true);
1422 menuBar.notebookPublishAction.setEnabled(true);
1423 menuBar.notebookShareAction.setEnabled(true);
1424 menuBar.notebookIconAction.setEnabled(true);
1425 menuBar.notebookStackAction.setEnabled(true);
1426 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1427 selectedNotebookGUIDs.clear();
1429 String stackName = "";
1430 if (selections.size() > 0) {
1431 guid = (selections.get(0).text(2));
1432 stackName = selections.get(0).text(0);
1434 if (!Global.mimicEvernoteInterface) {
1435 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1436 if (selections.size()==0) {
1437 selectedNotebookGUIDs.clear();
1438 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1439 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1441 menuBar.notebookEditAction.setEnabled(false);
1442 menuBar.notebookDeleteAction.setEnabled(false);
1443 menuBar.notebookStackAction.setEnabled(false);
1444 menuBar.notebookIconAction.setEnabled(false);
1447 if (!guid.equals("") && !guid.equals("STACK")) {
1448 selectedNotebookGUIDs.add(guid);
1449 menuBar.notebookIconAction.setEnabled(true);
1451 menuBar.notebookIconAction.setEnabled(true);
1452 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1453 Notebook book = listManager.getNotebookIndex().get(j);
1454 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1455 selectedNotebookGUIDs.add(book.getGuid());
1458 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1459 listManager.loadNotesIndex();
1460 noteIndexUpdated(false);
1461 refreshEvernoteNote(true);
1462 listManager.refreshCounters = true;
1463 listManager.refreshCounters();
1464 if (selectedNotebookGUIDs.size() == 1) {
1465 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1466 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1468 noteTableView.proxyModel.blocked = true;
1470 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1472 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1475 noteTableView.proxyModel.blocked = false;
1476 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1479 private void clearNotebookFilter() {
1480 notebookTree.blockSignals(true);
1481 notebookTree.clearSelection();
1482 menuBar.noteRestoreAction.setVisible(false);
1483 menuBar.notebookEditAction.setEnabled(false);
1484 menuBar.notebookDeleteAction.setEnabled(false);
1485 selectedNotebookGUIDs.clear();
1486 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1487 notebookTree.blockSignals(false);
1489 // Triggered when the notebook DB has been updated
1490 private void notebookIndexUpdated() {
1491 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1493 // Get the possible icons
1494 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1495 notebookTree.setIcons(icons);
1497 if (selectedNotebookGUIDs == null)
1498 selectedNotebookGUIDs = new ArrayList<String>();
1499 List<Notebook> books = conn.getNotebookTable().getAll();
1500 for (int i=books.size()-1; i>=0; i--) {
1501 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1502 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1504 j=listManager.getArchiveNotebookIndex().size();
1510 listManager.countNotebookResults(listManager.getNoteIndex());
1511 notebookTree.blockSignals(true);
1512 notebookTree.load(books, listManager.getLocalNotebooks());
1513 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1514 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1516 selectedNotebookGUIDs.remove(i);
1518 listManager.refreshCounters = true;
1519 listManager.refreshCounters();
1520 notebookTree.blockSignals(false);
1522 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1524 // Show/Hide note information
1525 @SuppressWarnings("unused")
1526 private void toggleNotebookWindow() {
1527 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1528 searchLayout.toggleNotebook();
1529 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1530 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1531 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1533 // Add a new notebook
1534 @SuppressWarnings("unused")
1535 private void addNotebook() {
1536 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1537 NotebookEdit edit = new NotebookEdit();
1538 edit.setNotebooks(listManager.getNotebookIndex());
1541 if (!edit.okPressed())
1544 Calendar currentTime = new GregorianCalendar();
1545 Long l = new Long(currentTime.getTimeInMillis());
1546 String randint = new String(Long.toString(l));
1548 Notebook newBook = new Notebook();
1549 newBook.setUpdateSequenceNum(0);
1550 newBook.setGuid(randint);
1551 newBook.setName(edit.getNotebook());
1552 newBook.setServiceCreated(new Date().getTime());
1553 newBook.setServiceUpdated(new Date().getTime());
1554 newBook.setDefaultNotebook(false);
1555 newBook.setPublished(false);
1557 listManager.getNotebookIndex().add(newBook);
1559 listManager.getLocalNotebooks().add(newBook.getGuid());
1560 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1561 notebookIndexUpdated();
1562 listManager.countNotebookResults(listManager.getNoteIndex());
1563 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1564 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1566 // Edit an existing notebook
1567 @SuppressWarnings("unused")
1568 private void stackNotebook() {
1569 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1570 StackNotebook edit = new StackNotebook();
1572 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1573 QTreeWidgetItem currentSelection;
1574 for (int i=0; i<selections.size(); i++) {
1575 currentSelection = selections.get(0);
1576 String guid = currentSelection.text(2);
1577 if (guid.equalsIgnoreCase("")) {
1578 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1581 if (guid.equalsIgnoreCase("STACK")) {
1582 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1587 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1592 if (!edit.okPressed())
1595 String stack = edit.getStackName();
1597 for (int i=0; i<selections.size(); i++) {
1598 currentSelection = selections.get(i);
1599 String guid = currentSelection.text(2);
1600 listManager.updateNotebookStack(guid, stack);
1602 notebookIndexUpdated();
1603 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1605 // Edit an existing notebook
1606 @SuppressWarnings("unused")
1607 private void editNotebook() {
1608 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1609 NotebookEdit edit = new NotebookEdit();
1611 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1612 QTreeWidgetItem currentSelection;
1613 currentSelection = selections.get(0);
1614 edit.setNotebook(currentSelection.text(0));
1616 String guid = currentSelection.text(2);
1617 if (!guid.equalsIgnoreCase("STACK")) {
1618 edit.setTitle(tr("Edit Notebook"));
1619 edit.setNotebooks(listManager.getNotebookIndex());
1620 edit.setLocalCheckboxEnabled(false);
1621 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1622 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1623 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1624 i=listManager.getNotebookIndex().size();
1628 edit.setTitle(tr("Edit Stack"));
1629 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1630 edit.hideLocalCheckbox();
1631 edit.hideDefaultCheckbox();
1636 if (!edit.okPressed())
1640 if (guid.equalsIgnoreCase("STACK")) {
1641 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1642 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1643 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1644 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1645 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1647 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1648 currentSelection.setText(0, edit.getNotebook());
1652 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1653 currentSelection.setText(0, edit.getNotebook());
1655 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1656 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1657 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1658 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1659 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1660 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1661 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1662 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1664 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1665 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1666 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1667 linkedNotebook.setShareName(edit.getNotebook());
1668 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1670 i=listManager.getNotebookIndex().size();
1674 // Build a list of non-closed notebooks
1675 List<Notebook> nbooks = new ArrayList<Notebook>();
1676 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1677 boolean found=false;
1678 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1679 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1683 nbooks.add(listManager.getNotebookIndex().get(i));
1687 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1688 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1689 browserWindow.setNotebookList(filteredBooks);
1690 Iterator<String> set = externalWindows.keySet().iterator();
1691 while(set.hasNext())
1692 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1693 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1695 // Publish a notebook
1696 @SuppressWarnings("unused")
1697 private void publishNotebook() {
1698 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1699 QTreeWidgetItem currentSelection;
1700 currentSelection = selections.get(0);
1701 String guid = currentSelection.text(2);
1703 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1708 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1709 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1710 n = listManager.getNotebookIndex().get(i);
1712 i = listManager.getNotebookIndex().size();
1718 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1721 if (!publish.okClicked())
1724 Publishing p = publish.getPublishing();
1725 boolean isPublished = !publish.isStopPressed();
1726 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1727 n.setPublished(isPublished);
1729 listManager.getNotebookIndex().set(position, n);
1730 notebookIndexUpdated();
1732 // Publish a notebook
1733 @SuppressWarnings("unused")
1734 private void shareNotebook() {
1735 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1736 QTreeWidgetItem currentSelection;
1737 currentSelection = selections.get(0);
1738 String guid = currentSelection.text(2);
1740 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1744 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1745 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1746 n = listManager.getNotebookIndex().get(i);
1747 i = listManager.getNotebookIndex().size();
1751 String authToken = null;
1752 if (syncRunner.isConnected)
1753 authToken = syncRunner.authToken;
1754 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1759 // Delete an existing notebook
1760 @SuppressWarnings("unused")
1761 private void deleteNotebook() {
1762 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1763 boolean stacksFound = false;
1764 boolean notebooksFound = false;
1765 boolean assigned = false;
1766 // Check if any notes have this notebook
1767 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1768 for (int i=0; i<selections.size(); i++) {
1769 QTreeWidgetItem currentSelection;
1770 currentSelection = selections.get(i);
1771 String guid = currentSelection.text(2);
1772 if (!guid.equalsIgnoreCase("STACK")) {
1773 notebooksFound = true;
1774 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1775 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1776 if (noteGuid.equals(guid)) {
1778 j=listManager.getNoteIndex().size();
1779 i=selections.size();
1787 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1788 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1792 if (conn.getNotebookTable().getAll().size() == 1) {
1793 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1797 // If all notebooks are clear, verify the delete
1798 String msg1 = new String(tr("Delete selected notebooks?"));
1799 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1800 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1801 " not deleted unless selected?"));
1803 if (stacksFound && notebooksFound)
1805 if (!stacksFound && notebooksFound)
1807 if (stacksFound && !notebooksFound)
1809 if (QMessageBox.question(this, tr("Confirmation"), msg,
1810 QMessageBox.StandardButton.Yes,
1811 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1815 // If confirmed, delete the notebook
1816 for (int i=selections.size()-1; i>=0; i--) {
1817 QTreeWidgetItem currentSelection;
1818 currentSelection = selections.get(i);
1819 String guid = currentSelection.text(2);
1820 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1821 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1822 listManager.renameStack(currentSelection.text(0), "");
1824 conn.getNotebookTable().expungeNotebook(guid, true);
1825 listManager.deleteNotebook(guid);
1829 notebookIndexUpdated();
1830 // notebookTreeSelection();
1831 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1832 // listManager.countNotebookResults(listManager.getNoteIndex());
1833 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1835 // A note's notebook has been updated
1836 @SuppressWarnings("unused")
1837 private void updateNoteNotebook(String guid, String notebookGuid) {
1839 // Update the list manager
1840 listManager.updateNoteNotebook(guid, notebookGuid);
1841 listManager.countNotebookResults(listManager.getNoteIndex());
1842 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1844 // Find the name of the notebook
1845 String notebookName = null;
1846 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1847 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1848 notebookName = listManager.getNotebookIndex().get(i).getName();
1853 // If we found the name, update the browser window
1854 if (notebookName != null) {
1855 updateListNoteNotebook(guid, notebookName);
1856 if (guid.equals(currentNoteGuid)) {
1857 int pos = browserWindow.notebookBox.findText(notebookName);
1859 browserWindow.notebookBox.setCurrentIndex(pos);
1863 // If we're dealing with the current note, then we need to be sure and update the notebook there
1864 if (guid.equals(currentNoteGuid)) {
1865 if (currentNote != null) {
1866 currentNote.setNotebookGuid(notebookGuid);
1870 // Open/close notebooks
1871 @SuppressWarnings("unused")
1872 private void closeNotebooks() {
1873 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1875 if (!na.okClicked())
1879 listManager.getArchiveNotebookIndex().clear();
1881 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1882 String text = na.getClosedBookList().takeItem(i).text();
1883 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1884 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1885 Notebook n = listManager.getNotebookIndex().get(j);
1886 conn.getNotebookTable().setArchived(n.getGuid(),true);
1887 listManager.getArchiveNotebookIndex().add(n);
1888 j=listManager.getNotebookIndex().size();
1893 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1894 String text = na.getOpenBookList().takeItem(i).text();
1895 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1896 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1897 Notebook n = listManager.getNotebookIndex().get(j);
1898 conn.getNotebookTable().setArchived(n.getGuid(),false);
1899 j=listManager.getNotebookIndex().size();
1903 notebookTreeSelection();
1904 listManager.loadNotesIndex();
1905 notebookIndexUpdated();
1906 noteIndexUpdated(false);
1907 reloadTagTree(true);
1908 // noteIndexUpdated(false);
1910 // Build a list of non-closed notebooks
1911 List<Notebook> nbooks = new ArrayList<Notebook>();
1912 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1913 boolean found=false;
1914 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1915 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1919 nbooks.add(listManager.getNotebookIndex().get(i));
1922 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1923 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1924 browserWindow.setNotebookList(filteredBooks);
1926 // Update any external windows
1927 Iterator<String> set = externalWindows.keySet().iterator();
1928 while(set.hasNext())
1929 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1933 // Change the notebook's icon
1934 @SuppressWarnings("unused")
1935 private void setNotebookIcon() {
1936 boolean stackSelected = false;
1937 boolean allNotebookSelected = false;
1939 QTreeWidgetItem currentSelection;
1940 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1941 if (selections.size() == 0)
1944 currentSelection = selections.get(0);
1945 String guid = currentSelection.text(2);
1946 if (guid.equalsIgnoreCase(""))
1947 allNotebookSelected = true;
1948 if (guid.equalsIgnoreCase("STACK"))
1949 stackSelected = true;
1951 QIcon currentIcon = currentSelection.icon(0);
1955 if (!stackSelected && !allNotebookSelected) {
1956 icon = conn.getNotebookTable().getIcon(guid);
1958 dialog = new SetIcon(currentIcon, saveLastPath);
1959 dialog.setUseDefaultIcon(true);
1961 dialog = new SetIcon(icon, saveLastPath);
1962 dialog.setUseDefaultIcon(false);
1965 if (stackSelected) {
1966 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1968 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1971 dialog = new SetIcon(currentIcon, saveLastPath);
1972 dialog.setUseDefaultIcon(true);
1974 dialog = new SetIcon(icon, saveLastPath);
1975 dialog.setUseDefaultIcon(false);
1979 if (dialog.okPressed()) {
1980 saveLastPath = dialog.getPath();
1982 QIcon newIcon = dialog.getIcon();
1983 if (stackSelected) {
1984 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1985 if (newIcon == null) {
1986 newIcon = new QIcon(iconPath+"books2.png");
1988 currentSelection.setIcon(0,newIcon);
1991 if (allNotebookSelected) {
1992 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1993 if (newIcon == null) {
1994 newIcon = new QIcon(iconPath+"notebook-green.png");
1996 currentSelection.setIcon(0,newIcon);
1999 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
2000 if (newIcon == null) {
2001 boolean isPublished = false;;
2002 boolean found = false;
2003 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
2004 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
2005 isPublished = listManager.getNotebookIndex().get(i).isPublished();
2009 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
2011 currentSelection.setIcon(0, newIcon);
2017 //***************************************************************
2018 //***************************************************************
2019 //** These functions deal with Tag menu items
2020 //***************************************************************
2021 //***************************************************************
2022 // Add a new notebook
2023 @SuppressWarnings("unused")
2024 private void addTag() {
2025 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2026 TagEdit edit = new TagEdit();
2027 edit.setTagList(listManager.getTagIndex());
2029 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2030 QTreeWidgetItem currentSelection = null;
2031 if (selections.size() > 0) {
2032 currentSelection = selections.get(0);
2033 edit.setParentTag(currentSelection.text(0));
2038 if (!edit.okPressed())
2041 Calendar currentTime = new GregorianCalendar();
2042 Long l = new Long(currentTime.getTimeInMillis());
2043 String randint = new String(Long.toString(l));
2045 Tag newTag = new Tag();
2046 newTag.setUpdateSequenceNum(0);
2047 newTag.setGuid(randint);
2048 newTag.setName(edit.getTag());
2049 if (edit.getParentTag().isChecked()) {
2050 newTag.setParentGuid(currentSelection.text(2));
2051 newTag.setParentGuidIsSet(true);
2052 currentSelection.setExpanded(true);
2054 conn.getTagTable().addTag(newTag, true);
2055 listManager.getTagIndex().add(newTag);
2056 reloadTagTree(true);
2058 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2060 @SuppressWarnings("unused")
2061 private void reloadTagTree() {
2062 reloadTagTree(false);
2064 private void reloadTagTree(boolean reload) {
2065 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2066 tagIndexUpdated(reload);
2067 boolean filter = false;
2069 listManager.countTagResults(listManager.getNoteIndex());
2070 if (notebookTree.selectedItems().size() > 0
2071 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2073 if (tagTree.selectedItems().size() > 0)
2075 tagTree.showAllTags(!filter);
2076 tagIndexUpdated(false);
2077 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2079 // Edit an existing tag
2080 @SuppressWarnings("unused")
2081 private void editTag() {
2082 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2083 TagEdit edit = new TagEdit();
2084 edit.setTitle("Edit Tag");
2085 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2086 QTreeWidgetItem currentSelection;
2087 currentSelection = selections.get(0);
2088 edit.setTag(currentSelection.text(0));
2089 edit.setTagList(listManager.getTagIndex());
2092 if (!edit.okPressed())
2095 String guid = currentSelection.text(2);
2096 currentSelection.setText(0,edit.getTag());
2098 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2099 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2100 listManager.getTagIndex().get(i).setName(edit.getTag());
2101 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2102 updateListTagName(guid);
2103 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2104 browserWindow.setTag(getTagNamesForNote(currentNote));
2105 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2109 browserWindow.setTag(getTagNamesForNote(currentNote));
2110 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2112 // Delete an existing tag
2113 @SuppressWarnings("unused")
2114 private void deleteTag() {
2115 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2117 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2118 QMessageBox.StandardButton.Yes,
2119 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2123 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2124 for (int i=selections.size()-1; i>=0; i--) {
2125 QTreeWidgetItem currentSelection;
2126 currentSelection = selections.get(i);
2127 removeTagItem(currentSelection.text(2));
2129 tagIndexUpdated(true);
2131 listManager.countTagResults(listManager.getNoteIndex());
2132 // tagTree.updateCounts(listManager.getTagCounter());
2133 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2135 // Remove a tag tree item. Go recursively down & remove the children too
2136 private void removeTagItem(String guid) {
2137 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2138 String parent = listManager.getTagIndex().get(j).getParentGuid();
2139 if (parent != null && parent.equals(guid)) {
2140 //Remove this tag's children
2141 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2144 //Now, remove this tag
2145 removeListTagName(guid);
2146 conn.getTagTable().expungeTag(guid, true);
2147 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2148 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2149 listManager.getTagIndex().remove(a);
2154 // Setup the tree containing the user's tags
2155 private void initializeTagTree() {
2156 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2157 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2158 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2159 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2160 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2161 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2163 // Listener when a tag is selected
2164 private void tagTreeSelection() {
2165 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2168 clearAttributeFilter();
2169 clearSavedSearchFilter();
2171 menuBar.noteRestoreAction.setVisible(false);
2173 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2174 QTreeWidgetItem currentSelection;
2175 selectedTagGUIDs.clear();
2176 for (int i=0; i<selections.size(); i++) {
2177 currentSelection = selections.get(i);
2178 selectedTagGUIDs.add(currentSelection.text(2));
2180 if (selections.size() > 0) {
2181 menuBar.tagEditAction.setEnabled(true);
2182 menuBar.tagDeleteAction.setEnabled(true);
2183 menuBar.tagIconAction.setEnabled(true);
2186 menuBar.tagEditAction.setEnabled(false);
2187 menuBar.tagDeleteAction.setEnabled(false);
2188 menuBar.tagIconAction.setEnabled(true);
2190 if (selections.size() > 1)
2191 menuBar.tagMergeAction.setEnabled(true);
2193 menuBar.tagMergeAction.setEnabled(false);
2194 listManager.setSelectedTags(selectedTagGUIDs);
2195 listManager.loadNotesIndex();
2196 noteIndexUpdated(false);
2197 refreshEvernoteNote(true);
2198 listManager.refreshCounters = true;
2199 listManager.refreshCounters();
2200 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2202 // trigger the tag index to be refreshed
2203 @SuppressWarnings("unused")
2204 private void tagIndexUpdated() {
2205 tagIndexUpdated(true);
2207 private void tagIndexUpdated(boolean reload) {
2208 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2209 if (selectedTagGUIDs == null)
2210 selectedTagGUIDs = new ArrayList<String>();
2212 listManager.reloadTagIndex();
2214 tagTree.blockSignals(true);
2216 tagTree.setIcons(conn.getTagTable().getAllIcons());
2217 tagTree.load(listManager.getTagIndex());
2220 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2221 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2223 selectedTagGUIDs.remove(i);
2225 tagTree.blockSignals(false);
2227 browserWindow.setTag(getTagNamesForNote(currentNote));
2228 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2230 // Show/Hide note information
2231 @SuppressWarnings("unused")
2232 private void toggleTagWindow() {
2233 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2234 if (tagTree.isVisible())
2238 menuBar.hideTags.setChecked(tagTree.isVisible());
2239 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2240 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2242 // A note's tags have been updated
2243 @SuppressWarnings("unused")
2244 private void updateNoteTags(String guid, List<String> tags) {
2245 // Save any new tags. We'll need them later.
2246 List<String> newTags = new ArrayList<String>();
2247 for (int i=0; i<tags.size(); i++) {
2248 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2249 newTags.add(tags.get(i));
2252 listManager.saveNoteTags(guid, tags);
2253 listManager.countTagResults(listManager.getNoteIndex());
2254 StringBuffer names = new StringBuffer("");
2255 for (int i=0; i<tags.size(); i++) {
2256 names = names.append(tags.get(i));
2257 if (i<tags.size()-1) {
2258 names.append(Global.tagDelimeter + " ");
2261 browserWindow.setTag(names.toString());
2264 // Now, we need to add any new tags to the tag tree
2265 for (int i=0; i<newTags.size(); i++)
2266 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2268 // Get a string containing all tag names for a note
2269 private String getTagNamesForNote(Note n) {
2270 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2271 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2273 StringBuffer buffer = new StringBuffer(100);
2274 Vector<String> v = new Vector<String>();
2275 List<String> guids = n.getTagGuids();
2280 for (int i=0; i<guids.size(); i++) {
2281 v.add(listManager.getTagNameByGuid(guids.get(i)));
2283 Comparator<String> comparator = Collections.reverseOrder();
2284 Collections.sort(v,comparator);
2285 Collections.reverse(v);
2287 for (int i = 0; i<v.size(); i++) {
2289 buffer.append(", ");
2290 buffer.append(v.get(i));
2293 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2294 return buffer.toString();
2296 // Tags were added via dropping notes from the note list
2297 @SuppressWarnings("unused")
2298 private void tagsAdded(String noteGuid, String tagGuid) {
2299 String tagName = null;
2300 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2301 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2302 tagName = listManager.getTagIndex().get(i).getName();
2303 i=listManager.getTagIndex().size();
2306 if (tagName == null)
2309 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2310 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2311 List<String> tagNames = new ArrayList<String>();
2312 tagNames.add(new String(tagName));
2313 Note n = listManager.getMasterNoteIndex().get(i);
2314 for (int j=0; j<n.getTagNames().size(); j++) {
2315 tagNames.add(new String(n.getTagNames().get(j)));
2317 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2318 if (n.getGuid().equals(currentNoteGuid)) {
2319 Collections.sort(tagNames);
2320 String display = "";
2321 for (int j=0; j<tagNames.size(); j++) {
2322 display = display+tagNames.get(j);
2323 if (j+2<tagNames.size())
2324 display = display+Global.tagDelimeter+" ";
2326 browserWindow.setTag(display);
2328 i=listManager.getMasterNoteIndex().size();
2333 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2335 private void clearTagFilter() {
2336 tagTree.blockSignals(true);
2337 tagTree.clearSelection();
2338 menuBar.noteRestoreAction.setVisible(false);
2339 menuBar.tagEditAction.setEnabled(false);
2340 menuBar.tagMergeAction.setEnabled(false);
2341 menuBar.tagDeleteAction.setEnabled(false);
2342 menuBar.tagIconAction.setEnabled(false);
2343 selectedTagGUIDs.clear();
2344 listManager.setSelectedTags(selectedTagGUIDs);
2345 tagTree.blockSignals(false);
2347 // Change the icon for a tag
2348 @SuppressWarnings("unused")
2349 private void setTagIcon() {
2350 QTreeWidgetItem currentSelection;
2351 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2352 if (selections.size() == 0)
2355 currentSelection = selections.get(0);
2356 String guid = currentSelection.text(2);
2358 QIcon currentIcon = currentSelection.icon(0);
2359 QIcon icon = conn.getTagTable().getIcon(guid);
2362 dialog = new SetIcon(currentIcon, saveLastPath);
2363 dialog.setUseDefaultIcon(true);
2365 dialog = new SetIcon(icon, saveLastPath);
2366 dialog.setUseDefaultIcon(false);
2369 if (dialog.okPressed()) {
2370 saveLastPath = dialog.getPath();
2371 QIcon newIcon = dialog.getIcon();
2372 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2373 if (newIcon == null)
2374 newIcon = new QIcon(iconPath+"tag.png");
2375 currentSelection.setIcon(0, newIcon);
2380 @SuppressWarnings("unused")
2381 private void mergeTags() {
2382 List<Tag> tags = new ArrayList<Tag>();
2383 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2384 for (int i=0; i<selections.size(); i++) {
2385 Tag record = new Tag();
2386 record.setGuid(selections.get(i).text(2));
2387 record.setName(selections.get(i).text(0));
2391 TagMerge mergeDialog = new TagMerge(tags);
2393 if (!mergeDialog.okClicked())
2395 String newGuid = mergeDialog.getNewTagGuid();
2397 for (int i=0; i<tags.size(); i++) {
2398 if (!tags.get(i).getGuid().equals(newGuid)) {
2399 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2400 for (int j=0; j<noteGuids.size(); j++) {
2401 String noteGuid = noteGuids.get(j);
2402 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2403 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2404 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2408 listManager.reloadIndexes();
2411 //***************************************************************
2412 //***************************************************************
2413 //** These functions deal with Saved Search menu items
2414 //***************************************************************
2415 //***************************************************************
2416 // Add a new notebook
2417 @SuppressWarnings("unused")
2418 private void addSavedSearch() {
2419 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2420 SavedSearchEdit edit = new SavedSearchEdit();
2421 edit.setSearchList(listManager.getSavedSearchIndex());
2424 if (!edit.okPressed())
2427 Calendar currentTime = new GregorianCalendar();
2428 Long l = new Long(currentTime.getTimeInMillis());
2429 String randint = new String(Long.toString(l));
2431 SavedSearch search = new SavedSearch();
2432 search.setUpdateSequenceNum(0);
2433 search.setGuid(randint);
2434 search.setName(edit.getName());
2435 search.setQuery(edit.getQuery());
2436 search.setFormat(QueryFormat.USER);
2437 listManager.getSavedSearchIndex().add(search);
2438 conn.getSavedSearchTable().addSavedSearch(search, true);
2439 savedSearchIndexUpdated();
2440 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2442 // Edit an existing tag
2443 @SuppressWarnings("unused")
2444 private void editSavedSearch() {
2445 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2446 SavedSearchEdit edit = new SavedSearchEdit();
2447 edit.setTitle(tr("Edit Search"));
2448 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2449 QTreeWidgetItem currentSelection;
2450 currentSelection = selections.get(0);
2451 String guid = currentSelection.text(1);
2452 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2453 edit.setName(currentSelection.text(0));
2454 edit.setQuery(s.getQuery());
2455 edit.setSearchList(listManager.getSavedSearchIndex());
2458 if (!edit.okPressed())
2461 List<SavedSearch> list = listManager.getSavedSearchIndex();
2462 SavedSearch search = null;
2463 boolean found = false;
2464 for (int i=0; i<list.size(); i++) {
2465 search = list.get(i);
2466 if (search.getGuid().equals(guid)) {
2473 search.setName(edit.getName());
2474 search.setQuery(edit.getQuery());
2475 conn.getSavedSearchTable().updateSavedSearch(search, true);
2476 savedSearchIndexUpdated();
2477 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2479 // Delete an existing tag
2480 @SuppressWarnings("unused")
2481 private void deleteSavedSearch() {
2482 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2484 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2485 QMessageBox.StandardButton.Yes,
2486 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2490 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2491 for (int i=selections.size()-1; i>=0; i--) {
2492 QTreeWidgetItem currentSelection;
2493 currentSelection = selections.get(i);
2494 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2495 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2496 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2497 listManager.getSavedSearchIndex().remove(j);
2498 j=listManager.getSavedSearchIndex().size()+1;
2501 selections.remove(i);
2503 savedSearchIndexUpdated();
2504 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2506 // Setup the tree containing the user's tags
2507 private void initializeSavedSearchTree() {
2508 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2509 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2510 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2512 // Listener when a tag is selected
2513 @SuppressWarnings("unused")
2514 private void savedSearchTreeSelection() {
2515 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2517 clearNotebookFilter();
2520 clearAttributeFilter();
2522 String currentGuid = selectedSavedSearchGUID;
2523 menuBar.savedSearchEditAction.setEnabled(true);
2524 menuBar.savedSearchDeleteAction.setEnabled(true);
2525 menuBar.savedSearchIconAction.setEnabled(true);
2526 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2527 QTreeWidgetItem currentSelection;
2528 selectedSavedSearchGUID = "";
2529 for (int i=0; i<selections.size(); i++) {
2530 currentSelection = selections.get(i);
2531 if (currentSelection.text(1).equals(currentGuid)) {
2532 currentSelection.setSelected(false);
2534 selectedSavedSearchGUID = currentSelection.text(1);
2536 // i = selections.size() +1;
2539 // There is the potential for no notebooks to be selected if this
2540 // happens then we make it look like all notebooks were selecetd.
2541 // If that happens, just select the "all notebooks"
2542 if (selections.size()==0) {
2543 clearSavedSearchFilter();
2545 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2547 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2549 private void clearSavedSearchFilter() {
2550 menuBar.savedSearchEditAction.setEnabled(false);
2551 menuBar.savedSearchDeleteAction.setEnabled(false);
2552 menuBar.savedSearchIconAction.setEnabled(false);
2553 savedSearchTree.blockSignals(true);
2554 savedSearchTree.clearSelection();
2555 savedSearchTree.blockSignals(false);
2556 selectedSavedSearchGUID = "";
2557 searchField.setEditText("");
2558 searchPerformed = false;
2559 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2561 // trigger the tag index to be refreshed
2562 private void savedSearchIndexUpdated() {
2563 if (selectedSavedSearchGUID == null)
2564 selectedSavedSearchGUID = new String();
2565 savedSearchTree.blockSignals(true);
2566 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2567 savedSearchTree.load(listManager.getSavedSearchIndex());
2568 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2569 savedSearchTree.blockSignals(false);
2571 // trigger when the saved search selection changes
2572 @SuppressWarnings("unused")
2573 private void updateSavedSearchSelection() {
2574 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2576 menuBar.savedSearchEditAction.setEnabled(true);
2577 menuBar.savedSearchDeleteAction.setEnabled(true);
2578 menuBar.savedSearchIconAction.setEnabled(true);
2579 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2581 if (selections.size() > 0) {
2582 menuBar.savedSearchEditAction.setEnabled(true);
2583 menuBar.savedSearchDeleteAction.setEnabled(true);
2584 menuBar.savedSearchIconAction.setEnabled(true);
2585 selectedSavedSearchGUID = selections.get(0).text(1);
2586 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2587 searchField.setEditText(s.getQuery());
2589 menuBar.savedSearchEditAction.setEnabled(false);
2590 menuBar.savedSearchDeleteAction.setEnabled(false);
2591 menuBar.savedSearchIconAction.setEnabled(false);
2592 selectedSavedSearchGUID = "";
2593 searchField.setEditText("");
2595 searchFieldChanged();
2597 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2601 // Show/Hide note information
2602 @SuppressWarnings("unused")
2603 private void toggleSavedSearchWindow() {
2604 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2605 if (savedSearchTree.isVisible())
2606 savedSearchTree.hide();
2608 savedSearchTree.show();
2609 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2611 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2612 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2614 // Change the icon for a saved search
2615 @SuppressWarnings("unused")
2616 private void setSavedSearchIcon() {
2617 QTreeWidgetItem currentSelection;
2618 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2619 if (selections.size() == 0)
2622 currentSelection = selections.get(0);
2623 String guid = currentSelection.text(1);
2625 QIcon currentIcon = currentSelection.icon(0);
2626 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2629 dialog = new SetIcon(currentIcon, saveLastPath);
2630 dialog.setUseDefaultIcon(true);
2632 dialog = new SetIcon(icon, saveLastPath);
2633 dialog.setUseDefaultIcon(false);
2636 if (dialog.okPressed()) {
2637 saveLastPath = dialog.getPath();
2638 QIcon newIcon = dialog.getIcon();
2639 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2640 if (newIcon == null)
2641 newIcon = new QIcon(iconPath+"search.png");
2642 currentSelection.setIcon(0, newIcon);
2650 //***************************************************************
2651 //***************************************************************
2652 //** These functions deal with Help menu & tool menu items
2653 //***************************************************************
2654 //***************************************************************
2655 // Show database status
2656 @SuppressWarnings("unused")
2657 private void databaseStatus() {
2659 indexRunner.interrupt = true;
2660 int dirty = conn.getNoteTable().getDirtyCount();
2661 int unindexed = conn.getNoteTable().getUnindexedCount();
2662 DatabaseStatus status = new DatabaseStatus();
2663 status.setUnsynchronized(dirty);
2664 status.setUnindexed(unindexed);
2665 status.setNoteCount(conn.getNoteTable().getNoteCount());
2666 status.setNotebookCount(listManager.getNotebookIndex().size());
2667 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2668 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2669 status.setTagCount(listManager.getTagIndex().size());
2670 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2671 status.setWordCount(conn.getWordsTable().getWordCount());
2675 // Compact the database
2676 @SuppressWarnings("unused")
2677 private void compactDatabase() {
2678 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2679 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2680 "but please be aware that depending upon the size of your database this can be time consuming " +
2681 "and NixNote will be unresponsive until it is complete. Do you wish to continue?"),
2682 QMessageBox.StandardButton.Yes,
2683 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2686 setMessage("Compacting database.");
2688 listManager.compactDatabase();
2690 setMessage("Database compact is complete.");
2691 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2693 @SuppressWarnings("unused")
2694 private void accountInformation() {
2695 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2696 AccountDialog dialog = new AccountDialog();
2698 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2700 @SuppressWarnings("unused")
2701 private void releaseNotes() {
2702 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2703 QDialog dialog = new QDialog(this);
2704 QHBoxLayout layout = new QHBoxLayout();
2705 QTextEdit textBox = new QTextEdit();
2706 layout.addWidget(textBox);
2707 textBox.setReadOnly(true);
2708 QFile file = new QFile(Global.getFileManager().getProgramDirPath("release.txt"));
2709 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2710 QIODevice.OpenModeFlag.Text)))
2712 textBox.setText(file.readAll().toString());
2714 dialog.setWindowTitle(tr("Release Notes"));
2715 dialog.setLayout(layout);
2717 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2719 // Called when user picks Log from the help menu
2720 @SuppressWarnings("unused")
2721 private void logger() {
2722 logger.log(logger.HIGH, "Entering NeverNote.logger");
2723 LogFileDialog dialog = new LogFileDialog(emitLog);
2725 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2727 // Menu option "help/about" was selected
2728 @SuppressWarnings("unused")
2729 private void about() {
2730 logger.log(logger.HIGH, "Entering NeverNote.about");
2731 QMessageBox.about(this,
2732 tr("About NixNote"),
2733 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2736 +"Open Source Evernote Client.<br><br>"
2737 +"Licensed under GPL v2. <br><hr><br>"
2738 +"</center>Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2739 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2740 +"PDFRenderer is licened under the LGPL<br>"
2741 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2742 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2743 +"Jazzy is licened under the LGPL<br>"
2744 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2745 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2746 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2747 logger.log(logger.HIGH, "Leaving NeverNote.about");
2749 // Hide the entire left hand side
2750 @SuppressWarnings("unused")
2751 private void toggleLeftSide() {
2754 hidden = !menuBar.hideLeftSide.isChecked();
2755 menuBar.hideLeftSide.setChecked(!hidden);
2758 leftSplitter1.setHidden(true);
2760 leftSplitter1.setHidden(false);
2762 Global.saveWindowVisible("leftPanel", hidden);
2765 public void checkForUpdates() {
2766 // Send off thread to check for a new version
2767 versionChecker = new QNetworkAccessManager(this);
2768 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2769 QNetworkRequest request = new QNetworkRequest();
2770 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2771 versionChecker.get(request);
2773 @SuppressWarnings("unused")
2774 private void upgradeFileRead(QNetworkReply reply) {
2775 if (!reply.isReadable())
2778 String winVersion = Global.version;
2779 String osxVersion = Global.version;
2780 String linuxVersion = Global.version;
2781 String linux64Version = Global.version;
2782 String version = Global.version;
2784 // Determine the versions available
2785 QByteArray data = reply.readLine();
2786 while (data != null && !reply.atEnd()) {
2787 String line = data.toString();
2789 if (line.contains(":"))
2790 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2793 if (line.toLowerCase().contains("windows"))
2794 winVersion = lineVersion;
2795 else if (line.toLowerCase().contains("os-x"))
2796 osxVersion = lineVersion;
2797 else if (line.toLowerCase().contains("linux amd64"))
2798 linux64Version = lineVersion;
2799 else if (line.toLowerCase().contains("linux i386"))
2800 linuxVersion = lineVersion;
2801 else if (line.toLowerCase().contains("default"))
2802 version = lineVersion;
2804 // Read the next line
2805 data = reply.readLine();
2808 // Now we need to determine what system we are on.
2809 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2810 version = winVersion;
2811 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2812 version = osxVersion;
2813 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2814 if (System.getProperty("os.arch").contains("amd64") ||
2815 System.getProperty("os.arch").contains("x86_64"))
2816 version = linux64Version;
2818 version = linuxVersion;
2822 for (String validVersion : Global.validVersions) {
2823 if (version.equals(validVersion))
2827 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2829 if (dialog.remindMe())
2830 Global.setCheckVersionUpgrade(true);
2832 Global.setCheckVersionUpgrade(false);
2836 //***************************************************************
2837 //***************************************************************
2838 //** These functions deal with the Toolbar
2839 //***************************************************************
2840 //***************************************************************
2841 @SuppressWarnings("unused")
2842 private void focusSearch() {
2843 searchField.setFocus();
2846 // Text in the search bar has been cleared
2847 private void searchFieldCleared() {
2850 // This is done because we want to force a reload of
2851 // images. Some images we may want to highlight the text.
2852 readOnlyCache.clear();
2853 inkNoteCache.clear();
2855 QWebSettings.setMaximumPagesInCache(0);
2856 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2858 searchField.setEditText("");
2859 saveNoteColumnPositions();
2860 saveNoteIndexWidth();
2861 noteIndexUpdated(true);
2862 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2863 currentNote = listManager.getNoteIndex().get(0);
2864 currentNoteGuid = currentNote.getGuid();
2866 refreshEvernoteNote(true);
2867 if (currentNote != null)
2868 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2870 // text in the search bar changed. We only use this to tell if it was cleared,
2871 // otherwise we trigger off searchFieldChanged.
2872 @SuppressWarnings("unused")
2873 private void searchFieldTextChanged(String text) {
2874 QWebSettings.setMaximumPagesInCache(0);
2875 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2877 if (text.trim().equals("")) {
2878 searchFieldCleared();
2879 if (searchPerformed) {
2881 // This is done because we want to force a reload of
2882 // images. Some images we may want to highlight the text.
2884 readOnlyCache.clear();
2885 inkNoteCache.clear();
2887 listManager.setEnSearch("");
2888 listManager.loadNotesIndex();
2889 refreshEvernoteNote(true);
2890 noteIndexUpdated(false);
2891 refreshEvernoteNote(true);
2893 searchPerformed = false;
2896 // Text in the toolbar has changed
2897 private void searchFieldChanged() {
2898 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2900 readOnlyCache.clear();
2901 inkNoteCache.clear();
2902 saveNoteColumnPositions();
2903 saveNoteIndexWidth();
2904 String text = searchField.currentText();
2905 listManager.setEnSearch(text.trim());
2906 listManager.loadNotesIndex();
2907 noteIndexUpdated(false);
2909 refreshEvernoteNote(true);
2910 searchPerformed = true;
2912 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2915 // Build the window tool bar
2916 private void setupToolBar() {
2917 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2918 toolBar = addToolBar(tr("Tool Bar"));
2919 toolBar.setObjectName("toolBar");
2920 menuBar.setupToolBarVisible();
2921 if (!Global.isWindowVisible("toolBar"))
2922 toolBar.setVisible(false);
2924 toolBar.setVisible(true);
2926 // toolBar.addWidget(menuBar);
2927 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2928 // toolBar.addSeparator();
2929 prevButton = toolBar.addAction(tr("Previous"));
2930 QIcon prevIcon = new QIcon(iconPath+"back.png");
2931 prevButton.setIcon(prevIcon);
2932 prevButton.triggered.connect(this, "previousViewedAction()");
2933 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2935 nextButton = toolBar.addAction(tr("Next"));
2936 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2937 nextButton.setIcon(nextIcon);
2938 nextButton.triggered.connect(this, "nextViewedAction()");
2939 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2941 upButton = toolBar.addAction(tr("Up"));
2942 QIcon upIcon = new QIcon(iconPath+"up.png");
2943 upButton.setIcon(upIcon);
2944 upButton.triggered.connect(this, "upAction()");
2945 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2948 downButton = toolBar.addAction(tr("Down"));
2949 QIcon downIcon = new QIcon(iconPath+"down.png");
2950 downButton.setIcon(downIcon);
2951 downButton.triggered.connect(this, "downAction()");
2952 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2954 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2955 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2956 synchronizeIconAngle = 0;
2957 synchronizeButton.triggered.connect(this, "evernoteSync()");
2958 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2960 printButton = toolBar.addAction(tr("Print"));
2961 QIcon printIcon = new QIcon(iconPath+"print.png");
2962 printButton.setIcon(printIcon);
2963 printButton.triggered.connect(this, "printNote()");
2964 togglePrintButton(Global.isToolbarButtonVisible("print"));
2966 tagButton = toolBar.addAction(tr("Tag"));
2967 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2968 tagButton.setIcon(tagIcon);
2969 tagButton.triggered.connect(browserWindow, "modifyTags()");
2970 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2972 attributeButton = toolBar.addAction(tr("Attributes"));
2973 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2974 attributeButton.setIcon(attributeIcon);
2975 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2976 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2978 emailButton = toolBar.addAction(tr("Email"));
2979 QIcon emailIcon = new QIcon(iconPath+"email.png");
2980 emailButton.setIcon(emailIcon);
2981 emailButton.triggered.connect(this, "emailNote()");
2982 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2984 deleteButton = toolBar.addAction(tr("Delete"));
2985 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2986 deleteButton.setIcon(deleteIcon);
2987 deleteButton.triggered.connect(this, "deleteNote()");
2988 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2990 newButton = toolBar.addAction(tr("New"));
2991 QIcon newIcon = new QIcon(iconPath+"new.png");
2992 newButton.triggered.connect(this, "addNote()");
2993 newButton.setIcon(newIcon);
2994 toggleNewButton(Global.isToolbarButtonVisible("new"));
2996 allNotesButton = toolBar.addAction(tr("All Notes"));
2997 QIcon allIcon = new QIcon(iconPath+"books.png");
2998 allNotesButton.triggered.connect(this, "allNotes()");
2999 allNotesButton.setIcon(allIcon);
3000 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
3002 //toolBar.addSeparator();
3003 //toolBar.addWidget(new QLabel(tr("Quota:")));
3004 //toolBar.addWidget(quotaBar);
3005 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
3007 //toolBar.addSeparator();
3009 //toolBar.addWidget(new QLabel(tr("Zoom")));
3010 //toolBar.addWidget(zoomSpinner);
3012 //toolBar.addWidget(new QLabel(" "));
3013 //toolBar.addSeparator();
3014 //toolBar.addWidget(new QLabel(tr(" Search:")));
3015 //toolBar.addWidget(searchField);
3016 QSizePolicy sizePolicy = new QSizePolicy();
3017 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
3018 QLabel spacer = new QLabel("");
3019 spacer.setSizePolicy(sizePolicy);
3020 toolBar.addWidget(spacer);
3021 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3023 //searchClearButton = toolBar.addAction("Search Clear");
3024 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3025 //searchClearButton.setIcon(searchClearIcon);
3026 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3027 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3029 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3031 // Update the sychronize button picture
3033 public QMenu createPopupMenu() {
3034 QMenu contextMenu = super.createPopupMenu();
3036 contextMenu.addSeparator();
3037 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3038 contextMenu.addAction(prevAction);
3039 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3041 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3042 contextMenu.addAction(nextAction);
3043 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3045 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3046 contextMenu.addAction(upAction);
3047 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3049 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3050 contextMenu.addAction(downAction);
3051 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3053 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3054 contextMenu.addAction(synchronizeAction);
3055 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3057 QAction printAction = addContextAction("print", tr("Print"));
3058 contextMenu.addAction(printAction);
3059 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3061 QAction tagAction = addContextAction("tag", tr("Tag"));
3062 contextMenu.addAction(tagAction);
3063 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3065 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3066 contextMenu.addAction(attributeAction);
3067 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3069 QAction emailAction = addContextAction("email", tr("Email"));
3070 contextMenu.addAction(emailAction);
3071 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3073 QAction deleteAction = addContextAction("delete", tr("Delete"));
3074 contextMenu.addAction(deleteAction);
3075 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3077 QAction newAction = addContextAction("new", tr("Add"));
3078 contextMenu.addAction(newAction);
3079 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3081 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3082 contextMenu.addAction(allNotesAction);
3083 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3085 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3086 contextMenu.addAction(searchClearAction);
3087 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3092 private QAction addContextAction(String config, String name) {
3093 QAction newAction = new QAction(this);
3094 newAction.setText(name);
3095 newAction.setCheckable(true);
3096 newAction.setChecked(Global.isToolbarButtonVisible(config));
3099 private void togglePrevArrowButton(Boolean toggle) {
3100 prevButton.setVisible(toggle);
3101 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3103 private void toggleNextArrowButton(Boolean toggle) {
3104 nextButton.setVisible(toggle);
3105 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3107 private void toggleUpArrowButton(Boolean toggle) {
3108 upButton.setVisible(toggle);
3109 Global.saveToolbarButtonsVisible("upArrow", toggle);
3111 private void toggleDownArrowButton(Boolean toggle) {
3112 downButton.setVisible(toggle);
3113 Global.saveToolbarButtonsVisible("downArrow", toggle);
3115 private void toggleSynchronizeButton(Boolean toggle) {
3116 synchronizeButton.setVisible(toggle);
3117 Global.saveToolbarButtonsVisible("synchronize", toggle);
3119 private void togglePrintButton(Boolean toggle) {
3120 printButton.setVisible(toggle);
3121 Global.saveToolbarButtonsVisible("print", toggle);
3123 private void toggleTagButton(Boolean toggle) {
3124 tagButton.setVisible(toggle);
3125 Global.saveToolbarButtonsVisible("tag", toggle);
3127 private void toggleAttributeButton(Boolean toggle) {
3128 attributeButton.setVisible(toggle);
3129 Global.saveToolbarButtonsVisible("attribute", toggle);
3131 private void toggleEmailButton(Boolean toggle) {
3132 emailButton.setVisible(toggle);
3133 Global.saveToolbarButtonsVisible("email", toggle);
3135 private void toggleDeleteButton(Boolean toggle) {
3136 deleteButton.setVisible(toggle);
3137 Global.saveToolbarButtonsVisible("delete", toggle);
3139 private void toggleNewButton(Boolean toggle) {
3140 newButton.setVisible(toggle);
3141 Global.saveToolbarButtonsVisible("new", toggle);
3143 private void toggleAllNotesButton(Boolean toggle) {
3144 allNotesButton.setVisible(toggle);
3145 Global.saveToolbarButtonsVisible("allNotes", toggle);
3147 @SuppressWarnings("unused")
3148 private void toggleSearchClearButton(Boolean toggle) {
3149 searchClearButton.setVisible(toggle);
3150 Global.saveToolbarButtonsVisible("searchClear", toggle);
3157 @SuppressWarnings("unused")
3158 private void updateSyncButton() {
3160 if (syncIcons == null) {
3161 syncIcons = new ArrayList<QPixmap>();
3163 synchronizeIconAngle = 0;
3164 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3166 for (int i=0; i<=360; i++) {
3167 QPixmap rotatedPix = new QPixmap(pix.size());
3168 QPainter p = new QPainter(rotatedPix);
3169 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3170 QSize size = pix.size();
3171 p.translate(size.width()/2, size.height()/2);
3174 p.setBackgroundMode(BGMode.OpaqueMode);
3175 p.translate(-size.width()/2, -size.height()/2);
3176 p.drawPixmap(0,0, pix);
3178 syncIcons.add(rotatedPix);
3182 synchronizeIconAngle++;
3183 if (synchronizeIconAngle > 359)
3184 synchronizeIconAngle=0;
3185 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3188 // Synchronize with Evernote
3190 private void evernoteSync() {
3191 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3192 if (!Global.isConnected)
3194 if (Global.isConnected)
3195 synchronizeAnimationTimer.start(5);
3196 // synchronizeAnimationTimer.start(200);
3198 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3200 private void updateQuotaBar() {
3201 long limit = Global.getUploadLimit();
3202 long amount = Global.getUploadAmount();
3203 if (amount>0 && limit>0) {
3204 int percent =(int)(amount*100/limit);
3205 quotaBar.setValue(percent);
3207 quotaBar.setValue(0);
3210 @SuppressWarnings("unused")
3211 private void zoomChanged() {
3212 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3215 //****************************************************************
3216 //****************************************************************
3217 //* System Tray functions
3218 //****************************************************************
3219 //****************************************************************
3220 private void trayToggleVisible() {
3225 if (windowMaximized)
3232 @SuppressWarnings("unused")
3233 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3234 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3235 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3236 trayToggleVisible();
3241 //***************************************************************
3242 //***************************************************************
3243 //** These functions deal with the trash tree
3244 //***************************************************************
3245 //***************************************************************
3246 // Setup the tree containing the trash.
3247 @SuppressWarnings("unused")
3248 private void trashTreeSelection() {
3249 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3251 clearNotebookFilter();
3253 clearAttributeFilter();
3254 clearSavedSearchFilter();
3256 String tempGuid = currentNoteGuid;
3258 // currentNoteGuid = "";
3259 currentNote = new Note();
3260 selectedNoteGUIDs.clear();
3261 listManager.getSelectedNotebooks().clear();
3262 listManager.getSelectedTags().clear();
3263 listManager.setSelectedSavedSearch("");
3264 browserWindow.clear();
3266 // toggle the add buttons
3267 newButton.setEnabled(!newButton.isEnabled());
3268 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3269 menuBar.noteAdd.setVisible(true);
3271 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3272 if (selections.size() == 0) {
3273 currentNoteGuid = trashNoteGuid;
3274 trashNoteGuid = tempGuid;
3275 Global.showDeleted = false;
3276 menuBar.noteRestoreAction.setEnabled(false);
3277 menuBar.noteRestoreAction.setVisible(false);
3280 trashNoteGuid = tempGuid;
3281 currentNoteGuid = trashNoteGuid;
3282 menuBar.noteRestoreAction.setEnabled(true);
3283 menuBar.noteRestoreAction.setVisible(true);
3284 Global.showDeleted = true;
3286 listManager.loadNotesIndex();
3287 noteIndexUpdated(false);
3288 //// browserWindow.setEnabled(newButton.isEnabled());
3289 browserWindow.setReadOnly(!newButton.isEnabled());
3290 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3292 // Empty the trash file
3293 @SuppressWarnings("unused")
3294 private void emptyTrash() {
3295 // browserWindow.clear();
3296 logger.log(logger.EXTREME, "Emptying Trash");
3297 listManager.emptyTrash();
3298 logger.log(logger.EXTREME, "Resetting view after trash empty");
3299 if (trashTree.selectedItems().size() > 0) {
3300 listManager.getSelectedNotebooks().clear();
3301 listManager.getSelectedTags().clear();
3302 listManager.setSelectedSavedSearch("");
3303 newButton.setEnabled(!newButton.isEnabled());
3304 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3305 menuBar.noteAdd.setVisible(true);
3306 browserWindow.clear();
3309 clearNotebookFilter();
3310 clearSavedSearchFilter();
3311 clearAttributeFilter();
3313 Global.showDeleted = false;
3314 menuBar.noteRestoreAction.setEnabled(false);
3315 menuBar.noteRestoreAction.setVisible(false);
3317 listManager.loadNotesIndex();
3318 noteIndexUpdated(false);
3321 // Show/Hide trash window
3322 @SuppressWarnings("unused")
3323 private void toggleTrashWindow() {
3324 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3325 if (trashTree.isVisible())
3329 menuBar.hideTrash.setChecked(trashTree.isVisible());
3331 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3332 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3334 private void clearTrashFilter() {
3335 Global.showDeleted = false;
3336 newButton.setEnabled(true);
3337 menuBar.noteAdd.setEnabled(true);
3338 menuBar.noteAdd.setVisible(true);
3339 trashTree.blockSignals(true);
3340 trashTree.clearSelection();
3341 trashTree.blockSignals(false);
3346 //***************************************************************
3347 //***************************************************************
3348 //** These functions deal with connection settings
3349 //***************************************************************
3350 //***************************************************************
3351 // SyncRunner had a problem and things are disconnected
3352 @SuppressWarnings("unused")
3353 private void remoteErrorDisconnect() {
3354 menuBar.connectAction.setText(tr("Connect"));
3355 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3356 menuBar.synchronizeAction.setEnabled(false);
3357 Global.isConnected = false;
3358 synchronizeAnimationTimer.stop();
3361 // Do a manual connect/disconnect
3362 private void remoteConnect() {
3363 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3365 if (Global.isConnected) {
3366 Global.isConnected = false;
3367 syncRunner.enDisconnect();
3368 setupConnectMenuOptions();
3373 AESEncrypter aes = new AESEncrypter();
3375 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3376 } catch (FileNotFoundException e) {
3377 // File not found, so we'll just get empty strings anyway.
3380 if (Global.getProxyValue("url").equals("")) {
3381 System.setProperty("http.proxyHost","") ;
3382 System.setProperty("http.proxyPort", "") ;
3383 System.setProperty("https.proxyHost","") ;
3384 System.setProperty("https.proxyPort", "") ;
3387 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3388 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3389 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3390 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3392 if (Global.getProxyValue("userid").equals("")) {
3393 Authenticator.setDefault(new Authenticator() {
3395 protected PasswordAuthentication getPasswordAuthentication() {
3397 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3403 syncRunner.userStoreUrl = Global.userStoreUrl;
3404 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3405 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3407 String userid = aes.getUserid();
3408 String password = aes.getPassword();
3409 if (!userid.equals("") && !password.equals("")) {
3410 Global.username = userid;
3411 Global.password = password;
3412 syncRunner.username = Global.username;
3413 syncRunner.password = Global.password;
3414 syncRunner.enConnect();
3417 Global.isConnected = syncRunner.isConnected;
3419 if (!Global.isConnected) {
3420 // Show the login dialog box
3421 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3422 LoginDialog login = new LoginDialog();
3425 if (!login.okPressed()) {
3429 Global.username = login.getUserid();
3430 Global.password = login.getPassword();
3432 syncRunner.username = Global.username;
3433 syncRunner.password = Global.password;
3434 syncRunner.enConnect();
3435 Global.isConnected = syncRunner.isConnected;
3438 if (!Global.isConnected)
3441 setupConnectMenuOptions();
3442 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3444 private void setupConnectMenuOptions() {
3445 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3446 if (!Global.isConnected) {
3447 menuBar.connectAction.setText(tr("Connect"));
3448 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3449 menuBar.synchronizeAction.setEnabled(false);
3451 menuBar.connectAction.setText(tr("Disconnect"));
3452 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3453 menuBar.synchronizeAction.setEnabled(true);
3455 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3460 //***************************************************************
3461 //***************************************************************
3462 //** These functions deal with the GUI Attribute tree
3463 //***************************************************************
3464 //***************************************************************
3465 @SuppressWarnings("unused")
3466 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3468 // clearTagFilter();
3469 // clearNotebookFilter();
3471 // clearSavedSearchFilter();
3473 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3474 if (item.childCount() > 0) {
3475 item.setSelected(false);
3477 Global.createdBeforeFilter.reset();
3478 Global.createdSinceFilter.reset();
3479 Global.changedBeforeFilter.reset();
3480 Global.changedSinceFilter.reset();
3481 Global.containsFilter.reset();
3482 attributeTreeSelected = item;
3483 DateAttributeFilterTable f = null;
3484 f = findDateAttributeFilterTable(item.parent());
3486 f.select(item.parent().indexOfChild(item));
3488 Global.containsFilter.select(item.parent().indexOfChild(item));
3491 listManager.loadNotesIndex();
3492 noteIndexUpdated(false);
3495 attributeTreeSelected = null;
3496 item.setSelected(false);
3497 Global.createdBeforeFilter.reset();
3498 Global.createdSinceFilter.reset();
3499 Global.changedBeforeFilter.reset();
3500 Global.changedSinceFilter.reset();
3501 Global.containsFilter.reset();
3502 listManager.loadNotesIndex();
3503 noteIndexUpdated(false);
3505 // This determines what attribute filter we need, depending upon the selection
3506 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3507 if (w.parent() != null && w.childCount() > 0) {
3508 QTreeWidgetItem parent = w.parent();
3509 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3510 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3511 return Global.createdSinceFilter;
3512 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3513 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3514 return Global.createdBeforeFilter;
3515 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3516 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3517 return Global.changedSinceFilter;
3518 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3519 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3520 return Global.changedBeforeFilter;
3525 // Show/Hide attribute search window
3526 @SuppressWarnings("unused")
3527 private void toggleAttributesWindow() {
3528 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3529 if (attributeTree.isVisible())
3530 attributeTree.hide();
3532 attributeTree.show();
3533 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3535 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3536 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3538 private void clearAttributeFilter() {
3539 Global.createdBeforeFilter.reset();
3540 Global.createdSinceFilter.reset();
3541 Global.changedBeforeFilter.reset();
3542 Global.changedSinceFilter.reset();
3543 Global.containsFilter.reset();
3544 attributeTreeSelected = null;
3545 attributeTree.blockSignals(true);
3546 attributeTree.clearSelection();
3547 attributeTree.blockSignals(false);
3551 //***************************************************************
3552 //***************************************************************
3553 //** These functions deal with the GUI Note index table
3554 //***************************************************************
3555 //***************************************************************
3556 // Initialize the note list table
3557 private void initializeNoteTable() {
3558 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3559 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3560 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3561 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3563 // Show/Hide trash window
3564 @SuppressWarnings("unused")
3565 private void toggleNoteListWindow() {
3566 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3567 if (noteTableView.isVisible())
3568 noteTableView.hide();
3570 noteTableView.show();
3571 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3573 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3574 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3576 // Handle the event that a user selects a note from the table
3577 @SuppressWarnings("unused")
3578 private void noteTableSelection() {
3579 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3583 // If we have more than one selection, then set the merge note action to true.
3584 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3585 if (selections.size() > 1)
3586 menuBar.noteMergeAction.setEnabled(true);
3588 menuBar.noteMergeAction.setEnabled(false);
3590 // If the ctrl key is pressed, then they are selecting multiple
3591 // entries and we don't want to change the currently viewed note.
3592 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3593 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3596 if (historyGuids.size() == 0) {
3597 historyGuids.add(currentNoteGuid);
3598 historyPosition = 1;
3600 noteTableView.showColumn(Global.noteTableGuidPosition);
3602 if (!Global.isColumnVisible("guid"))
3603 noteTableView.hideColumn(Global.noteTableGuidPosition);
3605 if (selections.size() > 0) {
3607 menuBar.noteDuplicateAction.setEnabled(true);
3608 menuBar.noteOnlineHistoryAction.setEnabled(true);
3609 menuBar.noteMergeAction.setEnabled(true);
3610 selectedNoteGUIDs.clear();
3611 if (selections.size() != 1 || Global.showDeleted) {
3612 menuBar.noteDuplicateAction.setEnabled(false);
3614 if (selections.size() != 1 || !Global.isConnected) {
3615 menuBar.noteOnlineHistoryAction.setEnabled(false);
3617 if (selections.size() == 1) {
3618 menuBar.noteMergeAction.setEnabled(false);
3620 for (int i=0; i<selections.size(); i++) {
3621 int row = selections.get(i).row();
3623 upButton.setEnabled(false);
3625 upButton.setEnabled(true);
3626 if (row < listManager.getNoteTableModel().rowCount()-1)
3627 downButton.setEnabled(true);
3629 downButton.setEnabled(false);
3630 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3631 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3632 currentNoteGuid = (String)ix.values().toArray()[0];
3633 selectedNoteGUIDs.add(currentNoteGuid);
3637 nextButton.setEnabled(true);
3638 prevButton.setEnabled(true);
3640 int endPosition = historyGuids.size()-1;
3641 for (int j=historyPosition; j<=endPosition; j++) {
3642 historyGuids.remove(historyGuids.size()-1);
3644 historyGuids.add(currentNoteGuid);
3645 historyPosition = historyGuids.size();
3647 if (historyPosition <= 1)
3648 prevButton.setEnabled(false);
3649 if (historyPosition == historyGuids.size())
3650 nextButton.setEnabled(false);
3652 fromHistory = false;
3653 scrollToGuid(currentNoteGuid);
3654 refreshEvernoteNote(true);
3655 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3657 // Trigger a refresh when the note db has been updated
3658 private void noteIndexUpdated(boolean reload) {
3659 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3661 refreshEvernoteNoteList();
3662 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3663 noteTableView.load(reload);
3664 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3666 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3667 pos = noteTableView.proxyModel.rowCount();
3670 if (noteTableView.proxyModel.rowCount() == 0)
3673 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3675 currentNoteGuid = (String)i.data();
3679 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3681 scrollToGuid(currentNoteGuid);
3682 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3684 // Called when the list of notes is updated
3685 private void refreshEvernoteNoteList() {
3686 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3687 browserWindow.setDisabled(false);
3688 if (selectedNoteGUIDs == null)
3689 selectedNoteGUIDs = new ArrayList<String>();
3690 selectedNoteGUIDs.clear(); // clear out old entries
3692 String saveCurrentNoteGuid = new String();
3693 String tempNoteGuid = new String();
3695 historyGuids.clear();
3696 historyPosition = 0;
3697 prevButton.setEnabled(false);
3698 nextButton.setEnabled(false);
3700 if (currentNoteGuid == null)
3701 currentNoteGuid = new String();
3703 //determine current note guid
3704 for (Note note : listManager.getNoteIndex()) {
3705 tempNoteGuid = note.getGuid();
3706 if (currentNoteGuid.equals(tempNoteGuid)) {
3707 saveCurrentNoteGuid = tempNoteGuid;
3711 if (listManager.getNoteIndex().size() == 0) {
3712 currentNoteGuid = "";
3714 browserWindow.clear();
3715 browserWindow.setDisabled(true);
3718 if (Global.showDeleted && listManager.getNotebookIndex().size() > 0 && saveCurrentNoteGuid.equals("")) {
3719 currentNoteGuid = listManager.getNoteIndex().get(0).getGuid();
3720 saveCurrentNoteGuid = currentNoteGuid;
3721 refreshEvernoteNote(true);
3724 if (!saveCurrentNoteGuid.equals("")) {
3725 refreshEvernoteNote(false);
3727 currentNoteGuid = "";
3729 reloadTagTree(false);
3731 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3733 // Called when the previous arrow button is clicked
3734 @SuppressWarnings("unused")
3735 private void previousViewedAction() {
3736 if (!prevButton.isEnabled())
3738 if (historyPosition == 0)
3741 if (historyPosition <= 0)
3743 String historyGuid = historyGuids.get(historyPosition-1);
3745 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3746 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3747 if (modelIndex != null) {
3748 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3749 String tableGuid = (String)ix.values().toArray()[0];
3750 if (tableGuid.equals(historyGuid)) {
3751 noteTableView.selectRow(i);
3757 @SuppressWarnings("unused")
3758 private void nextViewedAction() {
3759 if (!nextButton.isEnabled())
3761 String historyGuid = historyGuids.get(historyPosition);
3764 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3765 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3766 if (modelIndex != null) {
3767 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3768 String tableGuid = (String)ix.values().toArray()[0];
3769 if (tableGuid.equals(historyGuid)) {
3770 noteTableView.selectRow(i);
3776 // Called when the up arrow is clicked
3777 @SuppressWarnings("unused")
3778 private void upAction() {
3779 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3780 int row = selections.get(0).row();
3782 noteTableView.selectRow(row-1);
3785 // Called when the down arrow is clicked
3786 @SuppressWarnings("unused")
3787 private void downAction() {
3788 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3789 int row = selections.get(0).row();
3790 int max = listManager.getNoteTableModel().rowCount();
3792 noteTableView.selectRow(row+1);
3795 // Update a tag string for a specific note in the list
3796 @SuppressWarnings("unused")
3797 private void updateListTags(String guid, List<String> tags) {
3798 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3799 StringBuffer tagBuffer = new StringBuffer();
3800 for (int i=0; i<tags.size(); i++) {
3801 tagBuffer.append(tags.get(i));
3802 if (i<tags.size()-1)
3803 tagBuffer.append(", ");
3806 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3807 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3808 if (modelIndex != null) {
3809 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3810 String tableGuid = (String)ix.values().toArray()[0];
3811 if (tableGuid.equals(guid)) {
3812 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3813 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3814 noteTableView.proxyModel.invalidate();
3819 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3821 // Update a title for a specific note in the list
3822 @SuppressWarnings("unused")
3823 private void updateListAuthor(String guid, String author) {
3824 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3826 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3827 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
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.noteTableAuthorPosition,author);
3834 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3835 noteTableView.proxyModel.invalidate();
3841 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3843 private void updateListNoteNotebook(String guid, String notebook) {
3844 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3845 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3846 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3848 // Update a title for a specific note in the list
3849 @SuppressWarnings("unused")
3850 private void updateListSourceUrl(String guid, String url) {
3851 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3853 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3854 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3855 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3856 if (modelIndex != null) {
3857 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3858 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3859 String tableGuid = (String)ix.values().toArray()[0];
3860 if (tableGuid.equals(guid)) {
3861 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3862 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3863 noteTableView.proxyModel.invalidate();
3868 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3870 @SuppressWarnings("unused")
3871 private void updateListGuid(String oldGuid, String newGuid) {
3872 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3874 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3875 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3876 if (modelIndex != null) {
3877 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3878 String tableGuid = (String)ix.values().toArray()[0];
3879 if (tableGuid.equals(oldGuid)) {
3880 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3881 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3886 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3888 private void updateListTagName(String guid) {
3889 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3891 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3892 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3893 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
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 noteGuid = (String)ix.values().toArray()[0];
3900 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3901 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3902 i=listManager.getNoteTableModel().rowCount();
3908 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3910 private void removeListTagName(String guid) {
3911 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3913 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3914 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3915 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3916 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3917 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3920 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3921 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3922 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3923 if (modelIndex != null) {
3924 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3925 String noteGuid = (String)ix.values().toArray()[0];
3926 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3927 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3928 i=listManager.getNoteTableModel().rowCount();
3934 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3936 private void updateListNotebookName(String oldName, String newName) {
3937 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3939 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3940 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3941 if (modelIndex != null) {
3942 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3943 String tableName = (String)ix.values().toArray()[0];
3944 if (tableName.equalsIgnoreCase(oldName)) {
3945 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3949 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3951 @SuppressWarnings("unused")
3952 private void updateListDateCreated(String guid, QDateTime date) {
3953 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3955 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3956 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3957 if (modelIndex != null) {
3958 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3959 String tableGuid = (String)ix.values().toArray()[0];
3960 if (tableGuid.equals(guid)) {
3961 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3962 noteTableView.proxyModel.invalidate();
3967 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3969 @SuppressWarnings("unused")
3970 private void updateListDateSubject(String guid, QDateTime date) {
3971 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3973 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3974 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3975 if (modelIndex != null) {
3976 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3977 String tableGuid = (String)ix.values().toArray()[0];
3978 if (tableGuid.equals(guid)) {
3979 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3980 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3981 noteTableView.proxyModel.invalidate();
3986 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3988 private void updateListDateChanged(String guid, QDateTime date) {
3989 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3991 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3992 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3993 if (modelIndex != null) {
3994 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3995 String tableGuid = (String)ix.values().toArray()[0];
3996 if (tableGuid.equals(guid)) {
3997 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3998 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4003 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4005 private void updateListDateChanged() {
4006 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
4007 QDateTime date = new QDateTime(QDateTime.currentDateTime());
4008 updateListDateChanged(currentNoteGuid, date);
4009 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4012 private void scrollToCurrentGuid() {
4013 //scrollToGuid(currentNoteGuid);
4014 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
4015 if (selections.size() == 0)
4017 QModelIndex index = selections.get(0);
4018 int row = selections.get(0).row();
4019 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
4022 // Scroll to the current GUID in tthe list.
4023 // Scroll to a particular index item
4024 private void scrollToGuid(String guid) {
4025 if (currentNote == null || guid == null)
4027 if (currentNote.isActive() && Global.showDeleted) {
4028 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4029 if (!listManager.getNoteIndex().get(i).isActive()) {
4030 currentNote = listManager.getNoteIndex().get(i);
4031 currentNoteGuid = currentNote.getGuid();
4032 i = listManager.getNoteIndex().size();
4036 if (!currentNote.isActive() && !Global.showDeleted) {
4037 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4038 if (listManager.getNoteIndex().get(i).isActive()) {
4039 currentNote = listManager.getNoteIndex().get(i);
4040 currentNoteGuid = currentNote.getGuid();
4041 i = listManager.getNoteIndex().size();
4046 for (int i=0; i<noteTableView.model().rowCount(); i++) {
4047 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4048 if (currentNoteGuid.equals(index.data())) {
4049 // noteTableView.selectionModel().blockSignals(true);
4050 noteTableView.selectRow(i);
4051 // noteTableView.selectionModel().blockSignals(false);
4052 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
4053 i=listManager.getNoteTableModel().rowCount();
4056 noteTableView.repaint();
4058 // Show/Hide columns
4059 private void showColumns() {
4060 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4061 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4062 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4063 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4064 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4065 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4066 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4067 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4068 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4069 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4070 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4071 noteTableView.setColumnHidden(Global.noteTablePinnedPosition, !Global.isColumnVisible("pinned"));
4073 // Title color has changed
4074 @SuppressWarnings("unused")
4075 private void titleColorChanged(Integer color) {
4076 logger.log(logger.HIGH, "Entering NeverNote.titleColorChanged");
4079 QColor backgroundColor = new QColor();
4080 QColor foregroundColor = new QColor(QColor.black);
4081 backgroundColor.setRgb(color);
4083 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4084 foregroundColor.setRgb(QColor.white.rgb());
4086 if (selectedNoteGUIDs.size() == 0)
4087 selectedNoteGUIDs.add(currentNoteGuid);
4089 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4090 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4091 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4092 if (modelIndex != null) {
4093 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4094 String tableGuid = (String)ix.values().toArray()[0];
4095 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4096 for (int k=0; k<Global.noteTableColumnCount; k++) {
4097 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4098 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4099 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4101 i=listManager.getNoteTableModel().rowCount();
4106 logger.log(logger.HIGH, "Leaving NeverNote.titleColorChanged");
4108 // A note has been pinned or unpinned
4109 @SuppressWarnings("unused")
4110 private void notePinned() {
4111 logger.log(logger.EXTREME, "Entering NeverNote.notePinned()");
4114 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4115 NoteMetadata meta = listManager.getNoteMetadata().get(selectedNoteGUIDs.get(j));
4116 boolean pinned = !meta.isPinned();
4117 meta.setPinned(pinned); // Toggle the pinned/unpinned
4119 // Update the list & table
4120 listManager.updateNoteMetadata(meta);
4121 noteTableView.proxyModel.addGuid(selectedNoteGUIDs.get(j), meta);
4124 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4126 // Wide list was chosen
4127 public void narrowListView() {
4128 saveNoteColumnPositions();
4129 saveNoteIndexWidth();
4131 int sortCol = noteTableView.proxyModel.sortColumn();
4132 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4133 Global.setSortColumn(sortCol);
4134 Global.setSortOrder(sortOrder);
4136 Global.setListView(Global.View_List_Narrow);
4138 menuBar.wideListView.blockSignals(true);
4139 menuBar.narrowListView.blockSignals(true);
4141 menuBar.wideListView.setChecked(false);
4142 menuBar.narrowListView.setChecked(true);
4144 menuBar.wideListView.blockSignals(false);
4145 menuBar.narrowListView.blockSignals(false);
4147 mainLeftRightSplitter.addWidget(noteTableView);
4148 mainLeftRightSplitter.addWidget(browserWindow);
4149 restoreWindowState(false);
4150 noteTableView.repositionColumns();
4151 noteTableView.resizeColumnWidths();
4152 noteTableView.resizeRowHeights();
4154 sortCol = Global.getSortColumn();
4155 sortOrder = Global.getSortOrder();
4156 noteTableView.proxyModel.blocked = true;
4157 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4158 noteTableView.proxyModel.blocked = false;
4162 noteTableView.load(false);
4163 refreshEvernoteNote(true);
4164 scrollToCurrentGuid();
4166 public void wideListView() {
4167 int sortCol = noteTableView.proxyModel.sortColumn();
4168 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4169 Global.setSortColumn(sortCol);
4170 Global.setSortOrder(sortOrder);
4173 saveNoteColumnPositions();
4174 saveNoteIndexWidth();
4175 Global.setListView(Global.View_List_Wide);
4177 menuBar.wideListView.blockSignals(true);
4178 menuBar.narrowListView.blockSignals(true);
4180 menuBar.wideListView.setChecked(true);
4181 menuBar.narrowListView.setChecked(false);
4183 menuBar.wideListView.blockSignals(false);
4184 menuBar.narrowListView.blockSignals(false);
4185 browserIndexSplitter.setVisible(true);
4186 browserIndexSplitter.addWidget(noteTableView);
4187 browserIndexSplitter.addWidget(browserWindow);
4188 restoreWindowState(false);
4189 noteTableView.repositionColumns();
4190 noteTableView.resizeColumnWidths();
4191 noteTableView.resizeRowHeights();
4193 sortCol = Global.getSortColumn();
4194 sortOrder = Global.getSortOrder();
4195 noteTableView.proxyModel.blocked = true;
4196 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4197 noteTableView.proxyModel.blocked = false;
4200 noteTableView.load(false);
4201 scrollToCurrentGuid();
4203 // Sort order for the notebook has changed
4204 public void tableSortOrderChanged(Integer column, Integer order) {
4206 // Find what notebook (if any) is selected. We ignore stacks & the "All Notebooks".
4207 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4208 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4209 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4211 notebook = currentSelectedNotebook.text(2);
4212 conn.getNotebookTable().setSortOrder(notebook, column, order);
4216 //***************************************************************
4217 @SuppressWarnings("unused")
4218 private void evernoteLinkClick(String syncGuid, String locGuid) {
4220 if (conn.getNoteTable().guidExists(syncGuid)) {
4223 // If we didn't find it via the synchronized guid, look under the local guid
4224 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4225 // later synchronized (that causes the guid to change so we need to find the new one).
4226 if (conn.getNoteTable().guidExists(locGuid))
4229 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4232 openExternalEditor(guid);
4236 //If we've gotten this far, we can't find the note
4237 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4238 " seem to find that note."));
4240 //***************************************************************
4241 //***************************************************************
4242 //** External editor window functions
4243 //***************************************************************
4244 //***************************************************************
4245 private void listDoubleClick() {
4247 openExternalEditor(currentNoteGuid);
4249 private void openExternalEditor(String guid) {
4251 if (externalWindows.containsKey(guid)) {
4252 externalWindows.get(guid).raise();
4255 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4256 // We have a new external editor to create
4257 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4258 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4259 newBrowser.setWindowIcon(appIcon);
4260 externalWindows.put(guid, newBrowser);
4261 showEditorButtons(newBrowser.getBrowserWindow());
4262 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4263 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4264 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4265 //newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4266 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4267 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4268 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4269 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4271 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4272 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4273 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4277 @SuppressWarnings({ "rawtypes", "unused" })
4278 private void externalWindowTagsEdited(String guid, List values) {
4279 StringBuffer line = new StringBuffer(100);
4280 for (int i=0; i<values.size(); i++) {
4282 line.append(Global.tagDelimeter+" ");
4283 line.append(values.get(i));
4285 if (guid.equals(currentNoteGuid)) {
4286 browserWindow.setTag(line.toString());
4289 @SuppressWarnings("unused")
4290 private void externalWindowClosing(String guid) {
4291 externalWindows.remove(guid);
4296 //***************************************************************
4297 //***************************************************************
4298 //** These functions deal with Note specific things
4299 //***************************************************************
4300 //***************************************************************
4301 private void setNoteDirty() {
4302 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4304 // Find if the note is being edited externally. If it is, update it.
4305 if (externalWindows.containsKey(currentNoteGuid)) {
4306 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4307 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4308 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4309 window.getBrowserWindow().setContent(unicode);
4312 // If the note is dirty, then it is unsynchronized by default.
4316 // Set the note as dirty and check if its status is synchronized in the display table
4318 if (listManager.getNoteMetadata().containsKey(currentNoteGuid) &&
4319 listManager.getNoteMetadata().get(currentNoteGuid).isDirty()) {
4323 // If this wasn't already marked as unsynchronized, then we need to update the table
4324 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4325 // listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4326 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4327 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4328 if (modelIndex != null) {
4329 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4330 String tableGuid = (String)ix.values().toArray()[0];
4331 if (tableGuid.equals(currentNoteGuid)) {
4332 listManager.getNoteTableModel().proxyModel.setData(i, Global.noteTableSynchronizedPosition, "false");
4338 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4340 @SuppressWarnings("unused")
4341 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4342 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4343 QByteArray unicode = codec.fromUnicode(content);
4344 noteCache.remove(guid);
4345 noteCache.put(guid, unicode.toString());
4346 if (guid.equals(currentNoteGuid)) {
4348 browserWindow.setContent(unicode);
4351 thumbnailRunner.addWork("GENERATE "+ guid);
4352 saveNote(guid, browser);
4356 private void saveNote() {
4358 saveNote(currentNoteGuid, browserWindow);
4359 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4363 private void saveNote(String guid, BrowserWindow window) {
4364 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4367 logger.log(logger.EXTREME, "Saving to cache");
4368 QTextCodec codec = QTextCodec.codecForLocale();
4369 // QTextDecoder decoder = codec.makeDecoder();
4370 codec = QTextCodec.codecForName("UTF-8");
4371 QByteArray unicode = codec.fromUnicode(window.getContent());
4372 noteCache.put(guid, unicode.toString());
4374 logger.log(logger.EXTREME, "updating list manager");
4375 listManager.updateNoteContent(guid, window.getContent());
4376 logger.log(logger.EXTREME, "Updating title");
4377 listManager.updateNoteTitle(guid, window.getTitle());
4378 updateListDateChanged();
4380 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4381 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4382 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4383 currentNote = listManager.getNoteIndex().get(i);
4384 i = listManager.getNoteIndex().size();
4389 // Get a note from Evernote (and put it in the browser)
4390 private void refreshEvernoteNote(boolean reload) {
4391 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4393 if (Global.disableViewing) {
4394 browserWindow.setEnabled(false);
4399 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4401 Global.cryptCounter =0;
4403 browserWindow.setReadOnly(true);
4410 browserWindow.loadingData(true);
4412 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4413 if (currentNote == null)
4415 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4418 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4419 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4420 formatter.setNote(note, Global.pdfPreview());
4421 formatter.setHighlight(listManager.getEnSearch());
4423 if (!noteCache.containsKey(guid)) {
4424 js = new QByteArray();
4425 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4426 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4427 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>");
4428 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4429 js.append("<style> img { height:auto; width:auto; max-height:auto; max-width:100%; }</style>");
4430 if (Global.displayRightToLeft())
4431 js.append("<style> body { direction:rtl; }</style>");
4432 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4433 js.append("</head>");
4434 formatter.setNote(note, Global.pdfPreview());
4435 js.append(formatter.rebuildNoteHTML());
4436 js.append("</HTML>");
4437 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4438 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4439 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4440 // if (Global.enableHTMLEntitiesFix) {
4441 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4443 browser.setContent(js);
4444 noteCache.put(guid, js.toString());
4446 if (formatter.resourceError)
4447 resourceErrorMessage();
4448 if (formatter.formatError) {
4450 QMessageBox.information(this, tr("Error"),
4451 tr("NixNote had issues formatting this note." +
4452 " To protect your data this note is being marked as read-only."));
4455 readOnly = formatter.readOnly;
4456 inkNote = formatter.inkNote;
4458 readOnlyCache.put(guid, true);
4460 inkNoteCache.put(guid, true);
4462 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4463 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4464 js = new QByteArray(cachedContent);
4465 browser.setContent(js);
4466 if (readOnlyCache.containsKey(guid))
4468 if (inkNoteCache.containsKey(guid))
4471 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4472 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4474 if (readOnly || inkNote ||
4475 (note.getAttributes() != null && note.getAttributes().getContentClass() != null && note.getAttributes().getContentClass() != ""))
4476 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4478 browser.getBrowser().page().setContentEditable(true);
4479 browser.setReadOnly(readOnly);
4480 deleteButton.setEnabled(!readOnly);
4481 tagButton.setEnabled(!readOnly);
4482 menuBar.noteDelete.setEnabled(!readOnly);
4483 menuBar.noteTags.setEnabled(!readOnly);
4484 browser.setNote(note);
4486 if (note != null && note.getNotebookGuid() != null &&
4487 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4488 deleteButton.setEnabled(false);
4489 menuBar.notebookDeleteAction.setEnabled(false);
4491 deleteButton.setEnabled(true);
4492 menuBar.notebookDeleteAction.setEnabled(true);
4495 // Build a list of non-closed notebooks
4496 List<Notebook> nbooks = new ArrayList<Notebook>();
4497 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4498 boolean found=false;
4499 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4500 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4504 nbooks.add(listManager.getNotebookIndex().get(i));
4507 browser.setTitle(note.getTitle());
4508 browser.setTag(getTagNamesForNote(note));
4509 browser.setAuthor(note.getAttributes().getAuthor());
4511 browser.setAltered(note.getUpdated());
4512 browser.setCreation(note.getCreated());
4513 if (note.getAttributes().getSubjectDate() > 0)
4514 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4516 browser.setSubjectDate(note.getCreated());
4517 browser.setUrl(note.getAttributes().getSourceURL());
4519 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4520 List<Tag> tagList = tagFilter.getValidTags(note);
4521 browser.setAllTags(tagList);
4523 browser.setCurrentTags(note.getTagNames());
4527 browser.loadingData(false);
4528 if (thumbnailViewer.isActiveWindow())
4531 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4532 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4535 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4537 // Save a generated thumbnail
4538 private void toggleNoteInformation() {
4539 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4540 browserWindow.toggleInformation();
4541 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4542 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4543 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4545 // Listener triggered when a print button is pressed
4546 @SuppressWarnings("unused")
4547 private void printNote() {
4548 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4550 QPrintDialog dialog = new QPrintDialog();
4551 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4552 QPrinter printer = dialog.printer();
4553 browserWindow.getBrowser().print(printer);
4555 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4558 // Listener triggered when the email button is pressed
4559 @SuppressWarnings("unused")
4560 private void emailNote() {
4561 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4563 if (Desktop.isDesktopSupported()) {
4564 Desktop desktop = Desktop.getDesktop();
4566 String text2 = browserWindow.getContentsToEmail();
4567 QUrl url = new QUrl("mailto:");
4568 url.addQueryItem("subject", currentNote.getTitle());
4569 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4570 url.addQueryItem("body", text2);
4571 QDesktopServices.openUrl(url);
4575 if (desktop.isSupported(Desktop.Action.MAIL)) {
4576 URI uriMailTo = null;
4578 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4579 String text = browserWindow.getContentsToEmail();
4580 //text = "<b>" +text +"</b>";
4581 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4582 +"&BODY=" +text, null);
4583 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4584 +"&ATTACHMENT=d:/test.pdf", null);
4585 desktop.mail(uriMailTo);
4586 } catch (URISyntaxException e) {
4587 e.printStackTrace();
4588 } catch (IOException e) {
4589 e.printStackTrace();
4596 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4598 // Reindex all notes
4599 @SuppressWarnings("unused")
4600 private void fullReindex() {
4601 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4602 indexRunner.addWork("REINDEXALL");
4603 setMessage(tr("Database will be reindexed."));
4604 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4606 // Listener when a user wants to reindex a specific note
4607 @SuppressWarnings("unused")
4608 private void reindexNote() {
4609 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4610 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4611 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4613 if (selectedNotebookGUIDs.size() > 1)
4614 setMessage(tr("Notes will be reindexed."));
4616 setMessage(tr("Note will be reindexed."));
4617 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4620 @SuppressWarnings("unused")
4621 private void deleteNote() {
4622 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4623 if (currentNote == null)
4625 if (currentNoteGuid.equals(""))
4627 String title = null;
4628 if (selectedNoteGUIDs.size() == 1)
4629 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4631 // If we are deleting non-trash notes
4632 if (currentNote.isActive()) {
4633 if (Global.verifyDelete()) {
4635 if (selectedNoteGUIDs.size() > 1) {
4636 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4639 msg = new String(tr("Delete note \"") +title +"\"?");
4641 msg = new String(tr("Delete note selected note?"));
4643 if (QMessageBox.question(this, tr("Confirmation"), msg,
4644 QMessageBox.StandardButton.Yes,
4645 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4649 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4650 selectedNoteGUIDs.add(currentNoteGuid);
4651 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4652 listManager.deleteNote(selectedNoteGUIDs.get(i));
4655 // If we are deleting from the trash.
4656 if (Global.verifyDelete()) {
4658 if (selectedNoteGUIDs.size() > 1) {
4659 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4662 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4664 msg = new String(tr("Permanently delete note selected note?"));
4666 if (QMessageBox.question(this, "Confirmation", msg,
4667 QMessageBox.StandardButton.Yes,
4668 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4672 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4673 selectedNoteGUIDs.add(currentNoteGuid);
4674 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4675 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4676 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4677 if (modelIndex != null) {
4678 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4679 String tableGuid = (String)ix.values().toArray()[0];
4680 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4681 listManager.getNoteTableModel().removeRow(j);
4686 listManager.expungeNote(selectedNoteGUIDs.get(i));
4689 currentNoteGuid = "";
4690 listManager.loadNotesIndex();
4691 noteIndexUpdated(false);
4692 refreshEvernoteNote(true);
4693 scrollToGuid(currentNoteGuid);
4694 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4697 @SuppressWarnings("unused")
4698 private void addNote() {
4699 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4700 // browserWindow.setEnabled(true);
4701 browserWindow.setReadOnly(false);
4703 Calendar currentTime = new GregorianCalendar();
4704 StringBuffer noteString = new StringBuffer(100);
4705 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4706 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4709 if (Global.overrideDefaultFont()) {
4710 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4711 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4712 noteString.append("<br clear=\"none\" />\n");
4713 noteString.append("</span>\n</font>\n");
4715 noteString.append("<br clear=\"none\" />\n");
4716 noteString.append("</en-note>");
4718 Long l = new Long(currentTime.getTimeInMillis());
4719 String randint = new String(Long.toString(l));
4721 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4723 // for the first non-archived notebook. Finally, if nothing else we
4724 // pick the first notebook in the list.
4725 String notebook = null;
4726 listManager.getNotebookIndex().get(0).getGuid();
4727 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4728 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4729 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4730 notebook = currentSelectedNotebook.text(2);
4732 boolean found = false;
4733 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4734 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4735 boolean match = false;
4736 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4737 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4739 j = listManager.getArchiveNotebookIndex().size();
4743 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4744 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4746 // Now we have a list of good notebooks, so we can look for the default
4748 for (int i=0; i<goodNotebooks.size(); i++) {
4749 if (goodNotebooks.get(i).isDefaultNotebook()) {
4750 notebook = goodNotebooks.get(i).getGuid();
4752 i = goodNotebooks.size();
4756 if (goodNotebooks.size() > 0 && !found)
4757 notebook = goodNotebooks.get(0).getGuid();
4760 notebook = listManager.getNotebookIndex().get(0).getGuid();
4763 Note newNote = new Note();
4764 newNote.setUpdateSequenceNum(0);
4765 newNote.setGuid(randint);
4766 newNote.setNotebookGuid(notebook);
4767 newNote.setTitle("Untitled Note");
4768 newNote.setContent(noteString.toString());
4769 newNote.setDeleted(0);
4770 newNote.setCreated(System.currentTimeMillis());
4771 newNote.setUpdated(System.currentTimeMillis());
4772 newNote.setActive(true);
4773 NoteAttributes na = new NoteAttributes();
4774 na.setLatitude(0.0);
4775 na.setLongitude(0.0);
4776 na.setAltitude(0.0);
4777 newNote.setAttributes(new NoteAttributes());
4778 newNote.setTagGuids(new ArrayList<String>());
4779 newNote.setTagNames(new ArrayList<String>());
4781 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4782 if (Global.newNoteWithSelectedTags()) {
4783 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4784 QTreeWidgetItem currentSelection;
4785 for (int i=0; i<selections.size(); i++) {
4786 currentSelection = selections.get(i);
4787 newNote.getTagGuids().add(currentSelection.text(2));
4788 newNote.getTagNames().add(currentSelection.text(0));
4792 conn.getNoteTable().addNote(newNote, true);
4793 NoteMetadata metadata = new NoteMetadata();
4794 metadata.setGuid(newNote.getGuid());
4795 metadata.setDirty(true);
4796 listManager.addNote(newNote, metadata);
4797 // noteTableView.insertRow(newNote, true, -1);
4799 currentNote = newNote;
4800 currentNoteGuid = currentNote.getGuid();
4801 noteTableView.clearSelection();
4802 refreshEvernoteNote(true);
4803 listManager.countNotebookResults(listManager.getNoteIndex());
4804 browserWindow.titleLabel.setFocus();
4805 browserWindow.titleLabel.selectAll();
4806 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4808 // If the window is hidden, then we want to popup this in an external window &
4812 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4814 // Restore a note from the trash;
4815 @SuppressWarnings("unused")
4816 private void restoreNote() {
4818 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4819 selectedNoteGUIDs.add(currentNoteGuid);
4820 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4821 listManager.restoreNote(selectedNoteGUIDs.get(i));
4823 currentNoteGuid = "";
4824 listManager.loadNotesIndex();
4825 noteIndexUpdated(false);
4828 // Search a note for specific txt
4829 @SuppressWarnings("unused")
4830 private void findText() {
4832 find.setFocusOnTextField();
4834 @SuppressWarnings("unused")
4835 private void doFindText() {
4836 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4839 @SuppressWarnings("unused")
4840 private void updateNoteTitle(String guid, String title) {
4841 listManager.setNoteSynchronized(guid, false);
4843 // Signal received that note content has changed. Normally we just need the guid to remove
4844 // it from the cache.
4845 @SuppressWarnings("unused")
4846 private void invalidateNoteCache(String guid, String content) {
4847 noteCache.remove(guid);
4848 refreshEvernoteNote(true);
4850 // Signal received that a note guid has changed
4851 @SuppressWarnings("unused")
4852 private void noteGuidChanged(String oldGuid, String newGuid) {
4853 if (noteCache.containsKey(oldGuid)) {
4854 if (!oldGuid.equals(currentNoteGuid)) {
4855 String cache = noteCache.get(oldGuid);
4856 noteCache.put(newGuid, cache);
4857 noteCache.remove(oldGuid);
4859 noteCache.remove(oldGuid);
4860 noteCache.put(newGuid, browserWindow.getContent());
4864 listManager.updateNoteGuid(oldGuid, newGuid, false);
4865 if (currentNoteGuid.equals(oldGuid)) {
4866 if (currentNote != null)
4867 currentNote.setGuid(newGuid);
4868 currentNoteGuid = newGuid;
4871 if (externalWindows.containsKey(oldGuid)) {
4872 ExternalBrowse b = externalWindows.get(oldGuid);
4873 externalWindows.remove(oldGuid);
4874 b.getBrowserWindow().getNote().setGuid(newGuid);
4875 externalWindows.put(newGuid, b);
4878 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4879 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4880 noteTableView.proxyModel.addGuid(newGuid, listManager.getNoteMetadata().get(newGuid));
4881 i=listManager.getNoteIndex().size();
4885 if (listManager.getNoteTableModel().metaData.containsKey(oldGuid)) {
4886 NoteMetadata meta = listManager.getNoteTableModel().metaData.get(oldGuid);
4887 listManager.getNoteTableModel().metaData.put(newGuid, meta);
4888 listManager.getNoteTableModel().metaData.remove(oldGuid);
4892 // Toggle the note editor button bar
4893 private void toggleEditorButtonBar() {
4894 if (browserWindow.buttonsVisible) {
4895 browserWindow.hideButtons();
4896 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4897 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4899 browserWindow.buttonsVisible = true;
4900 showEditorButtons(browserWindow);
4902 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4904 // Show editor buttons
4905 private void showEditorButtons(BrowserWindow browser) {
4906 browser.buttonLayout.setVisible(true);
4907 browser.undoAction.setVisible(false);
4909 browser.undoButton.setVisible(false);
4911 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4912 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4913 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4914 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4915 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4916 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4917 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4918 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4919 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4920 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4921 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4922 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4923 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4924 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4925 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4926 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4927 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4928 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4929 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4930 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4931 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4932 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4933 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4935 private void duplicateNote(String guid) {
4937 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4938 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4939 oldNote.setContent(conn.getNoteTable().getNoteContentNoUTFConversion(guid));
4940 oldNote.setResources(resList);
4941 duplicateNote(oldNote);
4943 private void duplicateNote(Note oldNote) {
4945 // Now that we have a good notebook guid, we need to move the conflicting note
4946 // to the local notebook
4947 Calendar currentTime = new GregorianCalendar();
4948 Long l = new Long(currentTime.getTimeInMillis());
4949 String newGuid = new String(Long.toString(l));
4951 // Note newNote = oldNote.deepCopy();
4952 Note newNote = (Note)Global.deepCopy(oldNote);
4953 newNote.setUpdateSequenceNum(0);
4954 newNote.setGuid(newGuid);
4955 newNote.setDeleted(0);
4956 newNote.setActive(true);
4959 List<String> tagNames = new ArrayList<String>();
4960 List<String> tagGuids = new ArrayList<String>();;
4961 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4962 tagNames.add(oldNote.getTagNames().get(i));
4963 tagGuids.add(oldNote.getTagGuids().get(i));
4966 // Sort note Tags to make them look nice
4967 for (int i=0; i<tagNames.size()-1; i++) {
4968 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4969 String n1 = tagNames.get(i);
4970 String n2 = tagNames.get(i+1);
4971 tagNames.set(i, n2);
4972 tagNames.set(i+1, n1);
4975 newNote.setTagGuids(tagGuids);
4976 newNote.setTagNames(tagNames);
4978 // Add tag guids to note
4981 // Duplicate resources
4982 List<Resource> resList = oldNote.getResources();
4983 if (resList == null)
4984 resList = new ArrayList<Resource>();
4986 for (int i=0; i<resList.size(); i++) {
4988 while (l == prevGuid) {
4989 currentTime = new GregorianCalendar();
4990 l = new Long(currentTime.getTimeInMillis());
4993 String newResGuid = new String(Long.toString(l));
4994 resList.get(i).setNoteGuid(newGuid);
4995 resList.get(i).setGuid(newResGuid);
4996 resList.get(i).setUpdateSequenceNum(0);
4997 resList.get(i).setActive(true);
4998 conn.getNoteTable().noteResourceTable.saveNoteResource(
4999 (Resource)Global.deepCopy(resList.get(i)), true);
5001 newNote.setResources(resList);
5003 // Add note to the database
5004 conn.getNoteTable().addNote(newNote, true);
5005 NoteMetadata metaData = new NoteMetadata();
5006 NoteMetadata oldMeta = listManager.getNoteMetadata().get(oldNote.getGuid());
5007 metaData.copy(oldMeta);
5008 metaData.setGuid(newNote.getGuid());
5009 listManager.addNote(newNote, metaData);
5010 noteTableView.insertRow(newNote, metaData, true, -1);
5011 currentNoteGuid = newNote.getGuid();
5012 currentNote = newNote;
5013 refreshEvernoteNote(true);
5014 listManager.countNotebookResults(listManager.getNoteIndex());
5018 @SuppressWarnings("unused")
5019 private void allNotes() {
5020 clearAttributeFilter();
5021 clearNotebookFilter();
5022 clearSavedSearchFilter();
5025 searchField.clear();
5026 if (Global.mimicEvernoteInterface) {
5027 notebookTree.selectGuid("");
5029 notebookTreeSelection();
5030 refreshEvernoteNote(true);
5033 @SuppressWarnings("unused")
5034 private void mergeNotes() {
5035 logger.log(logger.HIGH, "Merging notes");
5038 String masterGuid = null;
5039 List<String> sources = new ArrayList<String>();
5041 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
5042 int r = noteTableView.selectionModel().selectedRows().get(i).row();
5043 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
5044 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5046 masterGuid = (String)ix.values().toArray()[0];
5048 sources.add((String)ix.values().toArray()[0]);
5051 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
5052 logger.log(logger.EXTREME, "Children count: "+sources.size());
5053 mergeNoteContents(masterGuid, sources);
5054 currentNoteGuid = masterGuid;
5055 noteIndexUpdated(false);
5056 refreshEvernoteNote(true);
5059 private void mergeNoteContents(String targetGuid, List<String> sources) {
5060 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
5061 String newContent = target.getContent();
5062 newContent = newContent.replace("</en-note>", "<br></br>");
5064 for (int i=0; i<sources.size(); i++) {
5065 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
5066 if (source.isSetTitle()) {
5067 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
5069 String sourceContent = source.getContent();
5070 logger.log(logger.EXTREME, "Merging contents into note");
5071 logger.log(logger.EXTREME, sourceContent);
5072 logger.log(logger.EXTREME, "End of content");
5073 int startOfNote = sourceContent.indexOf("<en-note>");
5074 sourceContent = sourceContent.substring(startOfNote+9);
5075 int endOfNote = sourceContent.indexOf("</en-note>");
5076 sourceContent = sourceContent.substring(0,endOfNote);
5077 newContent = newContent + sourceContent;
5078 logger.log(logger.EXTREME, "New note content");
5079 logger.log(logger.EXTREME, newContent);
5080 logger.log(logger.EXTREME, "End of content");
5081 for (int j=0; j<source.getResourcesSize(); j++) {
5082 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
5083 Resource r = source.getResources().get(j);
5084 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
5086 Calendar currentTime = new GregorianCalendar();
5087 Long l = new Long(currentTime.getTimeInMillis());
5091 while (l == prevGuid) {
5092 currentTime = new GregorianCalendar();
5093 l = new Long(currentTime.getTimeInMillis());
5095 String newResGuid = new String(Long.toString(l));
5096 newRes.setNoteGuid(targetGuid);
5097 newRes.setGuid(newResGuid);
5098 newRes.setUpdateSequenceNum(0);
5099 newRes.setActive(true);
5100 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5103 logger.log(logger.EXTREME, "Updating note");
5104 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5105 for (int i=0; i<sources.size(); i++) {
5106 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5107 listManager.deleteNote(sources.get(i));
5109 logger.log(logger.EXTREME, "Exiting merge note");
5111 // A resource within a note has had a guid change
5112 @SuppressWarnings("unused")
5113 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5114 if (oldGuid != null && !oldGuid.equals(newGuid))
5115 Global.resourceMap.put(oldGuid, newGuid);
5117 // View a thumbnail of the note
5118 public void thumbnailView() {
5120 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5121 QFile thumbnail = new QFile(thumbnailName);
5122 if (!thumbnail.exists()) {
5124 QImage img = new QImage();
5125 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5126 thumbnailViewer.setThumbnail(img);
5128 thumbnailViewer.setThumbnail(thumbnailName);
5129 if (!thumbnailViewer.isVisible())
5130 thumbnailViewer.showFullScreen();
5132 // An error happened while saving a note. Inform the user
5133 @SuppressWarnings("unused")
5134 private void saveRunnerError(String guid, String msg) {
5136 String title = "*Unknown*";
5137 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5138 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5139 title = listManager.getMasterNoteIndex().get(i).getTitle();
5140 i=listManager.getMasterNoteIndex().size();
5143 msg = tr("An error has happened while saving the note \"") +title+
5144 tr("\".\n\nThis is probably due to a document that is too complex for NixNote to process. "+
5145 "As a result, changes to the note may not be saved properly in the database."+
5146 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5147 "\nbe lost. Please review the note to recover any critical data before restarting.");
5149 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5152 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5153 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5154 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5155 // Find an idle preview object
5156 for (int i=0; i<thumbGenerators.size(); i++) {
5157 if (thumbGenerators.get(i).mutex.tryLock()) {
5158 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5159 thumbGenerators.get(i).loadContent(guid, html, zoom);
5163 if (thumbGenerators.size() >= 1) {
5164 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5168 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5169 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5170 thumbGenerators.add(preview);
5172 if (preview.mutex.tryLock()) {
5173 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5174 preview.loadContent(guid, html, zoom);
5176 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5181 //**********************************************************
5182 //**********************************************************
5183 //* Online user actions
5184 //**********************************************************
5185 //**********************************************************
5186 private void setupOnlineMenu() {
5187 if (!Global.isConnected) {
5188 menuBar.noteOnlineHistoryAction.setEnabled(false);
5189 menuBar.selectiveSyncAction.setEnabled(false);
5192 menuBar.noteOnlineHistoryAction.setEnabled(true);
5193 menuBar.selectiveSyncAction.setEnabled(true);
5196 @SuppressWarnings("unused")
5197 private void viewNoteHistory() {
5198 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5200 if (currentNote.getUpdateSequenceNum() == 0) {
5201 setMessage(tr("Note has never been synchronized."));
5202 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5206 setMessage(tr("Getting Note History"));
5208 Note currentOnlineNote = null;
5211 if (Global.isPremium())
5212 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5214 versions = new ArrayList<NoteVersionId>();
5215 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5216 } catch (EDAMUserException e) {
5217 setMessage("EDAMUserException: " +e.getMessage());
5219 } catch (EDAMSystemException e) {
5220 setMessage("EDAMSystemException: " +e.getMessage());
5222 } catch (EDAMNotFoundException e) {
5223 setMessage(tr("Note not found on server."));
5224 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5226 } catch (TException e) {
5227 setMessage("EDAMTransactionException: " +e.getMessage());
5231 // If we've gotten this far, we have a good note.
5232 if (historyWindow == null) {
5233 historyWindow = new OnlineNoteHistory(logger, conn);
5234 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5235 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5236 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5238 historyWindow.historyCombo.clear();
5240 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5241 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5243 historyWindow.setCurrent(isDirty);
5245 loadHistoryWindowContent(currentOnlineNote);
5246 historyWindow.load(versions);
5247 setMessage(tr("History retrieved"));
5249 historyWindow.exec();
5251 private Note reloadHistoryWindow(String selection) {
5253 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5254 String dateTimeFormat = new String(fmt);
5255 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5259 for (int i=0; i<versions.size(); i++) {
5260 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5261 if (versionDate.toString().equals(selection))
5265 if (index > -1 || selection.indexOf("Current") > -1) {
5266 Note historyNote = null;
5269 usn = versions.get(index).getUpdateSequenceNum();
5270 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5272 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5273 } catch (EDAMUserException e) {
5274 setMessage("EDAMUserException: " +e.getMessage());
5277 } catch (EDAMSystemException e) {
5278 setMessage("EDAMSystemException: " +e.getMessage());
5281 } catch (EDAMNotFoundException e) {
5282 setMessage("EDAMNotFoundException: " +e.getMessage());
5285 } catch (TException e) {
5286 setMessage("EDAMTransactionException: " +e.getMessage());
5292 if (historyNote != null)
5293 historyWindow.setContent(historyNote);
5299 private void loadHistoryWindowContent(Note note) {
5300 note.setUpdateSequenceNum(0);
5301 historyWindow.setContent(note);
5303 @SuppressWarnings("unused")
5304 private void restoreHistoryNoteAsNew() {
5305 setMessage(tr("Restoring as new note."));
5306 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5307 setMessage(tr("Note has been restored as a new note."));
5309 @SuppressWarnings("unused")
5310 private void restoreHistoryNote() {
5311 setMessage(tr("Restoring note."));
5312 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5313 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5316 for (int i=0; i<n.getResourcesSize(); i++) {
5317 n.getResources().get(i).setActive(true);
5318 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5320 NoteMetadata metadata = new NoteMetadata();
5321 metadata.setGuid(n.getGuid());
5322 listManager.addNote(n, metadata);
5323 conn.getNoteTable().addNote(n, true);
5324 refreshEvernoteNote(true);
5325 setMessage(tr("Note has been restored."));
5327 @SuppressWarnings("unused")
5328 private void setupSelectiveSync() {
5330 // Get a list of valid notebooks
5331 List<Notebook> notebooks = null;
5332 List<Tag> tags = null;
5333 List<LinkedNotebook> linkedNotebooks = null;
5335 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5336 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5337 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5338 } catch (EDAMUserException e) {
5339 setMessage("EDAMUserException: " +e.getMessage());
5341 } catch (EDAMSystemException e) {
5342 setMessage("EDAMSystemException: " +e.getMessage());
5344 } catch (TException e) {
5345 setMessage("EDAMTransactionException: " +e.getMessage());
5347 } catch (EDAMNotFoundException e) {
5348 setMessage("EDAMNotFoundException: " +e.getMessage());
5352 // Split up notebooks into synchronized & non-synchronized
5353 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5354 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5356 for (int i=notebooks.size()-1; i>=0; i--) {
5357 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5358 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5359 ignoredBooks.add(notebooks.get(i));
5360 j=dbIgnoredNotebooks.size();
5365 // split up tags into synchronized & non-synchronized
5366 List<Tag> ignoredTags = new ArrayList<Tag>();
5367 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5369 for (int i=tags.size()-1; i>=0; i--) {
5370 for (int j=0; j<dbIgnoredTags.size(); j++) {
5371 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5372 ignoredTags.add(tags.get(i));
5373 j=dbIgnoredTags.size();
5378 // split up linked notebooks into synchronized & non-synchronized
5379 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5380 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5381 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5382 String notebookGuid = linkedNotebooks.get(i).getGuid();
5383 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5384 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5385 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5386 j=dbIgnoredLinkedNotebooks.size();
5391 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5393 if (!ignore.okClicked())
5398 // Clear out old notebooks & add the new ones
5399 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5400 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5401 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5404 List<String> newNotebooks = new ArrayList<String>();
5405 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5406 String text = ignore.getIgnoredBookList().takeItem(i).text();
5407 for (int j=0; j<notebooks.size(); j++) {
5408 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5409 Notebook n = notebooks.get(j);
5410 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5412 newNotebooks.add(n.getGuid());
5417 // Clear out old tags & add new ones
5418 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5419 for (int i=0; i<oldIgnoreTags.size(); i++) {
5420 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5423 List<String> newTags = new ArrayList<String>();
5424 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5425 String text = ignore.getIgnoredTagList().takeItem(i).text();
5426 for (int j=0; j<tags.size(); j++) {
5427 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5428 Tag t = tags.get(j);
5429 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5430 newTags.add(t.getGuid());
5436 // Clear out old tags & add new ones
5437 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5438 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5439 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5442 List<String> newLinked = new ArrayList<String>();
5443 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5444 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5445 for (int j=0; j<linkedNotebooks.size(); j++) {
5446 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5447 LinkedNotebook t = linkedNotebooks.get(j);
5448 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5449 newLinked.add(t.getGuid());
5450 j=linkedNotebooks.size();
5455 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5461 //**********************************************************
5462 //**********************************************************
5463 //* XML Modifying methods
5464 //**********************************************************
5465 //**********************************************************
5466 // An error has happended fetching a resource. let the user know
5467 private void resourceErrorMessage() {
5471 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5472 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5473 "In a perfect world this wouldn't happen, but it has.\n" +
5474 "It is embarasing when a program like me, designed to save all your\n"+
5475 "precious data, has a problem finding data.\n\n" +
5476 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5477 "In the mean time, I'm not going to let you make changes to this note.\n" +
5478 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5479 "this note on the Evernote servers. Sorry."+
5480 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5482 browserWindow.setReadOnly(true);
5489 //**********************************************************
5490 //**********************************************************
5492 //**********************************************************
5493 //**********************************************************
5494 // We should now do a sync with Evernote
5495 private void syncTimer() {
5496 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5497 syncRunner.syncNeeded = true;
5498 syncRunner.disableUploads = Global.disableUploads;
5500 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5502 private void syncStart() {
5503 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5505 if (!syncRunning && Global.isConnected) {
5506 syncRunner.setConnected(true);
5507 syncRunner.setKeepRunning(Global.keepRunning);
5508 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5510 if (syncThreadsReady > 0) {
5511 thumbnailRunner.interrupt = true;
5512 saveNoteIndexWidth();
5513 saveNoteColumnPositions();
5514 if (syncRunner.addWork("SYNC")) {
5516 syncRunner.syncNeeded = true;
5521 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5523 @SuppressWarnings("unused")
5524 private void syncThreadComplete(Boolean refreshNeeded) {
5525 setMessage(tr("Finalizing Synchronization"));
5527 syncRunning = false;
5528 syncRunner.syncNeeded = false;
5529 synchronizeAnimationTimer.stop();
5530 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5532 if (currentNote == null) {
5533 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5535 listManager.refreshNoteMetadata();
5536 noteIndexUpdated(true);
5537 noteTableView.selectionModel().blockSignals(true);
5538 scrollToGuid(currentNoteGuid);
5539 noteTableView.selectionModel().blockSignals(false);
5540 refreshEvernoteNote(false);
5541 scrollToGuid(currentNoteGuid);
5544 // Check to see if there were any shared notebook errors
5545 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5546 String guid = syncRunner.errorSharedNotebooks.get(0);
5547 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5548 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5549 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5551 if (syncDialog.okPressed()) {
5552 if (syncDialog.doNothing.isChecked()) {
5553 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5556 if (syncDialog.deleteNotebook.isChecked()) {
5557 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5558 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5559 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5560 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5568 // Finalize the synchronization
5569 if (!syncRunner.error)
5570 setMessage(tr("Synchronization Complete"));
5572 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5573 logger.log(logger.MEDIUM, "Sync complete.");
5575 public void saveUploadAmount(long t) {
5576 Global.saveUploadAmount(t);
5578 public void saveUserInformation(User user) {
5579 Global.saveUserInformation(user);
5581 public void saveEvernoteUpdateCount(int i) {
5582 Global.saveEvernoteUpdateCount(i);
5584 public void refreshLists() {
5585 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5587 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5588 tagIndexUpdated(true);
5589 notebookIndexUpdated();
5590 savedSearchIndexUpdated();
5591 listManager.loadNotesIndex();
5593 noteTableView.selectionModel().blockSignals(true);
5594 noteIndexUpdated(true);
5595 noteTableView.selectionModel().blockSignals(false);
5596 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5600 @SuppressWarnings("unused")
5601 private void authTimer() {
5602 Calendar cal = Calendar.getInstance();
5604 // If we are not connected let's get out of here
5605 if (!Global.isConnected)
5608 // If this is the first time through, then we need to set this
5609 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5610 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5612 // long now = new Date().getTime();
5613 // if (now > Global.authRefreshTime && Global.isConnected) {
5614 syncRunner.authRefreshNeeded = true;
5618 @SuppressWarnings("unused")
5619 private void authRefreshComplete(boolean goodSync) {
5620 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5621 Global.isConnected = syncRunner.isConnected;
5623 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5624 authTimer.start(1000*60*15);
5625 logger.log(logger.LOW, "Authentication token has been renewed");
5626 // setMessage("Authentication token has been renewed.");
5628 authTimer.start(1000*60*5);
5629 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5630 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5632 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5636 @SuppressWarnings("unused")
5637 private synchronized void indexTimer() {
5638 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5641 if (!indexDisabled && indexRunner.idle) {
5642 thumbnailRunner.interrupt = true;
5643 indexRunner.addWork("SCAN");
5645 logger.log(logger.EXTREME, "Leaving NixNote index timer");
5648 @SuppressWarnings("unused")
5649 private void indexStarted() {
5650 setMessage(tr("Indexing notes"));
5652 @SuppressWarnings("unused")
5653 private void indexComplete() {
5654 setMessage(tr("Index complete"));
5656 @SuppressWarnings("unused")
5657 private synchronized void toggleNoteIndexing() {
5658 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5659 indexDisabled = !indexDisabled;
5661 setMessage(tr("Indexing is now enabled."));
5663 setMessage(tr("Indexing is now disabled."));
5664 menuBar.disableIndexing.setChecked(indexDisabled);
5665 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5668 @SuppressWarnings("unused")
5669 private void threadMonitorCheck() {
5674 alive = listManager.threadCheck(Global.tagCounterThreadId);
5677 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5678 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died. I recommend "+
5679 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5680 disableTagThreadCheck = true;
5685 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5687 notebookThreadDeadCount++;
5688 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5689 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died. I recommend "+
5690 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5691 disableNotebookThreadCheck=true;
5694 notebookThreadDeadCount=0;
5696 alive = listManager.threadCheck(Global.trashCounterThreadId);
5699 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5700 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died. I recommend "+
5701 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5702 disableTrashThreadCheck = true;
5707 alive = listManager.threadCheck(Global.saveThreadId);
5709 saveThreadDeadCount++;
5710 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5711 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died. I recommend "+
5712 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5713 disableSaveThreadCheck = true;
5716 saveThreadDeadCount=0;
5718 if (!syncThread.isAlive()) {
5719 syncThreadDeadCount++;
5720 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5721 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died. I recommend "+
5722 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5723 disableSyncThreadCheck = true;
5726 syncThreadDeadCount=0;
5728 if (!indexThread.isAlive()) {
5729 indexThreadDeadCount++;
5730 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5731 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died. I recommend "+
5732 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5733 disableIndexThreadCheck = true;
5736 indexThreadDeadCount=0;
5741 private void thumbnailTimer() {
5742 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5743 thumbnailRunner.addWork("SCAN");
5747 //**************************************************
5748 //* Backup & Restore
5749 //**************************************************
5750 @SuppressWarnings("unused")
5751 private void databaseBackup() {
5752 QFileDialog fd = new QFileDialog(this);
5753 fd.setFileMode(FileMode.AnyFile);
5754 fd.setConfirmOverwrite(true);
5755 fd.setWindowTitle(tr("Backup Database"));
5756 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5757 fd.setAcceptMode(AcceptMode.AcceptSave);
5758 if (saveLastPath == null || saveLastPath.equals(""))
5759 fd.setDirectory(System.getProperty("user.home"));
5761 fd.setDirectory(saveLastPath);
5762 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5768 saveLastPath = fd.selectedFiles().get(0);
5769 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5770 setMessage(tr("Backing up database"));
5772 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5774 ExportData noteWriter = new ExportData(conn, true);
5775 String fileName = fd.selectedFiles().get(0);
5777 if (!fileName.endsWith(".nnex"))
5778 fileName = fileName +".nnex";
5779 noteWriter.exportData(fileName);
5780 setMessage(tr("Database backup completed."));
5785 @SuppressWarnings("unused")
5786 private void databaseRestore() {
5787 if (QMessageBox.question(this, tr("Confirmation"),
5788 tr("This is used to restore a database from backups.\n" +
5789 "It is HIGHLY recommened that this only be used to populate\n" +
5790 "an empty database. Restoring into a database that\n already has data" +
5791 " can cause problems.\n\nAre you sure you want to continue?"),
5792 QMessageBox.StandardButton.Yes,
5793 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5798 QFileDialog fd = new QFileDialog(this);
5799 fd.setFileMode(FileMode.ExistingFile);
5800 fd.setConfirmOverwrite(true);
5801 fd.setWindowTitle(tr("Restore Database"));
5802 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5803 fd.setAcceptMode(AcceptMode.AcceptOpen);
5804 if (saveLastPath == null || saveLastPath.equals(""))
5805 fd.setDirectory(System.getProperty("user.home"));
5807 fd.setDirectory(saveLastPath);
5808 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5814 saveLastPath = fd.selectedFiles().get(0);
5815 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5817 setMessage(tr("Restoring database"));
5818 ImportData noteReader = new ImportData(conn, true);
5819 noteReader.importData(fd.selectedFiles().get(0));
5821 if (noteReader.lastError != 0) {
5822 setMessage(noteReader.getErrorMessage());
5823 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5828 listManager.loadNoteTitleColors();
5830 refreshEvernoteNote(true);
5831 setMessage(tr("Database has been restored."));
5834 @SuppressWarnings("unused")
5835 private void exportNotes() {
5836 QFileDialog fd = new QFileDialog(this);
5837 fd.setFileMode(FileMode.AnyFile);
5838 fd.setConfirmOverwrite(true);
5839 fd.setWindowTitle(tr("Backup Database"));
5840 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5841 fd.setAcceptMode(AcceptMode.AcceptSave);
5842 fd.setDirectory(System.getProperty("user.home"));
5843 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5849 setMessage(tr("Exporting Notes"));
5852 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5853 selectedNoteGUIDs.add(currentNoteGuid);
5855 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5856 String fileName = fd.selectedFiles().get(0);
5858 if (!fileName.endsWith(".nnex"))
5859 fileName = fileName +".nnex";
5860 noteWriter.exportData(fileName);
5861 setMessage(tr("Export completed."));
5867 @SuppressWarnings("unused")
5868 private void importNotes() {
5869 QFileDialog fd = new QFileDialog(this);
5870 fd.setFileMode(FileMode.ExistingFile);
5871 fd.setConfirmOverwrite(true);
5872 fd.setWindowTitle(tr("Import Notes"));
5873 fd.setFilter(tr("NixNote Export (*.nnex);;Evernote Export (*.enex);;All Files (*.*)"));
5874 fd.setAcceptMode(AcceptMode.AcceptOpen);
5875 if (saveLastPath == null || saveLastPath.equals(""))
5876 fd.setDirectory(System.getProperty("user.home"));
5878 fd.setDirectory(saveLastPath);
5879 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5885 setMessage(tr("Importing Notes"));
5888 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5889 selectedNoteGUIDs.add(currentNoteGuid);
5891 String fileName = fd.selectedFiles().get(0);
5892 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5894 if (fileName.endsWith(".nnex")) {
5895 ImportData noteReader = new ImportData(conn, false);
5896 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5897 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5899 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5901 noteReader.importData(fileName);
5903 if (noteReader.lastError != 0) {
5904 setMessage(noteReader.getErrorMessage());
5905 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5910 if (fileName.endsWith(".enex")) {
5911 ImportEnex noteReader = new ImportEnex(conn, false);
5912 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5913 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5915 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5918 if (QMessageBox.question(this, tr("Confirmation"),
5919 tr("Create new tags from import?"),
5920 QMessageBox.StandardButton.Yes,
5921 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
5922 noteReader.createNewTags = true;
5924 noteReader.createNewTags = false;
5926 noteReader.importData(fileName);
5928 if (noteReader.lastError != 0) {
5929 setMessage(noteReader.getErrorMessage());
5930 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5937 listManager.loadNoteTitleColors();
5939 refreshEvernoteNote(false);
5940 setMessage(tr("Notes have been imported."));
5943 setMessage(tr("Import completed."));
5950 //**************************************************
5951 //* Duplicate a note
5952 //**************************************************
5953 @SuppressWarnings("unused")
5954 private void duplicateNote() {
5956 duplicateNote(currentNoteGuid);
5959 //**************************************************
5960 //* Action from when a user clicks Copy As URL
5961 //**************************************************
5962 @SuppressWarnings("unused")
5963 private void copyAsUrlClicked() {
5964 QClipboard clipboard = QApplication.clipboard();
5965 QMimeData mime = new QMimeData();
5967 mime.setText(currentNoteGuid);
5968 List<QUrl> urls = new ArrayList<QUrl>();
5970 // Start building the URL
5971 User user = Global.getUserInformation();
5973 // Check that we have everything we need
5974 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
5975 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
5977 if (!warning.neverSynchronize())
5980 Global.setBypassSynchronizationWarning(true);
5981 user.setShardId("s0");
5987 // Start building a list of URLs based upon the selected notes
5988 noteTableView.showColumn(Global.noteTableGuidPosition);
5990 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
5991 if (!Global.isColumnVisible("guid"))
5992 noteTableView.hideColumn(Global.noteTableGuidPosition);
5994 // Check that the note is either synchronized, or in a local notebook
5995 for (int i=0; i<selections.size(); i++) {
5997 int row = selections.get(i).row();
5998 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5999 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6000 String selectedGuid = (String)ix.values().toArray()[0];
6002 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6003 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
6004 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
6005 "new notes to a local notebook."));
6010 // Start building the URLs
6011 for (int i=0; i<selections.size(); i++) {
6013 int row = selections.get(i).row();
6014 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
6015 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6016 String selectedGuid = (String)ix.values().toArray()[0];
6017 mime.setText(selectedGuid);
6021 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6022 if (selectedNote.getUpdateSequenceNum() > 0) {
6026 gid = "00000000-0000-0000-0000-000000000000";
6029 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
6031 urls.add(new QUrl(url));
6034 clipboard.setMimeData(mime);
6038 //**************************************************
6040 //**************************************************
6041 public void setupFolderImports() {
6042 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
6044 if (importKeepWatcher == null)
6045 importKeepWatcher = new QFileSystemWatcher();
6046 if (importDeleteWatcher == null) {
6047 importDeleteWatcher = new QFileSystemWatcher();
6048 for (int i=0; i<records.size(); i++) {
6049 if (!records.get(i).keep)
6050 folderImportDelete(records.get(i).folder);
6056 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
6057 for (int i=0; i<records.size(); i++) {
6058 if (records.get(i).keep)
6059 importKeepWatcher.addPath(records.get(i).folder);
6061 importDeleteWatcher.addPath(records.get(i).folder);
6064 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
6065 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
6067 // Look at the files already there so we don't import them again if a new file is created
6068 if (importedFiles == null) {
6069 importedFiles = new ArrayList<String>();
6070 for (int j=0; j<records.size(); j++) {
6071 QDir dir = new QDir(records.get(j).folder);
6072 List<QFileInfo> list = dir.entryInfoList();
6073 for (int k=0; k<list.size(); k++) {
6074 if (list.get(k).isFile())
6075 importedFiles.add(list.get(k).absoluteFilePath());
6080 public void folderImport() {
6081 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
6082 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
6084 if (!dialog.okClicked())
6087 // We have some sort of update.
6088 if (importKeepWatcher.directories().size() > 0)
6089 importKeepWatcher.removePaths(importKeepWatcher.directories());
6090 if (importDeleteWatcher.directories().size() > 0)
6091 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
6093 conn.getWatchFolderTable().expungeAll();
6094 // Start building from the table
6095 for (int i=0; i<dialog.table.rowCount(); i++) {
6096 QTableWidgetItem item = dialog.table.item(i, 0);
6097 String dir = item.text();
6098 item = dialog.table.item(i, 1);
6099 String notebook = item.text();
6100 item = dialog.table.item(i, 2);
6102 if (item.text().equalsIgnoreCase("Keep"))
6107 String guid = conn.getNotebookTable().findNotebookByName(notebook);
6108 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
6110 setupFolderImports();
6113 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
6115 String whichOS = System.getProperty("os.name");
6116 if (whichOS.contains("Windows"))
6117 dirName = dirName.replace('/','\\');
6119 FileImporter importer = new FileImporter(logger, conn);
6121 QDir dir = new QDir(dirName);
6122 List<QFileInfo> list = dir.entryInfoList();
6123 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6125 for (int i=0; i<list.size(); i++){
6127 boolean redundant = false;
6128 // Check if we've already imported this one or if it existed before
6129 for (int j=0; j<importedFiles.size(); j++) {
6130 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6135 importer.setFileInfo(list.get(i));
6136 importer.setFileName(list.get(i).absoluteFilePath());
6139 if (list.get(i).isFile() && importer.isValidType()) {
6141 if (!importer.importFile()) {
6142 // If we can't get to the file, it is probably locked. We'll try again later.
6143 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6144 importFilesKeep.add(list.get(i).absoluteFilePath());
6148 Note newNote = importer.getNote();
6149 newNote.setNotebookGuid(notebook);
6150 newNote.setTitle(dir.at(i));
6151 NoteMetadata metadata = new NoteMetadata();
6152 metadata.setDirty(true);
6153 metadata.setGuid(newNote.getGuid());
6154 listManager.addNote(newNote, metadata);
6155 conn.getNoteTable().addNote(newNote, true);
6156 noteTableView.insertRow(newNote, metadata, true, -1);
6157 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6158 listManager.countNotebookResults(listManager.getNoteIndex());
6159 importedFiles.add(list.get(i).absoluteFilePath());
6167 public void folderImportDelete(String dirName) {
6169 String whichOS = System.getProperty("os.name");
6170 if (whichOS.contains("Windows"))
6171 dirName = dirName.replace('/','\\');
6173 FileImporter importer = new FileImporter(logger, conn);
6174 QDir dir = new QDir(dirName);
6175 List<QFileInfo> list = dir.entryInfoList();
6176 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6178 for (int i=0; i<list.size(); i++){
6179 importer.setFileInfo(list.get(i));
6180 importer.setFileName(list.get(i).absoluteFilePath());
6182 if (list.get(i).isFile() && importer.isValidType()) {
6184 if (!importer.importFile()) {
6185 // If we can't get to the file, it is probably locked. We'll try again later.
6186 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6187 importFilesKeep.add(list.get(i).absoluteFilePath());
6191 Note newNote = importer.getNote();
6192 newNote.setNotebookGuid(notebook);
6193 newNote.setTitle(dir.at(i));
6194 NoteMetadata metadata = new NoteMetadata();
6195 metadata.setDirty(true);
6196 metadata.setGuid(newNote.getGuid());
6197 listManager.addNote(newNote, metadata);
6198 conn.getNoteTable().addNote(newNote, true);
6199 noteTableView.insertRow(newNote, metadata, true, -1);
6200 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6201 listManager.countNotebookResults(listManager.getNoteIndex());
6202 dir.remove(dir.at(i));
6208 //**************************************************
6210 //**************************************************
6211 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6212 logger.log(logger.HIGH, "Entering exernalFileEdited");
6214 // Strip URL prefix and base dir path
6215 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6216 String name = fileName.replace(dPath, "");
6217 int pos = name.lastIndexOf('.');
6220 guid = guid.substring(0,pos);
6222 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6224 guid = name.substring(0, pos);
6227 QFile file = new QFile(fileName);
6228 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6229 // If we can't get to the file, it is probably locked. We'll try again later.
6230 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6231 externalFiles.add(fileName);
6234 QByteArray binData = file.readAll();
6236 if (binData.size() == 0) {
6237 // If we can't get to the file, it is probably locked. We'll try again later.
6238 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6239 externalFiles.add(fileName);
6243 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6245 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6246 if (r == null || r.getData() == null || r.getData().getBody() == null)
6248 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6249 MessageDigest md = MessageDigest.getInstance("MD5");
6250 md.update(binData.toByteArray());
6251 byte[] hash = md.digest();
6252 String newHash = Global.byteArrayToHexString(hash);
6253 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6254 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6256 if (externalWindows.containsKey(r.getNoteGuid())) {
6257 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6258 r.getGuid(), oldHash, newHash);
6260 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6261 Data data = r.getData();
6262 data.setBody(binData.toByteArray());
6263 data.setBodyHash(hash);
6264 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6266 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6268 if (r.getNoteGuid().equals(currentNoteGuid)) {
6269 QWebSettings.setMaximumPagesInCache(0);
6270 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6271 refreshEvernoteNote(true);
6272 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6275 if (externalWindows.containsKey(r.getNoteGuid())) {
6276 QWebSettings.setMaximumPagesInCache(0);
6277 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6278 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6282 logger.log(logger.HIGH, "Exiting externalFielEdited");
6284 // This is a timer event that tries to save any external files that were edited. This
6285 // is only needed if we couldn't save a file earlier.
6286 public void externalFileEditedSaver() {
6287 for (int i=externalFiles.size()-1; i>=0; i--) {
6289 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6290 externalFileEdited(externalFiles.get(i));
6291 externalFiles.remove(i);
6292 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6294 for (int i=0; i<importFilesKeep.size(); i++) {
6296 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6297 folderImportKeep(importFilesKeep.get(i));
6298 importFilesKeep.remove(i);
6299 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6301 for (int i=0; i<importFilesDelete.size(); i++) {
6302 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6303 folderImportDelete(importFilesDelete.get(i));
6304 importFilesDelete.remove(i);
6311 // If an attachment on the current note was edited, we need to update the current notes's hash
6312 // Update a note content's hash. This happens if a resource is edited outside of NN
6313 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6314 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6316 for (;position>-1;) {
6317 endPos = browser.getContent().indexOf(">", position+1);
6318 String oldSegment = browser.getContent().substring(position,endPos);
6319 int hashPos = oldSegment.indexOf("hash=\"");
6320 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6321 String hash = oldSegment.substring(hashPos+6, hashEnd);
6322 if (hash.equalsIgnoreCase(oldHash)) {
6323 String newSegment = oldSegment.replace(oldHash, newHash);
6324 String content = browser.getContent().substring(0,position) +
6326 browser.getContent().substring(endPos);
6327 browser.setContent(new QByteArray(content));;
6330 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6335 //*************************************************
6336 //* Minimize to tray
6337 //*************************************************
6339 public void changeEvent(QEvent e) {
6340 if (e.type() == QEvent.Type.WindowStateChange) {
6341 if (isMinimized() && Global.showTrayIcon()) {
6343 QTimer.singleShot(10, this, "hide()");
6347 windowMaximized = true;
6349 windowMaximized = false;
6353 //*************************************************
6354 //* Check database userid & passwords
6355 //*************************************************
6356 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6357 Connection connection;
6360 Class.forName("org.h2.Driver");
6361 } catch (ClassNotFoundException e1) {
6362 e1.printStackTrace();
6367 String passwordString = null;
6368 if (cypherPassword==null || cypherPassword.trim().equals(""))
6369 passwordString = userPassword;
6371 passwordString = cypherPassword+" "+userPassword;
6372 connection = DriverManager.getConnection(url,userid,passwordString);
6373 } catch (SQLException e) {
6378 } catch (SQLException e) {
6379 e.printStackTrace();
6384 //*************************************************
6385 //* View / Hide source HTML for a note
6386 //*************************************************
6387 public void viewSource() {
6388 browserWindow.showSource(menuBar.viewSource.isChecked());
6390 //*************************************************
6391 // Block the program. This is used for things
6392 // like async web calls.
6393 //*************************************************
6394 @SuppressWarnings("unused")
6395 private void blockApplication(BrowserWindow b) {
6396 // Block all signals
6400 blockTimer = new QTimer();
6401 blockTimer.setSingleShot(true);
6402 blockTimer.setInterval(15000);
6403 blockTimer.timeout.connect(this, "unblockApplication()");
6408 @SuppressWarnings("unused")
6409 private void unblockApplication() {
6411 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6412 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6413 blockingWindow.unblockTime = -1;
6414 blockingWindow.awaitingHttpResponse = false;
6416 blockingWindow = null;
6417 blockSignals(false);