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.filters.FilterEditorNotebooks;
168 import cx.fbn.nevernote.filters.FilterEditorTags;
169 import cx.fbn.nevernote.gui.AttributeTreeWidget;
170 import cx.fbn.nevernote.gui.BrowserWindow;
171 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
172 import cx.fbn.nevernote.gui.ExternalBrowse;
173 import cx.fbn.nevernote.gui.MainMenuBar;
174 import cx.fbn.nevernote.gui.NotebookTreeWidget;
175 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
176 import cx.fbn.nevernote.gui.SearchPanel;
177 import cx.fbn.nevernote.gui.TableView;
178 import cx.fbn.nevernote.gui.TagTreeWidget;
179 import cx.fbn.nevernote.gui.Thumbnailer;
180 import cx.fbn.nevernote.gui.TrashTreeWidget;
181 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
182 import cx.fbn.nevernote.sql.DatabaseConnection;
183 import cx.fbn.nevernote.sql.WatchFolderRecord;
184 import cx.fbn.nevernote.threads.IndexRunner;
185 import cx.fbn.nevernote.threads.SyncRunner;
186 import cx.fbn.nevernote.threads.ThumbnailRunner;
187 import cx.fbn.nevernote.utilities.AESEncrypter;
188 import cx.fbn.nevernote.utilities.ApplicationLogger;
189 import cx.fbn.nevernote.utilities.FileImporter;
190 import cx.fbn.nevernote.utilities.FileUtils;
191 import cx.fbn.nevernote.utilities.ListManager;
192 import cx.fbn.nevernote.utilities.SyncTimes;
193 import cx.fbn.nevernote.xml.ExportData;
194 import cx.fbn.nevernote.xml.ImportData;
195 import cx.fbn.nevernote.xml.NoteFormatter;
198 public class NeverNote extends QMainWindow{
200 QStatusBar statusBar; // Application status bar
202 DatabaseConnection conn;
204 MainMenuBar menuBar; // Main menu bar
205 FindDialog find; // Text search in note dialog
206 List<String> emitLog; // Messages displayed in the status bar;
207 QSystemTrayIcon trayIcon; // little tray icon
208 QMenu trayMenu; // System tray menu
209 QAction trayExitAction; // Exit the application
210 QAction trayShowAction; // toggle the show/hide action
211 QAction trayAddNoteAction; // Add a note from the system tray
212 QNetworkAccessManager versionChecker; // Used when checking for new versions
214 NotebookTreeWidget notebookTree; // List of notebooks
215 AttributeTreeWidget attributeTree; // List of note attributes
216 TagTreeWidget tagTree; // list of user created tags
217 SavedSearchTreeWidget savedSearchTree; // list of saved searches
218 TrashTreeWidget trashTree; // Trashcan
219 TableView noteTableView; // List of notes (the widget).
221 public BrowserWindow browserWindow; // Window containing browser & labels
222 public QToolBar toolBar; // The tool bar under the menu
223 QComboBox searchField; // search filter bar on the toolbar;
224 QShortcut searchShortcut; // Shortcut to search bar
225 boolean searchPerformed = false; // Search was done?
226 QuotaProgressBar quotaBar; // The current quota usage
228 ApplicationLogger logger;
229 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
230 List<String> selectedTagGUIDs; // List of selected tag GUIDs
231 List<String> selectedNoteGUIDs; // List of selected notes
232 String selectedSavedSearchGUID; // Currently selected saved searches
233 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
235 NoteFilter filter; // Note filter
236 String currentNoteGuid; // GUID of the current note
237 Note currentNote; // The currently viewed note
238 boolean noteDirty; // Has the note been changed?
239 boolean inkNote; // if this is an ink note, it is read only
240 boolean readOnly; // Is this note read-only?
243 ListManager listManager; // DB runnable task
245 List<QTemporaryFile> tempFiles; // Array of temporary files;
247 QTimer indexTimer; // timer to start the index thread
248 IndexRunner indexRunner; // thread to index notes
251 QTimer syncTimer; // Sync on an interval
252 QTimer syncDelayTimer; // Sync delay to free up database
253 SyncRunner syncRunner; // thread to do a sync.
254 QThread syncThread; // Thread which talks to evernote
255 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
256 QThread thumbnailThread; // Thread that generates pretty pictures
257 QTimer saveTimer; // Timer to save note contents
259 QTimer authTimer; // Refresh authentication
260 QTimer externalFileSaveTimer; // Save files altered externally
261 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
262 List<String> externalFiles; // External files to save later
263 List<String> importFilesKeep; // Auto-import files to save later
264 List<String> importFilesDelete; // Auto-import files to save later
266 int indexTime; // how often to try and index
267 boolean indexRunning; // Is indexing running?
268 boolean indexDisabled; // Is indexing disabled?
270 int syncThreadsReady; // number of sync threads that are free
271 int syncTime; // Sync interval
272 boolean syncRunning; // Is sync running?
273 boolean automaticSync; // do sync automatically?
274 QTreeWidgetItem attributeTreeSelected;
276 QAction prevButton; // Go to the previous item viewed
277 QAction nextButton; // Go to the next item in the history
278 QAction downButton; // Go to the next item in the list
279 QAction upButton; // Go to the prev. item in the list;
280 QAction synchronizeButton; // Synchronize with Evernote
281 QAction allNotesButton; // Reset & view all notes
282 QTimer synchronizeAnimationTimer; // Timer to change animation button
283 int synchronizeIconAngle; // Used to rotate sync icon
284 QAction printButton; // Print Button
285 QAction tagButton; // Tag edit button
286 QAction attributeButton; // Attribute information button
287 QAction emailButton; // Email button
288 QAction deleteButton; // Delete button
289 QAction newButton; // new Note Button;
290 QSpinBox zoomSpinner; // Zoom zoom
291 QAction searchClearButton; // Clear the search field
293 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
295 QSplitter mainLeftRightSplitter; // main splitter for left/right side
296 QSplitter leftSplitter1; // first left hand splitter
297 QSplitter browserIndexSplitter; // splitter between note index & note text
299 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
300 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
301 List<String> importedFiles; // History of imported files (so we don't import twice)
303 OnlineNoteHistory historyWindow; // online history window
304 List<NoteVersionId> versions; // history versions
306 QTimer threadMonitorTimer; // Timer to watch threads.
307 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
308 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
309 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
310 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
311 int tagDeadCount=0; // number of consecutive dead times for the tag thread
312 int trashDeadCount=0; // number of consecutive dead times for the trash thread
313 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
314 boolean disableTagThreadCheck=false;
315 boolean disableNotebookThreadCheck=false;
316 boolean disableTrashThreadCheck=false;
317 boolean disableSaveThreadCheck=false;
318 boolean disableSyncThreadCheck=false;
319 boolean disableIndexThreadCheck=false;
321 HashMap<String, String> noteCache; // Cash of note content
322 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
323 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
324 List<String> historyGuids; // GUIDs of previously viewed items
325 int historyPosition; // Position within the viewed items
326 boolean fromHistory; // Is this from the history queue?
327 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
328 List<Thumbnailer> thumbGenerators; // generate preview image
329 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
330 boolean encryptOnShutdown; // should I encrypt when I close?
331 boolean decryptOnShutdown; // should I decrypt on shutdown;
332 String encryptCipher; // What cipher should I use?
333 Signal0 minimizeToTray;
334 boolean windowMaximized = false; // Keep track of the window state for restores
335 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
336 List<QPixmap> syncIcons; // Array of icons used in sync animation
337 private boolean closeAction = false; // Used to say when to close or when to minimize
338 private static Logger log = Logger.getLogger(NeverNote.class);
339 private String saveLastPath; // last path we used
340 private final QTimer messageTimer; // Timer to clear the status message.
341 private QTimer blockTimer;
342 BrowserWindow blockingWindow;
344 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
347 //***************************************************************
348 //***************************************************************
349 //** Constructor & main entry point
350 //***************************************************************
351 //***************************************************************
352 // Application Constructor
353 @SuppressWarnings("static-access")
354 public NeverNote(DatabaseConnection dbConn) {
356 if (conn.getConnection() == null) {
357 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
358 "is accessing the database or NixNote is already running.\n\n" +
359 "Please end any other process or shutdown the other NixNote before starting.\n\nExiting program."));
361 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
364 setObjectName("mainWindow");
365 // thread().setPriority(Thread.MAX_PRIORITY);
367 logger = new ApplicationLogger("nevernote.log");
368 logger.log(logger.HIGH, "Starting Application");
370 decryptOnShutdown = false;
371 encryptOnShutdown = false;
372 conn.checkDatabaseVersion();
376 // Start building the invalid XML tables
377 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
378 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
380 for (int i=0; i<elements.size(); i++) {
381 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
384 logger.log(logger.EXTREME, "Starting GUI build");
386 QTranslator nevernoteTranslator = new QTranslator();
387 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
388 QApplication.instance().installTranslator(nevernoteTranslator);
390 Global.originalPalette = QApplication.palette();
391 QApplication.setStyle(Global.getStyle());
392 if (Global.useStandardPalette())
393 QApplication.setPalette(QApplication.style().standardPalette());
394 setWindowTitle(tr("NixNote"));
396 mainLeftRightSplitter = new QSplitter();
397 setCentralWidget(mainLeftRightSplitter);
398 leftSplitter1 = new QSplitter();
399 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
401 browserIndexSplitter = new QSplitter();
402 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
404 //* Setup threads & thread timers
405 // int indexRunnerCount = Global.getIndexThreads();
406 // indexRunnerCount = 1;
407 QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount); // increase max thread count
409 logger.log(logger.EXTREME, "Building list manager");
410 listManager = new ListManager(conn, logger);
412 logger.log(logger.EXTREME, "Building index runners & timers");
413 indexRunner = new IndexRunner("indexRunner.log",
414 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
415 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
416 indexThread = new QThread(indexRunner, "Index Thread");
417 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
418 indexRunner.indexImageRecognition = Global.indexImageRecognition();
419 indexRunner.indexNoteBody = Global.indexNoteBody();
420 indexRunner.indexNoteTitle = Global.indexNoteTitle();
421 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
424 synchronizeAnimationTimer = new QTimer();
425 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
427 indexTimer = new QTimer();
428 indexTime = 1000*Global.getIndexThreadSleepInterval();
429 indexTimer.start(indexTime); // Start indexing timer
430 indexTimer.timeout.connect(this, "indexTimer()");
431 indexDisabled = false;
432 indexRunning = false;
434 logger.log(logger.EXTREME, "Setting sync thread & timers");
436 syncRunner = new SyncRunner("syncRunner.log",
437 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
438 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
439 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
440 syncTimer = new QTimer();
441 syncTimer.timeout.connect(this, "syncTimer()");
442 syncRunner.status.message.connect(this, "setMessage(String)");
443 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
444 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
447 automaticSync = true;
448 syncTimer.start(syncTime*60*1000);
450 automaticSync = false;
453 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
454 syncThread = new QThread(syncRunner, "Synchronization Thread");
458 logger.log(logger.EXTREME, "Starting thumnail thread");
459 pdfReadyQueue = new ArrayList<String>();
460 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
461 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
462 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
463 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
464 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
465 thumbnailThread.start();
466 thumbGenerators = new ArrayList<Thumbnailer>();
467 thumbnailTimer = new QTimer();
468 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
470 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
471 thumbnailTimer.start();
473 logger.log(logger.EXTREME, "Starting authentication timer");
474 authTimer = new QTimer();
475 authTimer.timeout.connect(this, "authTimer()");
476 authTimer.start(1000*60*15);
477 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
479 logger.log(logger.EXTREME, "Setting save note timer");
480 saveTimer = new QTimer();
481 saveTimer.timeout.connect(this, "saveNote()");
482 if (Global.getAutoSaveInterval() > 0) {
483 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
486 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
488 logger.log(logger.EXTREME, "Starting external file monitor timer");
489 externalFileSaveTimer = new QTimer();
490 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
491 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
492 externalFiles = new ArrayList<String>();
493 importFilesDelete = new ArrayList<String>();
494 importFilesKeep = new ArrayList<String>();
495 externalFileSaveTimer.start();
497 notebookTree = new NotebookTreeWidget(conn);
498 attributeTree = new AttributeTreeWidget();
499 tagTree = new TagTreeWidget(conn);
500 savedSearchTree = new SavedSearchTreeWidget();
501 trashTree = new TrashTreeWidget();
502 noteTableView = new TableView(logger, listManager);
504 searchField = new QComboBox();
505 searchField.setObjectName("searchField");
506 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
507 searchField.setEditable(true);
508 searchField.activatedIndex.connect(this, "searchFieldChanged()");
509 searchField.setDuplicatesEnabled(false);
510 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
511 searchShortcut = new QShortcut(this);
512 setupShortcut(searchShortcut, "Focus_Search");
513 searchShortcut.activated.connect(this, "focusSearch()");
515 quotaBar = new QuotaProgressBar();
517 zoomSpinner = new QSpinBox();
518 zoomSpinner.setMinimum(10);
519 zoomSpinner.setMaximum(1000);
520 zoomSpinner.setAccelerated(true);
521 zoomSpinner.setSingleStep(10);
522 zoomSpinner.setValue(100);
523 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
525 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
528 QGridLayout leftGrid = new QGridLayout();
529 leftSplitter1.setContentsMargins(5, 0, 0, 7);
530 leftSplitter1.setLayout(leftGrid);
531 leftGrid.addWidget(searchLayout,1,1);
532 leftGrid.addWidget(tagTree,2,1);
533 leftGrid.addWidget(attributeTree,3,1);
534 leftGrid.addWidget(savedSearchTree,4,1);
535 leftGrid.addWidget(trashTree,5, 1);
537 // Setup the browser window
538 noteCache = new HashMap<String,String>();
539 readOnlyCache = new HashMap<String, Boolean>();
540 inkNoteCache = new HashMap<String, Boolean>();
541 browserWindow = new BrowserWindow(conn);
543 mainLeftRightSplitter.addWidget(leftSplitter1);
544 mainLeftRightSplitter.addWidget(browserIndexSplitter);
546 if (Global.getListView() == Global.View_List_Wide) {
547 browserIndexSplitter.addWidget(noteTableView);
548 browserIndexSplitter.addWidget(browserWindow);
550 mainLeftRightSplitter.addWidget(noteTableView);
551 mainLeftRightSplitter.addWidget(browserWindow);
554 // Setup the thumbnail viewer
555 thumbnailViewer = new ThumbnailViewer();
556 thumbnailViewer.upArrow.connect(this, "upAction()");
557 thumbnailViewer.downArrow.connect(this, "downAction()");
558 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
559 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
561 //Setup external browser manager
562 externalWindows = new HashMap<String, ExternalBrowse>();
564 listManager.loadNotesIndex();
565 initializeNotebookTree();
567 initializeSavedSearchTree();
568 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
569 attributeTreeSelected = null;
570 initializeNoteTable();
572 selectedNoteGUIDs = new ArrayList<String>();
573 statusBar = new QStatusBar();
574 setStatusBar(statusBar);
575 menuBar = new MainMenuBar(this);
576 emitLog = new ArrayList<String>();
578 tagTree.setDeleteAction(menuBar.tagDeleteAction);
579 tagTree.setMergeAction(menuBar.tagMergeAction);
580 tagTree.setEditAction(menuBar.tagEditAction);
581 tagTree.setAddAction(menuBar.tagAddAction);
582 tagTree.setIconAction(menuBar.tagIconAction);
583 tagTree.setVisible(Global.isWindowVisible("tagTree"));
584 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
585 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
586 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
587 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
589 if (!Global.isWindowVisible("zoom")) {
590 searchLayout.hideZoom();
591 menuBar.hideZoom.setChecked(false);
594 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
595 notebookTree.setEditAction(menuBar.notebookEditAction);
596 notebookTree.setAddAction(menuBar.notebookAddAction);
597 notebookTree.setIconAction(menuBar.notebookIconAction);
598 notebookTree.setStackAction(menuBar.notebookStackAction);
599 notebookTree.setPublishAction(menuBar.notebookPublishAction);
600 notebookTree.setShareAction(menuBar.notebookShareAction);
601 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
602 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
603 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
604 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
605 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
607 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
608 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
609 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
610 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
611 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
612 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
613 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
615 noteTableView.setAddAction(menuBar.noteAdd);
616 noteTableView.setDeleteAction(menuBar.noteDelete);
617 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
618 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
619 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
620 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
621 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
622 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
623 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
624 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
626 quotaBar.setMouseClickAction(menuBar.accountAction);
629 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
630 trashTree.setEmptyAction(menuBar.emptyTrashAction);
631 trashTree.setVisible(Global.isWindowVisible("trashTree"));
632 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
633 trashTree.updateCounts(listManager.getTrashCount());
634 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
635 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
637 noteTableView.setVisible(Global.isWindowVisible("noteList"));
638 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
640 if (!Global.isWindowVisible("editorButtonBar"))
641 toggleEditorButtonBar();
642 if (!Global.isWindowVisible("leftPanel"))
643 menuBar.hideLeftSide.setChecked(true);
644 if (Global.isWindowVisible("noteInformation"))
645 toggleNoteInformation();
646 quotaBar.setVisible(Global.isWindowVisible("quota"));
647 if (!quotaBar.isVisible())
648 menuBar.hideQuota.setChecked(false);
649 searchField.setVisible(Global.isWindowVisible("searchField"));
650 if (!searchField.isVisible())
651 menuBar.hideSearch.setChecked(false);
653 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
658 find = new FindDialog();
659 find.getOkButton().clicked.connect(this, "doFindText()");
661 // Setup the tray icon menu bar
662 trayShowAction = new QAction(tr("Show/Hide"), this);
663 trayExitAction = new QAction(tr("Exit"), this);
664 trayAddNoteAction = new QAction(tr("Add Note"), this);
666 trayExitAction.triggered.connect(this, "closeNeverNote()");
667 trayAddNoteAction.triggered.connect(this, "addNote()");
668 trayShowAction.triggered.connect(this, "trayToggleVisible()");
670 trayMenu = new QMenu(this);
671 trayMenu.addAction(trayAddNoteAction);
672 trayMenu.addAction(trayShowAction);
673 trayMenu.addAction(trayExitAction);
676 trayIcon = new QSystemTrayIcon(this);
677 trayIcon.setToolTip(tr("NixNote"));
678 trayIcon.setContextMenu(trayMenu);
679 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
682 currentNoteGuid = Global.getLastViewedNoteGuid();
683 historyGuids = new ArrayList<String>();
687 if (!currentNoteGuid.trim().equals("")) {
688 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
691 noteIndexUpdated(true);
693 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
694 if (menuBar.showEditorBar.isChecked())
695 showEditorButtons(browserWindow);
696 tagIndexUpdated(true);
697 savedSearchIndexUpdated();
698 notebookIndexUpdated();
700 setupSyncSignalListeners();
701 setupBrowserSignalListeners();
702 setupIndexListeners();
705 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
706 tagTree.showAllTags(true);
708 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
709 setWindowIcon(appIcon);
710 trayIcon.setIcon(appIcon);
711 if (Global.showTrayIcon())
716 scrollToGuid(currentNoteGuid);
717 if (Global.automaticLogin()) {
719 if (Global.isConnected)
722 setupFolderImports();
725 restoreWindowState(true);
727 if (Global.mimicEvernoteInterface) {
728 notebookTree.selectGuid("");
731 threadMonitorTimer = new QTimer();
732 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
733 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
735 historyGuids.add(currentNoteGuid);
738 menuBar.blockSignals(true);
739 menuBar.narrowListView.blockSignals(true);
740 menuBar.wideListView.blockSignals(true);
741 if (Global.getListView() == Global.View_List_Narrow) {
742 menuBar.narrowListView.setChecked(true);
745 menuBar.wideListView.setChecked(true);
747 menuBar.blockSignals(false);
748 menuBar.narrowListView.blockSignals(false);
749 menuBar.wideListView.blockSignals(false);
751 if (Global.getListView() == Global.View_List_Wide) {
752 browserIndexSplitter.addWidget(noteTableView);
753 browserIndexSplitter.addWidget(browserWindow);
755 mainLeftRightSplitter.addWidget(noteTableView);
756 mainLeftRightSplitter.addWidget(browserWindow);
759 messageTimer = new QTimer();
760 messageTimer.timeout.connect(this, "clearMessage()");
761 messageTimer.setInterval(1000*15);
764 int sortCol = Global.getSortColumn();
765 int sortOrder = Global.getSortOrder();
766 noteTableView.proxyModel.blocked = true;
767 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
768 noteTableView.proxyModel.blocked = false;
769 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
771 if (Global.checkVersionUpgrade())
776 public static void main(String[] args) {
777 log.setLevel(Level.FATAL);
778 QApplication.initialize(args);
779 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
780 QSplashScreen splash = new QSplashScreen(pixmap);
783 DatabaseConnection dbConn;
786 initializeGlobalSettings(args);
788 showSplash = Global.isWindowVisible("SplashScreen");
792 dbConn = setupDatabaseConnection();
794 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
795 Global.getFileManager().purgeResDirectory(true);
797 } catch (InitializationException e) {
800 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
804 NeverNote application = new NeverNote(dbConn);
806 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
807 if (Global.startMinimized())
808 application.showMinimized();
810 if (Global.wasWindowMaximized())
811 application.showMaximized();
817 splash.finish(application);
819 System.out.println("Goodbye.");
824 * Open the internal database, or create if not present
826 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
828 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
829 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
831 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
832 File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
833 File fi = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
835 Global.setDatabaseUrl("");
837 Global.setResourceDatabaseUrl("");
839 Global.setIndexDatabaseUrl("");
841 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
842 boolean goodCheck = false;
844 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
846 if (!dialog.okPressed())
848 Global.cipherPassword = dialog.getPassword();
849 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
850 Global.getDatabaseUserPassword(), Global.cipherPassword);
853 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
854 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
855 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
859 // Encrypt the database upon shutdown
860 private void encryptOnShutdown() {
861 String dbPath= Global.getFileManager().getDbDirPath("");
864 Statement st = conn.getConnection().createStatement();
865 st.execute("shutdown");
866 st = conn.getResourceConnection().createStatement();
867 st.execute("shutdown");
868 st = conn.getIndexConnection().createStatement();
869 st.execute("shutdown");
870 if (QMessageBox.question(this, tr("Are you sure"),
871 tr("Are you sure you wish to encrypt the database?"),
872 QMessageBox.StandardButton.Yes,
873 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
874 ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
875 ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
876 ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
877 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
878 Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
879 Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
881 QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
883 } catch (SQLException e) {
888 // Decrypt the database upon shutdown
889 private void decryptOnShutdown() {
890 String dbPath= Global.getFileManager().getDbDirPath("");
891 String dbName = "NeverNote";
893 Statement st = conn.getConnection().createStatement();
894 st.execute("shutdown");
895 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
896 encryptCipher = "AES";
898 encryptCipher = "XTEA";
899 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
900 "Are you sure you wish to decrypt the database?"),
901 QMessageBox.StandardButton.Yes,
902 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
904 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
905 Global.setDatabaseUrl("");
906 Global.setResourceDatabaseUrl("");
907 Global.setIndexDatabaseUrl("");
908 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
910 } catch (SQLException e) {
915 * Encrypt/Decrypt the local database
917 public void doDatabaseEncrypt() {
918 // The database is not currently encrypted
919 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
920 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
921 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
922 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
923 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
924 "Do you wish to proceed?"),
925 QMessageBox.StandardButton.Yes,
926 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
929 DBEncryptDialog dialog = new DBEncryptDialog();
931 if (dialog.okPressed()) {
932 Global.cipherPassword = dialog.getPassword();
933 encryptOnShutdown = true;
934 encryptCipher = dialog.getEncryptionMethod();
937 DBEncryptDialog dialog = new DBEncryptDialog();
938 dialog.setWindowTitle(tr("Database Decryption"));
939 dialog.hideEncryption();
941 if (dialog.okPressed()) {
942 if (!dialog.getPassword().equals(Global.cipherPassword)) {
943 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
946 decryptOnShutdown = true;
953 private static void initializeGlobalSettings(String[] args) throws InitializationException {
954 StartupConfig startupConfig = new StartupConfig();
956 for (String arg : args) {
957 String lower = arg.toLowerCase();
958 if (lower.startsWith("--name="))
959 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
960 if (lower.startsWith("--home="))
961 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
962 if (lower.startsWith("--disable-viewing"))
963 startupConfig.setDisableViewing(true);
965 Global.setup(startupConfig);
970 public void closeEvent(QCloseEvent event) {
971 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
976 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
979 if (currentNote!= null & browserWindow!=null) {
980 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
981 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
984 setMessage(tr("Beginning shutdown."));
986 // Close down external windows
987 Collection<ExternalBrowse> windows = externalWindows.values();
988 Iterator<ExternalBrowse> iterator = windows.iterator();
989 while (iterator.hasNext()) {
990 ExternalBrowse browser = iterator.next();
991 browser.windowClosing.disconnect();
996 externalFileEditedSaver();
997 if (Global.isConnected && Global.synchronizeOnClose()) {
998 setMessage(tr("Performing synchronization before closing."));
999 syncRunner.syncNeeded = true;
1000 syncRunner.addWork("SYNC");
1002 syncRunner.keepRunning = false;
1004 syncRunner.addWork("STOP");
1005 setMessage("Closing Program.");
1006 threadMonitorTimer.stop();
1008 thumbnailRunner.addWork("STOP");
1009 indexRunner.addWork("STOP");
1014 if (tempFiles != null)
1017 browserWindow.noteSignal.tagsChanged.disconnect();
1018 browserWindow.noteSignal.titleChanged.disconnect();
1019 browserWindow.noteSignal.noteChanged.disconnect();
1020 browserWindow.noteSignal.notebookChanged.disconnect();
1021 browserWindow.noteSignal.createdDateChanged.disconnect();
1022 browserWindow.noteSignal.alteredDateChanged.disconnect();
1023 syncRunner.searchSignal.listChanged.disconnect();
1024 syncRunner.tagSignal.listChanged.disconnect();
1025 syncRunner.notebookSignal.listChanged.disconnect();
1026 syncRunner.noteIndexSignal.listChanged.disconnect();
1029 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1030 saveNoteColumnPositions();
1031 saveNoteIndexWidth();
1033 int width = notebookTree.columnWidth(0);
1034 Global.setColumnWidth("notebookTreeName", width);
1035 width = tagTree.columnWidth(0);
1036 Global.setColumnWidth("tagTreeName", width);
1038 Global.saveWindowMaximized(isMaximized());
1039 Global.saveCurrentNoteGuid(currentNoteGuid);
1041 int sortCol = noteTableView.proxyModel.sortColumn();
1042 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1043 Global.setSortColumn(sortCol);
1044 Global.setSortOrder(sortOrder);
1048 Global.keepRunning = false;
1050 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1051 if (indexRunner.thread().isAlive())
1052 indexRunner.thread().join(50);
1053 if (!indexRunner.thread().isAlive())
1054 logger.log(logger.MEDIUM, "Index thread has stopped");
1056 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1057 indexRunner.thread().interrupt();
1059 } catch (InterruptedException e1) {
1060 e1.printStackTrace();
1063 if (!syncRunner.thread().isAlive()) {
1064 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1065 if (syncRunner.thread().isAlive()) {
1066 System.out.println(tr("Synchronizing. Please be patient."));
1067 for(;syncRunner.thread().isAlive();) {
1070 } catch (InterruptedException e) {
1071 e.printStackTrace();
1075 logger.log(logger.MEDIUM, "Sync thread has stopped");
1078 if (encryptOnShutdown) {
1079 encryptOnShutdown();
1081 if (decryptOnShutdown) {
1082 decryptOnShutdown();
1085 Global.getFileManager().purgeResDirectory(false);
1086 } catch (InitializationException e) {
1087 System.out.println(tr("Empty res directory purge failed"));
1088 e.printStackTrace();
1090 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1093 @SuppressWarnings("unused")
1094 private void closeNeverNote() {
1098 public void setMessage(String s) {
1099 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1102 logger.log(logger.HIGH, "Message: " +s);
1103 statusBar.showMessage(s);
1107 messageTimer.stop();
1108 messageTimer.setSingleShot(true);
1109 messageTimer.start();
1112 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1115 private void clearMessage() {
1116 statusBar.clearMessage();
1120 private void waitCursor(boolean wait) {
1122 if (QApplication.overrideCursor() == null)
1123 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1126 while (QApplication.overrideCursor() != null)
1127 QApplication.restoreOverrideCursor();
1129 listManager.refreshCounters();
1132 private void setupIndexListeners() {
1133 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1134 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1135 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1136 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1138 private void setupSyncSignalListeners() {
1139 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1140 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1141 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1142 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1143 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1145 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1146 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1147 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1149 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1150 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1151 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1152 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1153 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1155 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1158 private void setupBrowserSignalListeners() {
1159 setupBrowserWindowListeners(browserWindow, true);
1162 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1163 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1164 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1165 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1166 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1167 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1168 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1169 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1170 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1171 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1172 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1173 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1174 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1175 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1176 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1177 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1178 browser.unblockApplication.connect(this, "unblockApplication()");
1179 if (master) browser.focusLost.connect(this, "saveNote()");
1180 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1181 browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1184 //**************************************************
1186 //**************************************************
1187 private void setupShortcut(QShortcut action, String text) {
1188 if (!Global.shortcutKeys.containsAction(text))
1190 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1193 //***************************************************************
1194 //***************************************************************
1195 //* Settings and look & feel
1196 //***************************************************************
1197 //***************************************************************
1198 @SuppressWarnings("unused")
1199 private void settings() {
1200 logger.log(logger.HIGH, "Entering NeverNote.settings");
1201 saveNoteColumnPositions();
1202 saveNoteIndexWidth();
1204 ConfigDialog settings = new ConfigDialog(this);
1205 String dateFormat = Global.getDateFormat();
1206 String timeFormat = Global.getTimeFormat();
1208 indexTime = 1000*Global.getIndexThreadSleepInterval();
1209 indexTimer.start(indexTime); // reset indexing timer
1212 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1213 indexRunner.indexNoteBody = Global.indexNoteBody();
1214 indexRunner.indexNoteTitle = Global.indexNoteTitle();
1215 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1216 indexRunner.indexImageRecognition = Global.indexImageRecognition();
1217 if (Global.showTrayIcon())
1222 if (menuBar.showEditorBar.isChecked())
1223 showEditorButtons(browserWindow);
1225 // Reset the save timer
1226 if (Global.getAutoSaveInterval() > 0)
1227 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1232 // Set special reloads
1233 if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1234 conn.executeSql("Delete from LinkedNotebook");
1235 conn.executeSql("delete from SharedNotebook");
1236 conn.executeSql("Delete from Notebook where linked=true");
1237 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1238 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1243 readOnlyCache.clear();
1244 inkNoteCache.clear();
1245 noteIndexUpdated(true);
1247 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1249 // Restore things to the way they were
1250 private void restoreWindowState(boolean mainWindow) {
1251 // We need to name things or this doesn't work.
1252 setObjectName("NeverNote");
1253 restoreState(Global.restoreState(objectName()));
1254 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1255 browserIndexSplitter.setObjectName("browserIndexSplitter");
1256 leftSplitter1.setObjectName("leftSplitter1");
1258 // Restore the actual positions.
1260 restoreGeometry(Global.restoreGeometry(objectName()));
1261 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1262 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1263 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1266 // Save window positions for the next start
1267 private void saveWindowState() {
1268 Global.saveGeometry(objectName(), saveGeometry());
1269 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1270 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1271 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1272 Global.saveState(objectName(), saveState());
1274 // Load the style sheet
1275 private void loadStyleSheet() {
1276 String styleSheetName = "default.qss";
1277 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1278 styleSheetName = "default-cleanlooks.qss";
1279 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1280 QFile file = new QFile(fileName);
1282 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1283 if (!file.exists()) {
1284 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1285 file = new QFile(fileName);
1287 file.open(OpenModeFlag.ReadOnly);
1288 String styleSheet = file.readAll().toString();
1290 setStyleSheet(styleSheet);
1292 // Save column positions for the next time
1293 private void saveNoteColumnPositions() {
1294 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1295 Global.setColumnPosition("noteTableCreationPosition", position);
1296 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1297 Global.setColumnPosition("noteTableTagPosition", position);
1298 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1299 Global.setColumnPosition("noteTableNotebookPosition", position);
1300 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1301 Global.setColumnPosition("noteTableChangedPosition", position);
1302 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1303 Global.setColumnPosition("noteTableAuthorPosition", position);
1304 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1305 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1306 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1307 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1308 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1309 Global.setColumnPosition("noteTableTitlePosition", position);
1310 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1311 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1312 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1313 Global.setColumnPosition("noteTableGuidPosition", position);
1314 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1315 Global.setColumnPosition("noteTableThumbnailPosition", position);
1318 // Save column widths for the next time
1319 private void saveNoteIndexWidth() {
1321 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1322 Global.setColumnWidth("noteTableCreationPosition", width);
1323 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1324 Global.setColumnWidth("noteTableChangedPosition", width);
1325 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1326 Global.setColumnWidth("noteTableGuidPosition", width);
1327 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1328 Global.setColumnWidth("noteTableNotebookPosition", width);
1329 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1330 Global.setColumnWidth("noteTableTagPosition", width);
1331 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1332 Global.setColumnWidth("noteTableTitlePosition", width);
1333 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1334 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1335 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1336 Global.setColumnWidth("noteTableAuthorPosition", width);
1337 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1338 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1339 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1340 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1341 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1342 Global.setColumnWidth("noteTableThumbnailPosition", width);
1343 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1344 Global.setColumnWidth("noteTableGuidPosition", width);
1347 @SuppressWarnings("unused")
1348 private void toggleSearchWindow() {
1349 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1350 searchLayout.toggleSearchField();
1351 menuBar.hideSearch.setChecked(searchField.isVisible());
1352 Global.saveWindowVisible("searchField", searchField.isVisible());
1353 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1355 @SuppressWarnings("unused")
1356 private void toggleQuotaWindow() {
1357 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1358 searchLayout.toggleQuotaBar();
1359 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1360 Global.saveWindowVisible("quota", quotaBar.isVisible());
1361 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1363 @SuppressWarnings("unused")
1364 private void toggleZoomWindow() {
1365 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1366 searchLayout.toggleZoom();
1367 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1368 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1369 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1374 //***************************************************************
1375 //***************************************************************
1376 //** These functions deal with Notebook menu items
1377 //***************************************************************
1378 //***************************************************************
1379 // Setup the tree containing the user's notebooks.
1380 private void initializeNotebookTree() {
1381 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1382 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1383 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1384 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1385 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1387 // Listener when a notebook is selected
1388 private void notebookTreeSelection() {
1389 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1390 noteTableView.proxyModel.blocked = true;
1393 clearAttributeFilter();
1394 clearSavedSearchFilter();
1395 if (Global.mimicEvernoteInterface) {
1397 searchField.clear();
1399 menuBar.noteRestoreAction.setVisible(false);
1400 menuBar.notebookEditAction.setEnabled(true);
1401 menuBar.notebookDeleteAction.setEnabled(true);
1402 menuBar.notebookPublishAction.setEnabled(true);
1403 menuBar.notebookShareAction.setEnabled(true);
1404 menuBar.notebookIconAction.setEnabled(true);
1405 menuBar.notebookStackAction.setEnabled(true);
1406 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1407 selectedNotebookGUIDs.clear();
1409 String stackName = "";
1410 if (selections.size() > 0) {
1411 guid = (selections.get(0).text(2));
1412 stackName = selections.get(0).text(0);
1414 if (!Global.mimicEvernoteInterface) {
1415 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1416 if (selections.size()==0) {
1417 selectedNotebookGUIDs.clear();
1418 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1419 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1421 menuBar.notebookEditAction.setEnabled(false);
1422 menuBar.notebookDeleteAction.setEnabled(false);
1423 menuBar.notebookStackAction.setEnabled(false);
1424 menuBar.notebookIconAction.setEnabled(false);
1427 if (!guid.equals("") && !guid.equals("STACK")) {
1428 selectedNotebookGUIDs.add(guid);
1429 menuBar.notebookIconAction.setEnabled(true);
1431 menuBar.notebookIconAction.setEnabled(true);
1432 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1433 Notebook book = listManager.getNotebookIndex().get(j);
1434 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1435 selectedNotebookGUIDs.add(book.getGuid());
1438 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1439 listManager.loadNotesIndex();
1440 noteIndexUpdated(false);
1441 refreshEvernoteNote(true);
1442 listManager.refreshCounters = true;
1443 listManager.refreshCounters();
1444 if (selectedNotebookGUIDs.size() == 1) {
1445 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1446 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1448 noteTableView.proxyModel.blocked = true;
1450 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1452 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1455 noteTableView.proxyModel.blocked = false;
1456 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1459 private void clearNotebookFilter() {
1460 notebookTree.blockSignals(true);
1461 notebookTree.clearSelection();
1462 menuBar.noteRestoreAction.setVisible(false);
1463 menuBar.notebookEditAction.setEnabled(false);
1464 menuBar.notebookDeleteAction.setEnabled(false);
1465 selectedNotebookGUIDs.clear();
1466 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1467 notebookTree.blockSignals(false);
1469 // Triggered when the notebook DB has been updated
1470 private void notebookIndexUpdated() {
1471 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1473 // Get the possible icons
1474 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1475 notebookTree.setIcons(icons);
1477 if (selectedNotebookGUIDs == null)
1478 selectedNotebookGUIDs = new ArrayList<String>();
1479 List<Notebook> books = conn.getNotebookTable().getAll();
1480 for (int i=books.size()-1; i>=0; i--) {
1481 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1482 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1484 j=listManager.getArchiveNotebookIndex().size();
1490 listManager.countNotebookResults(listManager.getNoteIndex());
1491 notebookTree.blockSignals(true);
1492 notebookTree.load(books, listManager.getLocalNotebooks());
1493 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1494 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1496 selectedNotebookGUIDs.remove(i);
1498 listManager.refreshCounters = true;
1499 listManager.refreshCounters();
1500 notebookTree.blockSignals(false);
1502 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1504 // Show/Hide note information
1505 @SuppressWarnings("unused")
1506 private void toggleNotebookWindow() {
1507 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1508 searchLayout.toggleNotebook();
1509 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1510 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1511 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1513 // Add a new notebook
1514 @SuppressWarnings("unused")
1515 private void addNotebook() {
1516 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1517 NotebookEdit edit = new NotebookEdit();
1518 edit.setNotebooks(listManager.getNotebookIndex());
1521 if (!edit.okPressed())
1524 Calendar currentTime = new GregorianCalendar();
1525 Long l = new Long(currentTime.getTimeInMillis());
1526 String randint = new String(Long.toString(l));
1528 Notebook newBook = new Notebook();
1529 newBook.setUpdateSequenceNum(0);
1530 newBook.setGuid(randint);
1531 newBook.setName(edit.getNotebook());
1532 newBook.setServiceCreated(new Date().getTime());
1533 newBook.setServiceUpdated(new Date().getTime());
1534 newBook.setDefaultNotebook(false);
1535 newBook.setPublished(false);
1537 listManager.getNotebookIndex().add(newBook);
1539 listManager.getLocalNotebooks().add(newBook.getGuid());
1540 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1541 notebookIndexUpdated();
1542 listManager.countNotebookResults(listManager.getNoteIndex());
1543 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1544 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1546 // Edit an existing notebook
1547 @SuppressWarnings("unused")
1548 private void stackNotebook() {
1549 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1550 StackNotebook edit = new StackNotebook();
1552 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1553 QTreeWidgetItem currentSelection;
1554 for (int i=0; i<selections.size(); i++) {
1555 currentSelection = selections.get(0);
1556 String guid = currentSelection.text(2);
1557 if (guid.equalsIgnoreCase("")) {
1558 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1561 if (guid.equalsIgnoreCase("STACK")) {
1562 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1567 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1572 if (!edit.okPressed())
1575 String stack = edit.getStackName();
1577 for (int i=0; i<selections.size(); i++) {
1578 currentSelection = selections.get(i);
1579 String guid = currentSelection.text(2);
1580 listManager.updateNotebookStack(guid, stack);
1582 notebookIndexUpdated();
1583 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1585 // Edit an existing notebook
1586 @SuppressWarnings("unused")
1587 private void editNotebook() {
1588 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1589 NotebookEdit edit = new NotebookEdit();
1591 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1592 QTreeWidgetItem currentSelection;
1593 currentSelection = selections.get(0);
1594 edit.setNotebook(currentSelection.text(0));
1596 String guid = currentSelection.text(2);
1597 if (!guid.equalsIgnoreCase("STACK")) {
1598 edit.setTitle(tr("Edit Notebook"));
1599 edit.setNotebooks(listManager.getNotebookIndex());
1600 edit.setLocalCheckboxEnabled(false);
1601 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1602 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1603 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1604 i=listManager.getNotebookIndex().size();
1608 edit.setTitle(tr("Edit Stack"));
1609 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1610 edit.hideLocalCheckbox();
1611 edit.hideDefaultCheckbox();
1616 if (!edit.okPressed())
1620 if (guid.equalsIgnoreCase("STACK")) {
1621 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1622 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1623 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1624 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1625 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1627 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1628 currentSelection.setText(0, edit.getNotebook());
1632 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1633 currentSelection.setText(0, edit.getNotebook());
1635 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1636 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1637 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1638 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1639 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1640 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1641 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1642 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1644 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1645 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1646 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1647 linkedNotebook.setShareName(edit.getNotebook());
1648 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1650 i=listManager.getNotebookIndex().size();
1654 // Build a list of non-closed notebooks
1655 List<Notebook> nbooks = new ArrayList<Notebook>();
1656 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1657 boolean found=false;
1658 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1659 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1663 nbooks.add(listManager.getNotebookIndex().get(i));
1667 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1668 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1669 browserWindow.setNotebookList(filteredBooks);
1670 Iterator<String> set = externalWindows.keySet().iterator();
1671 while(set.hasNext())
1672 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1673 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1675 // Publish a notebook
1676 @SuppressWarnings("unused")
1677 private void publishNotebook() {
1678 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1679 QTreeWidgetItem currentSelection;
1680 currentSelection = selections.get(0);
1681 String guid = currentSelection.text(2);
1683 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1688 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1689 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1690 n = listManager.getNotebookIndex().get(i);
1692 i = listManager.getNotebookIndex().size();
1698 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1701 if (!publish.okClicked())
1704 Publishing p = publish.getPublishing();
1705 boolean isPublished = !publish.isStopPressed();
1706 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1707 n.setPublished(isPublished);
1709 listManager.getNotebookIndex().set(position, n);
1710 notebookIndexUpdated();
1712 // Publish a notebook
1713 @SuppressWarnings("unused")
1714 private void shareNotebook() {
1715 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1716 QTreeWidgetItem currentSelection;
1717 currentSelection = selections.get(0);
1718 String guid = currentSelection.text(2);
1720 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1724 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1725 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1726 n = listManager.getNotebookIndex().get(i);
1727 i = listManager.getNotebookIndex().size();
1731 String authToken = null;
1732 if (syncRunner.isConnected)
1733 authToken = syncRunner.authToken;
1734 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1739 // Delete an existing notebook
1740 @SuppressWarnings("unused")
1741 private void deleteNotebook() {
1742 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1743 boolean stacksFound = false;
1744 boolean notebooksFound = false;
1745 boolean assigned = false;
1746 // Check if any notes have this notebook
1747 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1748 for (int i=0; i<selections.size(); i++) {
1749 QTreeWidgetItem currentSelection;
1750 currentSelection = selections.get(i);
1751 String guid = currentSelection.text(2);
1752 if (!guid.equalsIgnoreCase("STACK")) {
1753 notebooksFound = true;
1754 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1755 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1756 if (noteGuid.equals(guid)) {
1758 j=listManager.getNoteIndex().size();
1759 i=selections.size();
1767 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1768 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1772 if (conn.getNotebookTable().getAll().size() == 1) {
1773 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1777 // If all notebooks are clear, verify the delete
1778 String msg1 = new String(tr("Delete selected notebooks?"));
1779 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1780 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1781 " not deleted unless selected?"));
1783 if (stacksFound && notebooksFound)
1785 if (!stacksFound && notebooksFound)
1787 if (stacksFound && !notebooksFound)
1789 if (QMessageBox.question(this, tr("Confirmation"), msg,
1790 QMessageBox.StandardButton.Yes,
1791 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1795 // If confirmed, delete the notebook
1796 for (int i=selections.size()-1; i>=0; i--) {
1797 QTreeWidgetItem currentSelection;
1798 currentSelection = selections.get(i);
1799 String guid = currentSelection.text(2);
1800 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1801 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1802 listManager.renameStack(currentSelection.text(0), "");
1804 conn.getNotebookTable().expungeNotebook(guid, true);
1805 listManager.deleteNotebook(guid);
1809 notebookIndexUpdated();
1810 // notebookTreeSelection();
1811 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1812 // listManager.countNotebookResults(listManager.getNoteIndex());
1813 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1815 // A note's notebook has been updated
1816 @SuppressWarnings("unused")
1817 private void updateNoteNotebook(String guid, String notebookGuid) {
1819 // Update the list manager
1820 listManager.updateNoteNotebook(guid, notebookGuid);
1821 listManager.countNotebookResults(listManager.getNoteIndex());
1822 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1824 // Find the name of the notebook
1825 String notebookName = null;
1826 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1827 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1828 notebookName = listManager.getNotebookIndex().get(i).getName();
1833 // If we found the name, update the browser window
1834 if (notebookName != null) {
1835 updateListNoteNotebook(guid, notebookName);
1836 if (guid.equals(currentNoteGuid)) {
1837 int pos = browserWindow.notebookBox.findText(notebookName);
1839 browserWindow.notebookBox.setCurrentIndex(pos);
1843 // If we're dealing with the current note, then we need to be sure and update the notebook there
1844 if (guid.equals(currentNoteGuid)) {
1845 if (currentNote != null) {
1846 currentNote.setNotebookGuid(notebookGuid);
1850 // Open/close notebooks
1851 @SuppressWarnings("unused")
1852 private void closeNotebooks() {
1853 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1855 if (!na.okClicked())
1859 listManager.getArchiveNotebookIndex().clear();
1861 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1862 String text = na.getClosedBookList().takeItem(i).text();
1863 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1864 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1865 Notebook n = listManager.getNotebookIndex().get(j);
1866 conn.getNotebookTable().setArchived(n.getGuid(),true);
1867 listManager.getArchiveNotebookIndex().add(n);
1868 j=listManager.getNotebookIndex().size();
1873 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1874 String text = na.getOpenBookList().takeItem(i).text();
1875 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1876 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1877 Notebook n = listManager.getNotebookIndex().get(j);
1878 conn.getNotebookTable().setArchived(n.getGuid(),false);
1879 j=listManager.getNotebookIndex().size();
1883 notebookTreeSelection();
1884 listManager.loadNotesIndex();
1885 notebookIndexUpdated();
1886 noteIndexUpdated(false);
1887 reloadTagTree(true);
1888 // noteIndexUpdated(false);
1890 // Build a list of non-closed notebooks
1891 List<Notebook> nbooks = new ArrayList<Notebook>();
1892 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1893 boolean found=false;
1894 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1895 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1899 nbooks.add(listManager.getNotebookIndex().get(i));
1902 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1903 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1904 browserWindow.setNotebookList(filteredBooks);
1906 // Update any external windows
1907 Iterator<String> set = externalWindows.keySet().iterator();
1908 while(set.hasNext())
1909 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1913 // Change the notebook's icon
1914 @SuppressWarnings("unused")
1915 private void setNotebookIcon() {
1916 boolean stackSelected = false;
1917 boolean allNotebookSelected = false;
1919 QTreeWidgetItem currentSelection;
1920 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1921 if (selections.size() == 0)
1924 currentSelection = selections.get(0);
1925 String guid = currentSelection.text(2);
1926 if (guid.equalsIgnoreCase(""))
1927 allNotebookSelected = true;
1928 if (guid.equalsIgnoreCase("STACK"))
1929 stackSelected = true;
1931 QIcon currentIcon = currentSelection.icon(0);
1935 if (!stackSelected && !allNotebookSelected) {
1936 icon = conn.getNotebookTable().getIcon(guid);
1938 dialog = new SetIcon(currentIcon, saveLastPath);
1939 dialog.setUseDefaultIcon(true);
1941 dialog = new SetIcon(icon, saveLastPath);
1942 dialog.setUseDefaultIcon(false);
1945 if (stackSelected) {
1946 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1948 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1951 dialog = new SetIcon(currentIcon, saveLastPath);
1952 dialog.setUseDefaultIcon(true);
1954 dialog = new SetIcon(icon, saveLastPath);
1955 dialog.setUseDefaultIcon(false);
1959 if (dialog.okPressed()) {
1960 saveLastPath = dialog.getPath();
1962 QIcon newIcon = dialog.getIcon();
1963 if (stackSelected) {
1964 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1965 if (newIcon == null) {
1966 newIcon = new QIcon(iconPath+"books2.png");
1968 currentSelection.setIcon(0,newIcon);
1971 if (allNotebookSelected) {
1972 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1973 if (newIcon == null) {
1974 newIcon = new QIcon(iconPath+"notebook-green.png");
1976 currentSelection.setIcon(0,newIcon);
1979 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1980 if (newIcon == null) {
1981 boolean isPublished = false;;
1982 boolean found = false;
1983 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1984 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1985 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1989 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1991 currentSelection.setIcon(0, newIcon);
1997 //***************************************************************
1998 //***************************************************************
1999 //** These functions deal with Tag menu items
2000 //***************************************************************
2001 //***************************************************************
2002 // Add a new notebook
2003 @SuppressWarnings("unused")
2004 private void addTag() {
2005 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2006 TagEdit edit = new TagEdit();
2007 edit.setTagList(listManager.getTagIndex());
2009 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2010 QTreeWidgetItem currentSelection = null;
2011 if (selections.size() > 0) {
2012 currentSelection = selections.get(0);
2013 edit.setParentTag(currentSelection.text(0));
2018 if (!edit.okPressed())
2021 Calendar currentTime = new GregorianCalendar();
2022 Long l = new Long(currentTime.getTimeInMillis());
2023 String randint = new String(Long.toString(l));
2025 Tag newTag = new Tag();
2026 newTag.setUpdateSequenceNum(0);
2027 newTag.setGuid(randint);
2028 newTag.setName(edit.getTag());
2029 if (edit.getParentTag().isChecked()) {
2030 newTag.setParentGuid(currentSelection.text(2));
2031 newTag.setParentGuidIsSet(true);
2032 currentSelection.setExpanded(true);
2034 conn.getTagTable().addTag(newTag, true);
2035 listManager.getTagIndex().add(newTag);
2036 reloadTagTree(true);
2038 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2040 @SuppressWarnings("unused")
2041 private void reloadTagTree() {
2042 reloadTagTree(false);
2044 private void reloadTagTree(boolean reload) {
2045 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2046 tagIndexUpdated(reload);
2047 boolean filter = false;
2049 listManager.countTagResults(listManager.getNoteIndex());
2050 if (notebookTree.selectedItems().size() > 0
2051 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2053 if (tagTree.selectedItems().size() > 0)
2055 tagTree.showAllTags(!filter);
2056 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2058 // Edit an existing tag
2059 @SuppressWarnings("unused")
2060 private void editTag() {
2061 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2062 TagEdit edit = new TagEdit();
2063 edit.setTitle("Edit Tag");
2064 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2065 QTreeWidgetItem currentSelection;
2066 currentSelection = selections.get(0);
2067 edit.setTag(currentSelection.text(0));
2068 edit.setTagList(listManager.getTagIndex());
2071 if (!edit.okPressed())
2074 String guid = currentSelection.text(2);
2075 currentSelection.setText(0,edit.getTag());
2077 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2078 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2079 listManager.getTagIndex().get(i).setName(edit.getTag());
2080 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2081 updateListTagName(guid);
2082 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2083 browserWindow.setTag(getTagNamesForNote(currentNote));
2084 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2088 browserWindow.setTag(getTagNamesForNote(currentNote));
2089 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2091 // Delete an existing tag
2092 @SuppressWarnings("unused")
2093 private void deleteTag() {
2094 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2096 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2097 QMessageBox.StandardButton.Yes,
2098 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2102 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2103 for (int i=selections.size()-1; i>=0; i--) {
2104 QTreeWidgetItem currentSelection;
2105 currentSelection = selections.get(i);
2106 removeTagItem(currentSelection.text(2));
2108 tagIndexUpdated(true);
2110 listManager.countTagResults(listManager.getNoteIndex());
2111 // tagTree.updateCounts(listManager.getTagCounter());
2112 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2114 // Remove a tag tree item. Go recursively down & remove the children too
2115 private void removeTagItem(String guid) {
2116 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2117 String parent = listManager.getTagIndex().get(j).getParentGuid();
2118 if (parent != null && parent.equals(guid)) {
2119 //Remove this tag's children
2120 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2123 //Now, remove this tag
2124 removeListTagName(guid);
2125 conn.getTagTable().expungeTag(guid, true);
2126 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2127 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2128 listManager.getTagIndex().remove(a);
2133 // Setup the tree containing the user's tags
2134 private void initializeTagTree() {
2135 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2136 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2137 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2138 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2139 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2140 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2142 // Listener when a tag is selected
2143 private void tagTreeSelection() {
2144 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2147 clearAttributeFilter();
2148 clearSavedSearchFilter();
2150 menuBar.noteRestoreAction.setVisible(false);
2152 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2153 QTreeWidgetItem currentSelection;
2154 selectedTagGUIDs.clear();
2155 for (int i=0; i<selections.size(); i++) {
2156 currentSelection = selections.get(i);
2157 selectedTagGUIDs.add(currentSelection.text(2));
2159 if (selections.size() > 0) {
2160 menuBar.tagEditAction.setEnabled(true);
2161 menuBar.tagDeleteAction.setEnabled(true);
2162 menuBar.tagIconAction.setEnabled(true);
2165 menuBar.tagEditAction.setEnabled(false);
2166 menuBar.tagDeleteAction.setEnabled(false);
2167 menuBar.tagIconAction.setEnabled(true);
2169 if (selections.size() > 1)
2170 menuBar.tagMergeAction.setEnabled(true);
2172 menuBar.tagMergeAction.setEnabled(false);
2173 listManager.setSelectedTags(selectedTagGUIDs);
2174 listManager.loadNotesIndex();
2175 noteIndexUpdated(false);
2176 refreshEvernoteNote(true);
2177 listManager.refreshCounters = true;
2178 listManager.refreshCounters();
2179 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2181 // trigger the tag index to be refreshed
2182 @SuppressWarnings("unused")
2183 private void tagIndexUpdated() {
2184 tagIndexUpdated(true);
2186 private void tagIndexUpdated(boolean reload) {
2187 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2188 if (selectedTagGUIDs == null)
2189 selectedTagGUIDs = new ArrayList<String>();
2191 listManager.reloadTagIndex();
2193 tagTree.blockSignals(true);
2195 tagTree.setIcons(conn.getTagTable().getAllIcons());
2196 tagTree.load(listManager.getTagIndex());
2199 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2200 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2202 selectedTagGUIDs.remove(i);
2204 tagTree.blockSignals(false);
2206 browserWindow.setTag(getTagNamesForNote(currentNote));
2207 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2209 // Show/Hide note information
2210 @SuppressWarnings("unused")
2211 private void toggleTagWindow() {
2212 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2213 if (tagTree.isVisible())
2217 menuBar.hideTags.setChecked(tagTree.isVisible());
2218 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2219 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2221 // A note's tags have been updated
2222 @SuppressWarnings("unused")
2223 private void updateNoteTags(String guid, List<String> tags) {
2224 // Save any new tags. We'll need them later.
2225 List<String> newTags = new ArrayList<String>();
2226 for (int i=0; i<tags.size(); i++) {
2227 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2228 newTags.add(tags.get(i));
2231 listManager.saveNoteTags(guid, tags);
2232 listManager.countTagResults(listManager.getNoteIndex());
2233 StringBuffer names = new StringBuffer("");
2234 for (int i=0; i<tags.size(); i++) {
2235 names = names.append(tags.get(i));
2236 if (i<tags.size()-1) {
2237 names.append(Global.tagDelimeter + " ");
2240 browserWindow.setTag(names.toString());
2243 // Now, we need to add any new tags to the tag tree
2244 for (int i=0; i<newTags.size(); i++)
2245 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2247 // Get a string containing all tag names for a note
2248 private String getTagNamesForNote(Note n) {
2249 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2250 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2252 StringBuffer buffer = new StringBuffer(100);
2253 Vector<String> v = new Vector<String>();
2254 List<String> guids = n.getTagGuids();
2259 for (int i=0; i<guids.size(); i++) {
2260 v.add(listManager.getTagNameByGuid(guids.get(i)));
2262 Comparator<String> comparator = Collections.reverseOrder();
2263 Collections.sort(v,comparator);
2264 Collections.reverse(v);
2266 for (int i = 0; i<v.size(); i++) {
2268 buffer.append(", ");
2269 buffer.append(v.get(i));
2272 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2273 return buffer.toString();
2275 // Tags were added via dropping notes from the note list
2276 @SuppressWarnings("unused")
2277 private void tagsAdded(String noteGuid, String tagGuid) {
2278 String tagName = null;
2279 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2280 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2281 tagName = listManager.getTagIndex().get(i).getName();
2282 i=listManager.getTagIndex().size();
2285 if (tagName == null)
2288 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2289 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2290 List<String> tagNames = new ArrayList<String>();
2291 tagNames.add(new String(tagName));
2292 Note n = listManager.getMasterNoteIndex().get(i);
2293 for (int j=0; j<n.getTagNames().size(); j++) {
2294 tagNames.add(new String(n.getTagNames().get(j)));
2296 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2297 if (n.getGuid().equals(currentNoteGuid)) {
2298 Collections.sort(tagNames);
2299 String display = "";
2300 for (int j=0; j<tagNames.size(); j++) {
2301 display = display+tagNames.get(j);
2302 if (j+2<tagNames.size())
2303 display = display+Global.tagDelimeter+" ";
2305 browserWindow.setTag(display);
2307 i=listManager.getMasterNoteIndex().size();
2312 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2314 private void clearTagFilter() {
2315 tagTree.blockSignals(true);
2316 tagTree.clearSelection();
2317 menuBar.noteRestoreAction.setVisible(false);
2318 menuBar.tagEditAction.setEnabled(false);
2319 menuBar.tagMergeAction.setEnabled(false);
2320 menuBar.tagDeleteAction.setEnabled(false);
2321 menuBar.tagIconAction.setEnabled(false);
2322 selectedTagGUIDs.clear();
2323 listManager.setSelectedTags(selectedTagGUIDs);
2324 tagTree.blockSignals(false);
2326 // Change the icon for a tag
2327 @SuppressWarnings("unused")
2328 private void setTagIcon() {
2329 QTreeWidgetItem currentSelection;
2330 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2331 if (selections.size() == 0)
2334 currentSelection = selections.get(0);
2335 String guid = currentSelection.text(2);
2337 QIcon currentIcon = currentSelection.icon(0);
2338 QIcon icon = conn.getTagTable().getIcon(guid);
2341 dialog = new SetIcon(currentIcon, saveLastPath);
2342 dialog.setUseDefaultIcon(true);
2344 dialog = new SetIcon(icon, saveLastPath);
2345 dialog.setUseDefaultIcon(false);
2348 if (dialog.okPressed()) {
2349 saveLastPath = dialog.getPath();
2350 QIcon newIcon = dialog.getIcon();
2351 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2352 if (newIcon == null)
2353 newIcon = new QIcon(iconPath+"tag.png");
2354 currentSelection.setIcon(0, newIcon);
2359 @SuppressWarnings("unused")
2360 private void mergeTags() {
2361 List<Tag> tags = new ArrayList<Tag>();
2362 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2363 for (int i=0; i<selections.size(); i++) {
2364 Tag record = new Tag();
2365 record.setGuid(selections.get(i).text(2));
2366 record.setName(selections.get(i).text(0));
2370 TagMerge mergeDialog = new TagMerge(tags);
2372 if (!mergeDialog.okClicked())
2374 String newGuid = mergeDialog.getNewTagGuid();
2376 for (int i=0; i<tags.size(); i++) {
2377 if (!tags.get(i).getGuid().equals(newGuid)) {
2378 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2379 for (int j=0; j<noteGuids.size(); j++) {
2380 String noteGuid = noteGuids.get(j);
2381 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2382 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2383 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2387 listManager.reloadIndexes();
2390 //***************************************************************
2391 //***************************************************************
2392 //** These functions deal with Saved Search menu items
2393 //***************************************************************
2394 //***************************************************************
2395 // Add a new notebook
2396 @SuppressWarnings("unused")
2397 private void addSavedSearch() {
2398 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2399 SavedSearchEdit edit = new SavedSearchEdit();
2400 edit.setSearchList(listManager.getSavedSearchIndex());
2403 if (!edit.okPressed())
2406 Calendar currentTime = new GregorianCalendar();
2407 Long l = new Long(currentTime.getTimeInMillis());
2408 String randint = new String(Long.toString(l));
2410 SavedSearch search = new SavedSearch();
2411 search.setUpdateSequenceNum(0);
2412 search.setGuid(randint);
2413 search.setName(edit.getName());
2414 search.setQuery(edit.getQuery());
2415 search.setFormat(QueryFormat.USER);
2416 listManager.getSavedSearchIndex().add(search);
2417 conn.getSavedSearchTable().addSavedSearch(search, true);
2418 savedSearchIndexUpdated();
2419 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2421 // Edit an existing tag
2422 @SuppressWarnings("unused")
2423 private void editSavedSearch() {
2424 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2425 SavedSearchEdit edit = new SavedSearchEdit();
2426 edit.setTitle(tr("Edit Search"));
2427 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2428 QTreeWidgetItem currentSelection;
2429 currentSelection = selections.get(0);
2430 String guid = currentSelection.text(1);
2431 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2432 edit.setName(currentSelection.text(0));
2433 edit.setQuery(s.getQuery());
2434 edit.setSearchList(listManager.getSavedSearchIndex());
2437 if (!edit.okPressed())
2440 List<SavedSearch> list = listManager.getSavedSearchIndex();
2441 SavedSearch search = null;
2442 boolean found = false;
2443 for (int i=0; i<list.size(); i++) {
2444 search = list.get(i);
2445 if (search.getGuid().equals(guid)) {
2452 search.setName(edit.getName());
2453 search.setQuery(edit.getQuery());
2454 conn.getSavedSearchTable().updateSavedSearch(search, true);
2455 savedSearchIndexUpdated();
2456 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2458 // Delete an existing tag
2459 @SuppressWarnings("unused")
2460 private void deleteSavedSearch() {
2461 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2463 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2464 QMessageBox.StandardButton.Yes,
2465 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2469 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2470 for (int i=selections.size()-1; i>=0; i--) {
2471 QTreeWidgetItem currentSelection;
2472 currentSelection = selections.get(i);
2473 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2474 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2475 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2476 listManager.getSavedSearchIndex().remove(j);
2477 j=listManager.getSavedSearchIndex().size()+1;
2480 selections.remove(i);
2482 savedSearchIndexUpdated();
2483 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2485 // Setup the tree containing the user's tags
2486 private void initializeSavedSearchTree() {
2487 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2488 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2489 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2491 // Listener when a tag is selected
2492 @SuppressWarnings("unused")
2493 private void savedSearchTreeSelection() {
2494 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2496 clearNotebookFilter();
2499 clearAttributeFilter();
2501 String currentGuid = selectedSavedSearchGUID;
2502 menuBar.savedSearchEditAction.setEnabled(true);
2503 menuBar.savedSearchDeleteAction.setEnabled(true);
2504 menuBar.savedSearchIconAction.setEnabled(true);
2505 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2506 QTreeWidgetItem currentSelection;
2507 selectedSavedSearchGUID = "";
2508 for (int i=0; i<selections.size(); i++) {
2509 currentSelection = selections.get(i);
2510 if (currentSelection.text(1).equals(currentGuid)) {
2511 currentSelection.setSelected(false);
2513 selectedSavedSearchGUID = currentSelection.text(1);
2515 // i = selections.size() +1;
2518 // There is the potential for no notebooks to be selected if this
2519 // happens then we make it look like all notebooks were selecetd.
2520 // If that happens, just select the "all notebooks"
2521 if (selections.size()==0) {
2522 clearSavedSearchFilter();
2524 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2526 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2528 private void clearSavedSearchFilter() {
2529 menuBar.savedSearchEditAction.setEnabled(false);
2530 menuBar.savedSearchDeleteAction.setEnabled(false);
2531 menuBar.savedSearchIconAction.setEnabled(false);
2532 savedSearchTree.blockSignals(true);
2533 savedSearchTree.clearSelection();
2534 savedSearchTree.blockSignals(false);
2535 selectedSavedSearchGUID = "";
2536 searchField.setEditText("");
2537 searchPerformed = false;
2538 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2540 // trigger the tag index to be refreshed
2541 private void savedSearchIndexUpdated() {
2542 if (selectedSavedSearchGUID == null)
2543 selectedSavedSearchGUID = new String();
2544 savedSearchTree.blockSignals(true);
2545 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2546 savedSearchTree.load(listManager.getSavedSearchIndex());
2547 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2548 savedSearchTree.blockSignals(false);
2550 // trigger when the saved search selection changes
2551 @SuppressWarnings("unused")
2552 private void updateSavedSearchSelection() {
2553 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2555 menuBar.savedSearchEditAction.setEnabled(true);
2556 menuBar.savedSearchDeleteAction.setEnabled(true);
2557 menuBar.savedSearchIconAction.setEnabled(true);
2558 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2560 if (selections.size() > 0) {
2561 menuBar.savedSearchEditAction.setEnabled(true);
2562 menuBar.savedSearchDeleteAction.setEnabled(true);
2563 menuBar.savedSearchIconAction.setEnabled(true);
2564 selectedSavedSearchGUID = selections.get(0).text(1);
2565 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2566 searchField.setEditText(s.getQuery());
2568 menuBar.savedSearchEditAction.setEnabled(false);
2569 menuBar.savedSearchDeleteAction.setEnabled(false);
2570 menuBar.savedSearchIconAction.setEnabled(false);
2571 selectedSavedSearchGUID = "";
2572 searchField.setEditText("");
2574 searchFieldChanged();
2576 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2580 // Show/Hide note information
2581 @SuppressWarnings("unused")
2582 private void toggleSavedSearchWindow() {
2583 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2584 if (savedSearchTree.isVisible())
2585 savedSearchTree.hide();
2587 savedSearchTree.show();
2588 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2590 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2591 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2593 // Change the icon for a saved search
2594 @SuppressWarnings("unused")
2595 private void setSavedSearchIcon() {
2596 QTreeWidgetItem currentSelection;
2597 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2598 if (selections.size() == 0)
2601 currentSelection = selections.get(0);
2602 String guid = currentSelection.text(1);
2604 QIcon currentIcon = currentSelection.icon(0);
2605 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2608 dialog = new SetIcon(currentIcon, saveLastPath);
2609 dialog.setUseDefaultIcon(true);
2611 dialog = new SetIcon(icon, saveLastPath);
2612 dialog.setUseDefaultIcon(false);
2615 if (dialog.okPressed()) {
2616 saveLastPath = dialog.getPath();
2617 QIcon newIcon = dialog.getIcon();
2618 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2619 if (newIcon == null)
2620 newIcon = new QIcon(iconPath+"search.png");
2621 currentSelection.setIcon(0, newIcon);
2629 //***************************************************************
2630 //***************************************************************
2631 //** These functions deal with Help menu & tool menu items
2632 //***************************************************************
2633 //***************************************************************
2634 // Show database status
2635 @SuppressWarnings("unused")
2636 private void databaseStatus() {
2638 indexRunner.interrupt = true;
2639 int dirty = conn.getNoteTable().getDirtyCount();
2640 int unindexed = conn.getNoteTable().getUnindexedCount();
2641 DatabaseStatus status = new DatabaseStatus();
2642 status.setUnsynchronized(dirty);
2643 status.setUnindexed(unindexed);
2644 status.setNoteCount(conn.getNoteTable().getNoteCount());
2645 status.setNotebookCount(listManager.getNotebookIndex().size());
2646 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2647 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2648 status.setTagCount(listManager.getTagIndex().size());
2649 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2650 status.setWordCount(conn.getWordsTable().getWordCount());
2654 // Compact the database
2655 @SuppressWarnings("unused")
2656 private void compactDatabase() {
2657 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2658 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2659 "but please be aware that depending upon the size of your database this can be time consuming " +
2660 "and NixNote will be unresponsive until it is complete. Do you wish to continue?"),
2661 QMessageBox.StandardButton.Yes,
2662 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2665 setMessage("Compacting database.");
2667 listManager.compactDatabase();
2669 setMessage("Database compact is complete.");
2670 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2672 @SuppressWarnings("unused")
2673 private void accountInformation() {
2674 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2675 AccountDialog dialog = new AccountDialog();
2677 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2679 @SuppressWarnings("unused")
2680 private void releaseNotes() {
2681 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2682 QDialog dialog = new QDialog(this);
2683 QHBoxLayout layout = new QHBoxLayout();
2684 QTextEdit textBox = new QTextEdit();
2685 layout.addWidget(textBox);
2686 textBox.setReadOnly(true);
2687 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2688 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2689 QIODevice.OpenModeFlag.Text)))
2691 textBox.setText(file.readAll().toString());
2693 dialog.setWindowTitle(tr("Release Notes"));
2694 dialog.setLayout(layout);
2696 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2698 // Called when user picks Log from the help menu
2699 @SuppressWarnings("unused")
2700 private void logger() {
2701 logger.log(logger.HIGH, "Entering NeverNote.logger");
2702 LogFileDialog dialog = new LogFileDialog(emitLog);
2704 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2706 // Menu option "help/about" was selected
2707 @SuppressWarnings("unused")
2708 private void about() {
2709 logger.log(logger.HIGH, "Entering NeverNote.about");
2710 QMessageBox.about(this,
2711 tr("About NixNote"),
2712 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2714 +tr("<hr></center>Evernote"
2715 +"An Open Source Evernote Client.<br><br>"
2716 +"Licensed under GPL v2. <br><hr><br>"
2717 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2718 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2719 +"PDFRenderer is licened under the LGPL<br>"
2720 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2721 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2722 +"Jazzy is licened under the LGPL<br>"
2723 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2724 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2725 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2726 logger.log(logger.HIGH, "Leaving NeverNote.about");
2728 // Hide the entire left hand side
2729 @SuppressWarnings("unused")
2730 private void toggleLeftSide() {
2733 hidden = !menuBar.hideLeftSide.isChecked();
2734 menuBar.hideLeftSide.setChecked(!hidden);
2737 leftSplitter1.setHidden(true);
2739 leftSplitter1.setHidden(false);
2741 Global.saveWindowVisible("leftPanel", hidden);
2744 public void checkForUpdates() {
2745 // Send off thread to check for a new version
2746 versionChecker = new QNetworkAccessManager(this);
2747 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2748 QNetworkRequest request = new QNetworkRequest();
2749 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2750 versionChecker.get(request);
2752 @SuppressWarnings("unused")
2753 private void upgradeFileRead(QNetworkReply reply) {
2754 if (!reply.isReadable())
2757 String winVersion = Global.version;
2758 String osxVersion = Global.version;
2759 String linuxVersion = Global.version;
2760 String linux64Version = Global.version;
2761 String version = Global.version;
2763 // Determine the versions available
2764 QByteArray data = reply.readLine();
2765 while (data != null && !reply.atEnd()) {
2766 String line = data.toString();
2768 if (line.contains(":"))
2769 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2772 if (line.toLowerCase().contains("windows"))
2773 winVersion = lineVersion;
2774 else if (line.toLowerCase().contains("os-x"))
2775 osxVersion = lineVersion;
2776 else if (line.toLowerCase().contains("linux amd64"))
2777 linux64Version = lineVersion;
2778 else if (line.toLowerCase().contains("linux i386"))
2779 linuxVersion = lineVersion;
2780 else if (line.toLowerCase().contains("default"))
2781 version = lineVersion;
2783 // Read the next line
2784 data = reply.readLine();
2787 // Now we need to determine what system we are on.
2788 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2789 version = winVersion;
2790 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2791 version = osxVersion;
2792 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2793 if (System.getProperty("os.arch").contains("amd64") ||
2794 System.getProperty("os.arch").contains("x86_64"))
2795 version = linux64Version;
2797 version = linuxVersion;
2801 for (String validVersion : Global.validVersions) {
2802 if (version.equals(validVersion))
2806 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2808 if (dialog.remindMe())
2809 Global.setCheckVersionUpgrade(true);
2811 Global.setCheckVersionUpgrade(false);
2815 //***************************************************************
2816 //***************************************************************
2817 //** These functions deal with the Toolbar
2818 //***************************************************************
2819 //***************************************************************
2820 @SuppressWarnings("unused")
2821 private void focusSearch() {
2822 searchField.setFocus();
2825 // Text in the search bar has been cleared
2826 private void searchFieldCleared() {
2829 // This is done because we want to force a reload of
2830 // images. Some images we may want to highlight the text.
2831 readOnlyCache.clear();
2832 inkNoteCache.clear();
2834 QWebSettings.setMaximumPagesInCache(0);
2835 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2837 searchField.setEditText("");
2838 saveNoteColumnPositions();
2839 saveNoteIndexWidth();
2840 noteIndexUpdated(true);
2841 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2842 currentNote = listManager.getNoteIndex().get(0);
2843 currentNoteGuid = currentNote.getGuid();
2845 refreshEvernoteNote(true);
2846 if (currentNote != null)
2847 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2849 // text in the search bar changed. We only use this to tell if it was cleared,
2850 // otherwise we trigger off searchFieldChanged.
2851 @SuppressWarnings("unused")
2852 private void searchFieldTextChanged(String text) {
2853 QWebSettings.setMaximumPagesInCache(0);
2854 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2856 if (text.trim().equals("")) {
2857 searchFieldCleared();
2858 if (searchPerformed) {
2860 // This is done because we want to force a reload of
2861 // images. Some images we may want to highlight the text.
2863 readOnlyCache.clear();
2864 inkNoteCache.clear();
2866 listManager.setEnSearch("");
2867 listManager.loadNotesIndex();
2868 refreshEvernoteNote(true);
2869 noteIndexUpdated(false);
2870 refreshEvernoteNote(true);
2872 searchPerformed = false;
2875 // Text in the toolbar has changed
2876 private void searchFieldChanged() {
2877 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2879 readOnlyCache.clear();
2880 inkNoteCache.clear();
2881 saveNoteColumnPositions();
2882 saveNoteIndexWidth();
2883 String text = searchField.currentText();
2884 listManager.setEnSearch(text.trim());
2885 listManager.loadNotesIndex();
2886 noteIndexUpdated(false);
2887 refreshEvernoteNote(true);
2888 searchPerformed = true;
2889 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2892 // Build the window tool bar
2893 private void setupToolBar() {
2894 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2895 toolBar = addToolBar(tr("Tool Bar"));
2896 toolBar.setObjectName("toolBar");
2897 menuBar.setupToolBarVisible();
2898 if (!Global.isWindowVisible("toolBar"))
2899 toolBar.setVisible(false);
2901 toolBar.setVisible(true);
2903 // toolBar.addWidget(menuBar);
2904 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2905 // toolBar.addSeparator();
2906 prevButton = toolBar.addAction(tr("Previous"));
2907 QIcon prevIcon = new QIcon(iconPath+"back.png");
2908 prevButton.setIcon(prevIcon);
2909 prevButton.triggered.connect(this, "previousViewedAction()");
2910 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2912 nextButton = toolBar.addAction(tr("Next"));
2913 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2914 nextButton.setIcon(nextIcon);
2915 nextButton.triggered.connect(this, "nextViewedAction()");
2916 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2918 upButton = toolBar.addAction(tr("Up"));
2919 QIcon upIcon = new QIcon(iconPath+"up.png");
2920 upButton.setIcon(upIcon);
2921 upButton.triggered.connect(this, "upAction()");
2922 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2925 downButton = toolBar.addAction(tr("Down"));
2926 QIcon downIcon = new QIcon(iconPath+"down.png");
2927 downButton.setIcon(downIcon);
2928 downButton.triggered.connect(this, "downAction()");
2929 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2931 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2932 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2933 synchronizeIconAngle = 0;
2934 synchronizeButton.triggered.connect(this, "evernoteSync()");
2935 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2937 printButton = toolBar.addAction(tr("Print"));
2938 QIcon printIcon = new QIcon(iconPath+"print.png");
2939 printButton.setIcon(printIcon);
2940 printButton.triggered.connect(this, "printNote()");
2941 togglePrintButton(Global.isToolbarButtonVisible("print"));
2943 tagButton = toolBar.addAction(tr("Tag"));
2944 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2945 tagButton.setIcon(tagIcon);
2946 tagButton.triggered.connect(browserWindow, "modifyTags()");
2947 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2949 attributeButton = toolBar.addAction(tr("Attributes"));
2950 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2951 attributeButton.setIcon(attributeIcon);
2952 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2953 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2955 emailButton = toolBar.addAction(tr("Email"));
2956 QIcon emailIcon = new QIcon(iconPath+"email.png");
2957 emailButton.setIcon(emailIcon);
2958 emailButton.triggered.connect(this, "emailNote()");
2959 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2961 deleteButton = toolBar.addAction(tr("Delete"));
2962 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2963 deleteButton.setIcon(deleteIcon);
2964 deleteButton.triggered.connect(this, "deleteNote()");
2965 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2967 newButton = toolBar.addAction(tr("New"));
2968 QIcon newIcon = new QIcon(iconPath+"new.png");
2969 newButton.triggered.connect(this, "addNote()");
2970 newButton.setIcon(newIcon);
2971 toggleNewButton(Global.isToolbarButtonVisible("new"));
2973 allNotesButton = toolBar.addAction(tr("All Notes"));
2974 QIcon allIcon = new QIcon(iconPath+"books.png");
2975 allNotesButton.triggered.connect(this, "allNotes()");
2976 allNotesButton.setIcon(allIcon);
2977 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2979 //toolBar.addSeparator();
2980 //toolBar.addWidget(new QLabel(tr("Quota:")));
2981 //toolBar.addWidget(quotaBar);
2982 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2984 //toolBar.addSeparator();
2986 //toolBar.addWidget(new QLabel(tr("Zoom")));
2987 //toolBar.addWidget(zoomSpinner);
2989 //toolBar.addWidget(new QLabel(" "));
2990 //toolBar.addSeparator();
2991 //toolBar.addWidget(new QLabel(tr(" Search:")));
2992 //toolBar.addWidget(searchField);
2993 QSizePolicy sizePolicy = new QSizePolicy();
2994 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2995 QLabel spacer = new QLabel("");
2996 spacer.setSizePolicy(sizePolicy);
2997 toolBar.addWidget(spacer);
2998 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3000 //searchClearButton = toolBar.addAction("Search Clear");
3001 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3002 //searchClearButton.setIcon(searchClearIcon);
3003 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3004 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3006 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3008 // Update the sychronize button picture
3010 public QMenu createPopupMenu() {
3011 QMenu contextMenu = super.createPopupMenu();
3013 contextMenu.addSeparator();
3014 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3015 contextMenu.addAction(prevAction);
3016 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3018 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3019 contextMenu.addAction(nextAction);
3020 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3022 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3023 contextMenu.addAction(upAction);
3024 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3026 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3027 contextMenu.addAction(downAction);
3028 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3030 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3031 contextMenu.addAction(synchronizeAction);
3032 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3034 QAction printAction = addContextAction("print", tr("Print"));
3035 contextMenu.addAction(printAction);
3036 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3038 QAction tagAction = addContextAction("tag", tr("Tag"));
3039 contextMenu.addAction(tagAction);
3040 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3042 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3043 contextMenu.addAction(attributeAction);
3044 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3046 QAction emailAction = addContextAction("email", tr("Email"));
3047 contextMenu.addAction(emailAction);
3048 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3050 QAction deleteAction = addContextAction("delete", tr("Delete"));
3051 contextMenu.addAction(deleteAction);
3052 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3054 QAction newAction = addContextAction("new", tr("Add"));
3055 contextMenu.addAction(newAction);
3056 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3058 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3059 contextMenu.addAction(allNotesAction);
3060 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3062 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3063 contextMenu.addAction(searchClearAction);
3064 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3069 private QAction addContextAction(String config, String name) {
3070 QAction newAction = new QAction(this);
3071 newAction.setText(name);
3072 newAction.setCheckable(true);
3073 newAction.setChecked(Global.isToolbarButtonVisible(config));
3076 private void togglePrevArrowButton(Boolean toggle) {
3077 prevButton.setVisible(toggle);
3078 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3080 private void toggleNextArrowButton(Boolean toggle) {
3081 nextButton.setVisible(toggle);
3082 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3084 private void toggleUpArrowButton(Boolean toggle) {
3085 upButton.setVisible(toggle);
3086 Global.saveToolbarButtonsVisible("upArrow", toggle);
3088 private void toggleDownArrowButton(Boolean toggle) {
3089 downButton.setVisible(toggle);
3090 Global.saveToolbarButtonsVisible("downArrow", toggle);
3092 private void toggleSynchronizeButton(Boolean toggle) {
3093 synchronizeButton.setVisible(toggle);
3094 Global.saveToolbarButtonsVisible("synchronize", toggle);
3096 private void togglePrintButton(Boolean toggle) {
3097 printButton.setVisible(toggle);
3098 Global.saveToolbarButtonsVisible("print", toggle);
3100 private void toggleTagButton(Boolean toggle) {
3101 tagButton.setVisible(toggle);
3102 Global.saveToolbarButtonsVisible("tag", toggle);
3104 private void toggleAttributeButton(Boolean toggle) {
3105 attributeButton.setVisible(toggle);
3106 Global.saveToolbarButtonsVisible("attribute", toggle);
3108 private void toggleEmailButton(Boolean toggle) {
3109 emailButton.setVisible(toggle);
3110 Global.saveToolbarButtonsVisible("email", toggle);
3112 private void toggleDeleteButton(Boolean toggle) {
3113 deleteButton.setVisible(toggle);
3114 Global.saveToolbarButtonsVisible("delete", toggle);
3116 private void toggleNewButton(Boolean toggle) {
3117 newButton.setVisible(toggle);
3118 Global.saveToolbarButtonsVisible("new", toggle);
3120 private void toggleAllNotesButton(Boolean toggle) {
3121 allNotesButton.setVisible(toggle);
3122 Global.saveToolbarButtonsVisible("allNotes", toggle);
3124 @SuppressWarnings("unused")
3125 private void toggleSearchClearButton(Boolean toggle) {
3126 searchClearButton.setVisible(toggle);
3127 Global.saveToolbarButtonsVisible("searchClear", toggle);
3134 @SuppressWarnings("unused")
3135 private void updateSyncButton() {
3137 if (syncIcons == null) {
3138 syncIcons = new ArrayList<QPixmap>();
3140 synchronizeIconAngle = 0;
3141 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3143 for (int i=0; i<=360; i++) {
3144 QPixmap rotatedPix = new QPixmap(pix.size());
3145 QPainter p = new QPainter(rotatedPix);
3146 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3147 QSize size = pix.size();
3148 p.translate(size.width()/2, size.height()/2);
3151 p.setBackgroundMode(BGMode.OpaqueMode);
3152 p.translate(-size.width()/2, -size.height()/2);
3153 p.drawPixmap(0,0, pix);
3155 syncIcons.add(rotatedPix);
3159 synchronizeIconAngle++;
3160 if (synchronizeIconAngle > 359)
3161 synchronizeIconAngle=0;
3162 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3165 // Synchronize with Evernote
3167 private void evernoteSync() {
3168 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3169 if (!Global.isConnected)
3171 if (Global.isConnected)
3172 synchronizeAnimationTimer.start(5);
3173 // synchronizeAnimationTimer.start(200);
3175 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3177 private void updateQuotaBar() {
3178 long limit = Global.getUploadLimit();
3179 long amount = Global.getUploadAmount();
3180 if (amount>0 && limit>0) {
3181 int percent =(int)(amount*100/limit);
3182 quotaBar.setValue(percent);
3184 quotaBar.setValue(0);
3187 @SuppressWarnings("unused")
3188 private void zoomChanged() {
3189 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3192 //****************************************************************
3193 //****************************************************************
3194 //* System Tray functions
3195 //****************************************************************
3196 //****************************************************************
3197 private void trayToggleVisible() {
3202 if (windowMaximized)
3209 @SuppressWarnings("unused")
3210 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3211 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3212 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3213 trayToggleVisible();
3218 //***************************************************************
3219 //***************************************************************
3220 //** These functions deal with the trash tree
3221 //***************************************************************
3222 //***************************************************************
3223 // Setup the tree containing the trash.
3224 @SuppressWarnings("unused")
3225 private void trashTreeSelection() {
3226 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3228 clearNotebookFilter();
3230 clearAttributeFilter();
3231 clearSavedSearchFilter();
3233 String tempGuid = currentNoteGuid;
3235 // currentNoteGuid = "";
3236 currentNote = new Note();
3237 selectedNoteGUIDs.clear();
3238 listManager.getSelectedNotebooks().clear();
3239 listManager.getSelectedTags().clear();
3240 listManager.setSelectedSavedSearch("");
3241 browserWindow.clear();
3243 // toggle the add buttons
3244 newButton.setEnabled(!newButton.isEnabled());
3245 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3246 menuBar.noteAdd.setVisible(true);
3248 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3249 if (selections.size() == 0) {
3250 currentNoteGuid = trashNoteGuid;
3251 trashNoteGuid = tempGuid;
3252 Global.showDeleted = false;
3253 menuBar.noteRestoreAction.setEnabled(false);
3254 menuBar.noteRestoreAction.setVisible(false);
3257 currentNoteGuid = trashNoteGuid;
3258 trashNoteGuid = tempGuid;
3259 menuBar.noteRestoreAction.setEnabled(true);
3260 menuBar.noteRestoreAction.setVisible(true);
3261 Global.showDeleted = true;
3263 listManager.loadNotesIndex();
3264 noteIndexUpdated(false);
3265 //// browserWindow.setEnabled(newButton.isEnabled());
3266 browserWindow.setReadOnly(!newButton.isEnabled());
3267 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3269 // Empty the trash file
3270 @SuppressWarnings("unused")
3271 private void emptyTrash() {
3272 // browserWindow.clear();
3273 logger.log(logger.EXTREME, "Emptying Trash");
3274 listManager.emptyTrash();
3275 logger.log(logger.EXTREME, "Resetting view after trash empty");
3276 if (trashTree.selectedItems().size() > 0) {
3277 listManager.getSelectedNotebooks().clear();
3278 listManager.getSelectedTags().clear();
3279 listManager.setSelectedSavedSearch("");
3280 newButton.setEnabled(!newButton.isEnabled());
3281 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3282 menuBar.noteAdd.setVisible(true);
3283 browserWindow.clear();
3286 clearNotebookFilter();
3287 clearSavedSearchFilter();
3288 clearAttributeFilter();
3290 Global.showDeleted = false;
3291 menuBar.noteRestoreAction.setEnabled(false);
3292 menuBar.noteRestoreAction.setVisible(false);
3294 listManager.loadNotesIndex();
3295 noteIndexUpdated(false);
3298 // Show/Hide trash window
3299 @SuppressWarnings("unused")
3300 private void toggleTrashWindow() {
3301 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3302 if (trashTree.isVisible())
3306 menuBar.hideTrash.setChecked(trashTree.isVisible());
3308 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3309 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3311 private void clearTrashFilter() {
3312 Global.showDeleted = false;
3313 newButton.setEnabled(true);
3314 menuBar.noteAdd.setEnabled(true);
3315 menuBar.noteAdd.setVisible(true);
3316 trashTree.blockSignals(true);
3317 trashTree.clearSelection();
3318 trashTree.blockSignals(false);
3323 //***************************************************************
3324 //***************************************************************
3325 //** These functions deal with connection settings
3326 //***************************************************************
3327 //***************************************************************
3328 // SyncRunner had a problem and things are disconnected
3329 @SuppressWarnings("unused")
3330 private void remoteErrorDisconnect() {
3331 menuBar.connectAction.setText(tr("Connect"));
3332 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3333 menuBar.synchronizeAction.setEnabled(false);
3334 Global.isConnected = false;
3335 synchronizeAnimationTimer.stop();
3338 // Do a manual connect/disconnect
3339 private void remoteConnect() {
3340 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3342 if (Global.isConnected) {
3343 Global.isConnected = false;
3344 syncRunner.enDisconnect();
3345 setupConnectMenuOptions();
3350 AESEncrypter aes = new AESEncrypter();
3352 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3353 } catch (FileNotFoundException e) {
3354 // File not found, so we'll just get empty strings anyway.
3357 if (Global.getProxyValue("url").equals("")) {
3358 System.setProperty("http.proxyHost","") ;
3359 System.setProperty("http.proxyPort", "") ;
3360 System.setProperty("https.proxyHost","") ;
3361 System.setProperty("https.proxyPort", "") ;
3364 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3365 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3366 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3367 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3369 if (Global.getProxyValue("userid").equals("")) {
3370 Authenticator.setDefault(new Authenticator() {
3372 protected PasswordAuthentication getPasswordAuthentication() {
3374 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3380 syncRunner.userStoreUrl = Global.userStoreUrl;
3381 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3382 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3384 String userid = aes.getUserid();
3385 String password = aes.getPassword();
3386 if (!userid.equals("") && !password.equals("")) {
3387 Global.username = userid;
3388 Global.password = password;
3389 syncRunner.username = Global.username;
3390 syncRunner.password = Global.password;
3391 syncRunner.enConnect();
3394 Global.isConnected = syncRunner.isConnected;
3396 if (!Global.isConnected) {
3397 // Show the login dialog box
3398 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3399 LoginDialog login = new LoginDialog();
3402 if (!login.okPressed()) {
3406 Global.username = login.getUserid();
3407 Global.password = login.getPassword();
3409 syncRunner.username = Global.username;
3410 syncRunner.password = Global.password;
3411 syncRunner.enConnect();
3412 Global.isConnected = syncRunner.isConnected;
3415 if (!Global.isConnected)
3418 setupConnectMenuOptions();
3419 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3421 private void setupConnectMenuOptions() {
3422 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3423 if (!Global.isConnected) {
3424 menuBar.connectAction.setText(tr("Connect"));
3425 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3426 menuBar.synchronizeAction.setEnabled(false);
3428 menuBar.connectAction.setText(tr("Disconnect"));
3429 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3430 menuBar.synchronizeAction.setEnabled(true);
3432 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3437 //***************************************************************
3438 //***************************************************************
3439 //** These functions deal with the GUI Attribute tree
3440 //***************************************************************
3441 //***************************************************************
3442 @SuppressWarnings("unused")
3443 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3445 // clearTagFilter();
3446 // clearNotebookFilter();
3448 // clearSavedSearchFilter();
3450 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3451 if (item.childCount() > 0) {
3452 item.setSelected(false);
3454 Global.createdBeforeFilter.reset();
3455 Global.createdSinceFilter.reset();
3456 Global.changedBeforeFilter.reset();
3457 Global.changedSinceFilter.reset();
3458 Global.containsFilter.reset();
3459 attributeTreeSelected = item;
3460 DateAttributeFilterTable f = null;
3461 f = findDateAttributeFilterTable(item.parent());
3463 f.select(item.parent().indexOfChild(item));
3465 Global.containsFilter.select(item.parent().indexOfChild(item));
3468 listManager.loadNotesIndex();
3469 noteIndexUpdated(false);
3472 attributeTreeSelected = null;
3473 item.setSelected(false);
3474 Global.createdBeforeFilter.reset();
3475 Global.createdSinceFilter.reset();
3476 Global.changedBeforeFilter.reset();
3477 Global.changedSinceFilter.reset();
3478 Global.containsFilter.reset();
3479 listManager.loadNotesIndex();
3480 noteIndexUpdated(false);
3482 // This determines what attribute filter we need, depending upon the selection
3483 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3484 if (w.parent() != null && w.childCount() > 0) {
3485 QTreeWidgetItem parent = w.parent();
3486 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3487 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3488 return Global.createdSinceFilter;
3489 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3490 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3491 return Global.createdBeforeFilter;
3492 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3493 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3494 return Global.changedSinceFilter;
3495 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3496 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3497 return Global.changedBeforeFilter;
3502 // Show/Hide attribute search window
3503 @SuppressWarnings("unused")
3504 private void toggleAttributesWindow() {
3505 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3506 if (attributeTree.isVisible())
3507 attributeTree.hide();
3509 attributeTree.show();
3510 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3512 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3513 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3515 private void clearAttributeFilter() {
3516 Global.createdBeforeFilter.reset();
3517 Global.createdSinceFilter.reset();
3518 Global.changedBeforeFilter.reset();
3519 Global.changedSinceFilter.reset();
3520 Global.containsFilter.reset();
3521 attributeTreeSelected = null;
3522 attributeTree.blockSignals(true);
3523 attributeTree.clearSelection();
3524 attributeTree.blockSignals(false);
3528 //***************************************************************
3529 //***************************************************************
3530 //** These functions deal with the GUI Note index table
3531 //***************************************************************
3532 //***************************************************************
3533 // Initialize the note list table
3534 private void initializeNoteTable() {
3535 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3536 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3537 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3538 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3540 // Show/Hide trash window
3541 @SuppressWarnings("unused")
3542 private void toggleNoteListWindow() {
3543 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3544 if (noteTableView.isVisible())
3545 noteTableView.hide();
3547 noteTableView.show();
3548 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3550 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3551 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3553 // Handle the event that a user selects a note from the table
3554 @SuppressWarnings("unused")
3555 private void noteTableSelection() {
3556 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3560 // If the ctrl key is pressed, then they are selecting multiple
3561 // entries and we don't want to change the currently viewed note.
3562 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3563 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3566 if (historyGuids.size() == 0) {
3567 historyGuids.add(currentNoteGuid);
3568 historyPosition = 1;
3570 noteTableView.showColumn(Global.noteTableGuidPosition);
3572 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3573 if (!Global.isColumnVisible("guid"))
3574 noteTableView.hideColumn(Global.noteTableGuidPosition);
3576 if (selections.size() > 0) {
3578 menuBar.noteDuplicateAction.setEnabled(true);
3579 menuBar.noteOnlineHistoryAction.setEnabled(true);
3580 menuBar.noteMergeAction.setEnabled(true);
3581 selectedNoteGUIDs.clear();
3582 if (selections.size() != 1 || Global.showDeleted) {
3583 menuBar.noteDuplicateAction.setEnabled(false);
3585 if (selections.size() != 1 || !Global.isConnected) {
3586 menuBar.noteOnlineHistoryAction.setEnabled(false);
3588 if (selections.size() == 1) {
3589 menuBar.noteMergeAction.setEnabled(false);
3591 for (int i=0; i<selections.size(); i++) {
3592 int row = selections.get(i).row();
3594 upButton.setEnabled(false);
3596 upButton.setEnabled(true);
3597 if (row < listManager.getNoteTableModel().rowCount()-1)
3598 downButton.setEnabled(true);
3600 downButton.setEnabled(false);
3601 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3602 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3603 currentNoteGuid = (String)ix.values().toArray()[0];
3604 selectedNoteGUIDs.add(currentNoteGuid);
3608 nextButton.setEnabled(true);
3609 prevButton.setEnabled(true);
3611 int endPosition = historyGuids.size()-1;
3612 for (int j=historyPosition; j<=endPosition; j++) {
3613 historyGuids.remove(historyGuids.size()-1);
3615 historyGuids.add(currentNoteGuid);
3616 historyPosition = historyGuids.size();
3618 if (historyPosition <= 1)
3619 prevButton.setEnabled(false);
3620 if (historyPosition == historyGuids.size())
3621 nextButton.setEnabled(false);
3623 fromHistory = false;
3624 scrollToGuid(currentNoteGuid);
3625 refreshEvernoteNote(true);
3626 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3628 // Trigger a refresh when the note db has been updated
3629 private void noteIndexUpdated(boolean reload) {
3630 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3632 refreshEvernoteNoteList();
3633 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3634 noteTableView.load(reload);
3635 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3637 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3638 pos = noteTableView.proxyModel.rowCount();
3641 if (noteTableView.proxyModel.rowCount() == 0)
3644 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3646 currentNoteGuid = (String)i.data();
3650 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3652 scrollToGuid(currentNoteGuid);
3653 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3655 // Called when the list of notes is updated
3656 private void refreshEvernoteNoteList() {
3657 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3658 browserWindow.setDisabled(false);
3659 if (selectedNoteGUIDs == null)
3660 selectedNoteGUIDs = new ArrayList<String>();
3661 selectedNoteGUIDs.clear(); // clear out old entries
3663 String saveCurrentNoteGuid = new String();
3664 String tempNoteGuid = new String();
3666 historyGuids.clear();
3667 historyPosition = 0;
3668 prevButton.setEnabled(false);
3669 nextButton.setEnabled(false);
3671 if (currentNoteGuid == null)
3672 currentNoteGuid = new String();
3674 //determine current note guid
3675 for (Note note : listManager.getNoteIndex()) {
3676 tempNoteGuid = note.getGuid();
3677 if (currentNoteGuid.equals(tempNoteGuid)) {
3678 saveCurrentNoteGuid = tempNoteGuid;
3682 if (listManager.getNoteIndex().size() == 0) {
3683 currentNoteGuid = "";
3685 browserWindow.clear();
3686 browserWindow.setDisabled(true);
3689 if (!saveCurrentNoteGuid.equals("")) {
3690 refreshEvernoteNote(false);
3692 currentNoteGuid = "";
3694 reloadTagTree(false);
3696 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3698 // Called when the previous arrow button is clicked
3699 @SuppressWarnings("unused")
3700 private void previousViewedAction() {
3701 if (!prevButton.isEnabled())
3703 if (historyPosition == 0)
3706 if (historyPosition <= 0)
3708 String historyGuid = historyGuids.get(historyPosition-1);
3710 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3711 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3712 if (modelIndex != null) {
3713 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3714 String tableGuid = (String)ix.values().toArray()[0];
3715 if (tableGuid.equals(historyGuid)) {
3716 noteTableView.selectRow(i);
3722 @SuppressWarnings("unused")
3723 private void nextViewedAction() {
3724 if (!nextButton.isEnabled())
3726 String historyGuid = historyGuids.get(historyPosition);
3729 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3730 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3731 if (modelIndex != null) {
3732 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3733 String tableGuid = (String)ix.values().toArray()[0];
3734 if (tableGuid.equals(historyGuid)) {
3735 noteTableView.selectRow(i);
3741 // Called when the up arrow is clicked
3742 @SuppressWarnings("unused")
3743 private void upAction() {
3744 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3745 int row = selections.get(0).row();
3747 noteTableView.selectRow(row-1);
3750 // Called when the down arrow is clicked
3751 @SuppressWarnings("unused")
3752 private void downAction() {
3753 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3754 int row = selections.get(0).row();
3755 int max = listManager.getNoteTableModel().rowCount();
3757 noteTableView.selectRow(row+1);
3760 // Update a tag string for a specific note in the list
3761 @SuppressWarnings("unused")
3762 private void updateListTags(String guid, List<String> tags) {
3763 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3764 StringBuffer tagBuffer = new StringBuffer();
3765 for (int i=0; i<tags.size(); i++) {
3766 tagBuffer.append(tags.get(i));
3767 if (i<tags.size()-1)
3768 tagBuffer.append(", ");
3771 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3772 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3773 if (modelIndex != null) {
3774 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3775 String tableGuid = (String)ix.values().toArray()[0];
3776 if (tableGuid.equals(guid)) {
3777 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3778 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3779 noteTableView.proxyModel.invalidate();
3784 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3786 // Update a title for a specific note in the list
3787 @SuppressWarnings("unused")
3788 private void updateListAuthor(String guid, String author) {
3789 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3791 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3792 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3793 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3794 if (modelIndex != null) {
3795 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3796 String tableGuid = (String)ix.values().toArray()[0];
3797 if (tableGuid.equals(guid)) {
3798 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3799 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3800 noteTableView.proxyModel.invalidate();
3806 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3808 private void updateListNoteNotebook(String guid, String notebook) {
3809 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3810 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3811 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3813 // Update a title for a specific note in the list
3814 @SuppressWarnings("unused")
3815 private void updateListSourceUrl(String guid, String url) {
3816 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3818 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3819 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3820 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3821 if (modelIndex != null) {
3822 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3823 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3824 String tableGuid = (String)ix.values().toArray()[0];
3825 if (tableGuid.equals(guid)) {
3826 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3827 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3828 noteTableView.proxyModel.invalidate();
3833 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3835 @SuppressWarnings("unused")
3836 private void updateListGuid(String oldGuid, String newGuid) {
3837 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3839 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3840 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3841 if (modelIndex != null) {
3842 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3843 String tableGuid = (String)ix.values().toArray()[0];
3844 if (tableGuid.equals(oldGuid)) {
3845 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3846 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3851 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3853 private void updateListTagName(String guid) {
3854 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3856 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3857 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3858 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3860 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3861 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3862 if (modelIndex != null) {
3863 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3864 String noteGuid = (String)ix.values().toArray()[0];
3865 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3866 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3867 i=listManager.getNoteTableModel().rowCount();
3873 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3875 private void removeListTagName(String guid) {
3876 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3878 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3879 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3880 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3881 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3882 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3885 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3886 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3887 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3888 if (modelIndex != null) {
3889 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3890 String noteGuid = (String)ix.values().toArray()[0];
3891 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3892 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3893 i=listManager.getNoteTableModel().rowCount();
3899 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3901 private void updateListNotebookName(String oldName, String newName) {
3902 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3904 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3905 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3906 if (modelIndex != null) {
3907 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3908 String tableName = (String)ix.values().toArray()[0];
3909 if (tableName.equalsIgnoreCase(oldName)) {
3910 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3914 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3916 @SuppressWarnings("unused")
3917 private void updateListDateCreated(String guid, QDateTime date) {
3918 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3920 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3921 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3922 if (modelIndex != null) {
3923 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3924 String tableGuid = (String)ix.values().toArray()[0];
3925 if (tableGuid.equals(guid)) {
3926 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3927 noteTableView.proxyModel.invalidate();
3932 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3934 @SuppressWarnings("unused")
3935 private void updateListDateSubject(String guid, QDateTime date) {
3936 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3938 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3939 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3940 if (modelIndex != null) {
3941 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3942 String tableGuid = (String)ix.values().toArray()[0];
3943 if (tableGuid.equals(guid)) {
3944 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3945 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3946 noteTableView.proxyModel.invalidate();
3951 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3953 private void updateListDateChanged(String guid, QDateTime date) {
3954 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3956 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3957 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3958 if (modelIndex != null) {
3959 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3960 String tableGuid = (String)ix.values().toArray()[0];
3961 if (tableGuid.equals(guid)) {
3962 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3963 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3968 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3970 private void updateListDateChanged() {
3971 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3972 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3973 updateListDateChanged(currentNoteGuid, date);
3974 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3977 private void scrollToCurrentGuid() {
3978 //scrollToGuid(currentNoteGuid);
3979 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3980 if (selections.size() == 0)
3982 QModelIndex index = selections.get(0);
3983 int row = selections.get(0).row();
3984 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3987 // Scroll to the current GUID in tthe list.
3988 // Scroll to a particular index item
3989 private void scrollToGuid(String guid) {
3990 if (currentNote == null || guid == null)
3992 if (currentNote.isActive() && Global.showDeleted) {
3993 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3994 if (!listManager.getNoteIndex().get(i).isActive()) {
3995 currentNote = listManager.getNoteIndex().get(i);
3996 currentNoteGuid = currentNote.getGuid();
3997 i = listManager.getNoteIndex().size();
4001 if (!currentNote.isActive() && !Global.showDeleted) {
4002 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4003 if (listManager.getNoteIndex().get(i).isActive()) {
4004 currentNote = listManager.getNoteIndex().get(i);
4005 currentNoteGuid = currentNote.getGuid();
4006 i = listManager.getNoteIndex().size();
4011 for (int i=0; i<noteTableView.model().rowCount(); i++) {
4012 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4013 if (currentNoteGuid.equals(index.data())) {
4014 // noteTableView.selectionModel().blockSignals(true);
4015 noteTableView.selectRow(i);
4016 // noteTableView.selectionModel().blockSignals(false);
4017 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
4018 i=listManager.getNoteTableModel().rowCount();
4021 noteTableView.repaint();
4023 // Show/Hide columns
4024 private void showColumns() {
4025 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4026 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4027 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4028 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4029 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4030 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4031 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4032 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4033 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4034 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4035 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4037 // Title color has changed
4038 @SuppressWarnings("unused")
4039 private void titleColorChanged(Integer color) {
4040 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
4042 QColor backgroundColor = new QColor();
4043 QColor foregroundColor = new QColor(QColor.black);
4044 backgroundColor.setRgb(color);
4046 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4047 foregroundColor.setRgb(QColor.white.rgb());
4049 if (selectedNoteGUIDs.size() == 0)
4050 selectedNoteGUIDs.add(currentNoteGuid);
4052 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4053 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4054 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4055 if (modelIndex != null) {
4056 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4057 String tableGuid = (String)ix.values().toArray()[0];
4058 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4059 for (int k=0; k<Global.noteTableColumnCount; k++) {
4060 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4061 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4062 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4064 i=listManager.getNoteTableModel().rowCount();
4069 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
4071 // Wide list was chosen
4072 public void narrowListView() {
4073 saveNoteColumnPositions();
4074 saveNoteIndexWidth();
4076 int sortCol = noteTableView.proxyModel.sortColumn();
4077 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4078 Global.setSortColumn(sortCol);
4079 Global.setSortOrder(sortOrder);
4081 Global.setListView(Global.View_List_Narrow);
4083 menuBar.wideListView.blockSignals(true);
4084 menuBar.narrowListView.blockSignals(true);
4086 menuBar.wideListView.setChecked(false);
4087 menuBar.narrowListView.setChecked(true);
4089 menuBar.wideListView.blockSignals(false);
4090 menuBar.narrowListView.blockSignals(false);
4092 mainLeftRightSplitter.addWidget(noteTableView);
4093 mainLeftRightSplitter.addWidget(browserWindow);
4094 restoreWindowState(false);
4095 noteTableView.repositionColumns();
4096 noteTableView.resizeColumnWidths();
4097 noteTableView.resizeRowHeights();
4099 sortCol = Global.getSortColumn();
4100 sortOrder = Global.getSortOrder();
4101 noteTableView.proxyModel.blocked = true;
4102 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4103 noteTableView.proxyModel.blocked = false;
4107 noteTableView.load(false);
4108 refreshEvernoteNote(true);
4109 scrollToCurrentGuid();
4111 public void wideListView() {
4112 int sortCol = noteTableView.proxyModel.sortColumn();
4113 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4114 Global.setSortColumn(sortCol);
4115 Global.setSortOrder(sortOrder);
4118 saveNoteColumnPositions();
4119 saveNoteIndexWidth();
4120 Global.setListView(Global.View_List_Wide);
4122 menuBar.wideListView.blockSignals(true);
4123 menuBar.narrowListView.blockSignals(true);
4125 menuBar.wideListView.setChecked(true);
4126 menuBar.narrowListView.setChecked(false);
4128 menuBar.wideListView.blockSignals(false);
4129 menuBar.narrowListView.blockSignals(false);
4130 browserIndexSplitter.setVisible(true);
4131 browserIndexSplitter.addWidget(noteTableView);
4132 browserIndexSplitter.addWidget(browserWindow);
4133 restoreWindowState(false);
4134 noteTableView.repositionColumns();
4135 noteTableView.resizeColumnWidths();
4136 noteTableView.resizeRowHeights();
4138 sortCol = Global.getSortColumn();
4139 sortOrder = Global.getSortOrder();
4140 noteTableView.proxyModel.blocked = true;
4141 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4142 noteTableView.proxyModel.blocked = false;
4145 noteTableView.load(false);
4146 scrollToCurrentGuid();
4148 // Sort order for the notebook has changed
4149 public void tableSortOrderChanged(Integer column, Integer order) {
4151 // Find what notebook (if any) is selected. We ignore stacks & the "All Notebooks".
4152 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4153 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4154 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4156 notebook = currentSelectedNotebook.text(2);
4157 conn.getNotebookTable().setSortOrder(notebook, column, order);
4161 //***************************************************************
4162 @SuppressWarnings("unused")
4163 private void evernoteLinkClick(String syncGuid, String locGuid) {
4165 if (conn.getNoteTable().guidExists(syncGuid)) {
4168 // If we didn't find it via the synchronized guid, look under the local guid
4169 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4170 // later synchronized (that causes the guid to change so we need to find the new one).
4171 if (conn.getNoteTable().guidExists(locGuid))
4174 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4177 openExternalEditor(guid);
4181 //If we've gotten this far, we can't find the note
4182 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4183 " seem to find that note."));
4185 //***************************************************************
4186 //***************************************************************
4187 //** External editor window functions
4188 //***************************************************************
4189 //***************************************************************
4190 private void listDoubleClick() {
4192 openExternalEditor(currentNoteGuid);
4194 private void openExternalEditor(String guid) {
4196 if (externalWindows.containsKey(guid)) {
4197 externalWindows.get(guid).raise();
4200 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4201 // We have a new external editor to create
4202 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4203 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4204 newBrowser.setWindowIcon(appIcon);
4205 externalWindows.put(guid, newBrowser);
4206 showEditorButtons(newBrowser.getBrowserWindow());
4207 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4208 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4209 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4210 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4211 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4212 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4213 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4214 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4216 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4217 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4218 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4222 @SuppressWarnings("unused")
4223 private void externalWindowTitleEdited(String guid, String text) {
4224 if (guid.equals(currentNoteGuid)) {
4225 browserWindow.setTitle(text);
4228 @SuppressWarnings({ "rawtypes", "unused" })
4229 private void externalWindowTagsEdited(String guid, List values) {
4230 StringBuffer line = new StringBuffer(100);
4231 for (int i=0; i<values.size(); i++) {
4233 line.append(Global.tagDelimeter+" ");
4234 line.append(values.get(i));
4236 if (guid.equals(currentNoteGuid)) {
4237 browserWindow.setTag(line.toString());
4240 @SuppressWarnings("unused")
4241 private void externalWindowClosing(String guid) {
4242 externalWindows.remove(guid);
4247 //***************************************************************
4248 //***************************************************************
4249 //** These functions deal with Note specific things
4250 //***************************************************************
4251 //***************************************************************
4252 @SuppressWarnings("unused")
4253 private void setNoteDirty() {
4254 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4256 // Find if the note is being edited externally. If it is, update it.
4257 if (externalWindows.containsKey(currentNoteGuid)) {
4258 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4259 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4260 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4261 window.getBrowserWindow().setContent(unicode);
4264 // If the note is dirty, then it is unsynchronized by default.
4268 // Set the note as dirty and check if its status is synchronized in the display table
4270 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
4271 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
4275 // If this wasn't already marked as unsynchronized, then we need to update the table
4276 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4277 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4278 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4279 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4280 if (modelIndex != null) {
4281 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4282 String tableGuid = (String)ix.values().toArray()[0];
4283 if (tableGuid.equals(currentNoteGuid)) {
4284 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4290 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4292 @SuppressWarnings("unused")
4293 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4294 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4295 QByteArray unicode = codec.fromUnicode(content);
4296 noteCache.remove(guid);
4297 noteCache.put(guid, unicode.toString());
4298 if (guid.equals(currentNoteGuid)) {
4300 browserWindow.setContent(unicode);
4303 thumbnailRunner.addWork("GENERATE "+ guid);
4304 saveNote(guid, browser);
4308 private void saveNote() {
4310 saveNote(currentNoteGuid, browserWindow);
4311 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4315 private void saveNote(String guid, BrowserWindow window) {
4316 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4319 logger.log(logger.EXTREME, "Saving to cache");
4320 QTextCodec codec = QTextCodec.codecForLocale();
4321 // QTextDecoder decoder = codec.makeDecoder();
4322 codec = QTextCodec.codecForName("UTF-8");
4323 QByteArray unicode = codec.fromUnicode(window.getContent());
4324 noteCache.put(guid, unicode.toString());
4326 logger.log(logger.EXTREME, "updating list manager");
4327 listManager.updateNoteContent(guid, window.getContent());
4328 logger.log(logger.EXTREME, "Updating title");
4329 listManager.updateNoteTitle(guid, window.getTitle());
4330 updateListDateChanged();
4332 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4333 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4334 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4335 currentNote = listManager.getNoteIndex().get(i);
4336 i = listManager.getNoteIndex().size();
4341 // Get a note from Evernote (and put it in the browser)
4342 private void refreshEvernoteNote(boolean reload) {
4343 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4345 if (Global.disableViewing) {
4346 browserWindow.setEnabled(false);
4351 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4353 Global.cryptCounter =0;
4355 browserWindow.setReadOnly(true);
4363 browserWindow.loadingData(true);
4365 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4366 if (currentNote == null)
4368 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4371 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4372 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4373 formatter.setNote(note, Global.pdfPreview());
4374 formatter.setHighlight(listManager.getEnSearch());
4376 if (!noteCache.containsKey(guid)) {
4377 js = new QByteArray();
4378 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4379 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4380 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>");
4381 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4382 js.append("<style> img { max-width:100%; }</style>");
4383 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4384 js.append("</head>");
4385 formatter.setNote(note, Global.pdfPreview());
4386 js.append(formatter.rebuildNoteHTML());
4387 js.append("</HTML>");
4388 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4389 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4390 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4391 // if (Global.enableHTMLEntitiesFix) {
4392 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4394 browser.setContent(js);
4395 noteCache.put(guid, js.toString());
4397 if (formatter.resourceError)
4398 resourceErrorMessage();
4399 if (formatter.formatError) {
4401 QMessageBox.information(this, tr("Error"),
4402 tr("NixNote had issues formatting this note." +
4403 " To protect your data this note is being marked as read-only."));
4406 readOnly = formatter.readOnly;
4407 inkNote = formatter.inkNote;
4409 readOnlyCache.put(guid, true);
4411 inkNoteCache.put(guid, true);
4413 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4414 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4415 js = new QByteArray(cachedContent);
4416 browser.setContent(js);
4417 if (readOnlyCache.containsKey(guid))
4419 if (inkNoteCache.containsKey(guid))
4422 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4423 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4425 if (readOnly || inkNote)
4426 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4428 browser.getBrowser().page().setContentEditable(true);
4429 browser.setReadOnly(readOnly);
4430 deleteButton.setEnabled(!readOnly);
4431 tagButton.setEnabled(!readOnly);
4432 menuBar.noteDelete.setEnabled(!readOnly);
4433 menuBar.noteTags.setEnabled(!readOnly);
4434 browser.setNote(note);
4436 if (note != null && note.getNotebookGuid() != null &&
4437 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4438 deleteButton.setEnabled(false);
4439 menuBar.notebookDeleteAction.setEnabled(false);
4441 deleteButton.setEnabled(true);
4442 menuBar.notebookDeleteAction.setEnabled(true);
4445 // Build a list of non-closed notebooks
4446 List<Notebook> nbooks = new ArrayList<Notebook>();
4447 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4448 boolean found=false;
4449 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4450 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4454 nbooks.add(listManager.getNotebookIndex().get(i));
4457 browser.setTitle(note.getTitle());
4458 browser.setTag(getTagNamesForNote(note));
4459 browser.setAuthor(note.getAttributes().getAuthor());
4461 browser.setAltered(note.getUpdated());
4462 browser.setCreation(note.getCreated());
4463 if (note.getAttributes().getSubjectDate() > 0)
4464 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4466 browser.setSubjectDate(note.getCreated());
4467 browser.setUrl(note.getAttributes().getSourceURL());
4469 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4470 List<Tag> tagList = tagFilter.getValidTags(note);
4471 browser.setAllTags(tagList);
4473 browser.setCurrentTags(note.getTagNames());
4477 browser.loadingData(false);
4478 if (thumbnailViewer.isActiveWindow())
4481 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4482 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4485 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4487 // Save a generated thumbnail
4488 private void toggleNoteInformation() {
4489 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4490 browserWindow.toggleInformation();
4491 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4492 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4493 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4495 // Listener triggered when a print button is pressed
4496 @SuppressWarnings("unused")
4497 private void printNote() {
4498 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4500 QPrintDialog dialog = new QPrintDialog();
4501 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4502 QPrinter printer = dialog.printer();
4503 browserWindow.getBrowser().print(printer);
4505 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4508 // Listener triggered when the email button is pressed
4509 @SuppressWarnings("unused")
4510 private void emailNote() {
4511 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4513 if (Desktop.isDesktopSupported()) {
4514 Desktop desktop = Desktop.getDesktop();
4516 String text2 = browserWindow.getContentsToEmail();
4517 QUrl url = new QUrl("mailto:");
4518 url.addQueryItem("subject", currentNote.getTitle());
4519 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4520 url.addQueryItem("body", text2);
4521 QDesktopServices.openUrl(url);
4525 if (desktop.isSupported(Desktop.Action.MAIL)) {
4526 URI uriMailTo = null;
4528 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4529 String text = browserWindow.getContentsToEmail();
4530 //text = "<b>" +text +"</b>";
4531 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4532 +"&BODY=" +text, null);
4533 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4534 +"&ATTACHMENT=d:/test.pdf", null);
4535 desktop.mail(uriMailTo);
4536 } catch (URISyntaxException e) {
4537 e.printStackTrace();
4538 } catch (IOException e) {
4539 e.printStackTrace();
4546 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4548 // Reindex all notes
4549 @SuppressWarnings("unused")
4550 private void fullReindex() {
4551 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4552 indexRunner.addWork("REINDEXALL");
4553 setMessage(tr("Database will be reindexed."));
4554 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4556 // Listener when a user wants to reindex a specific note
4557 @SuppressWarnings("unused")
4558 private void reindexNote() {
4559 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4560 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4561 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4563 if (selectedNotebookGUIDs.size() > 1)
4564 setMessage(tr("Notes will be reindexed."));
4566 setMessage(tr("Note will be reindexed."));
4567 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4570 @SuppressWarnings("unused")
4571 private void deleteNote() {
4572 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4573 if (currentNote == null)
4575 if (currentNoteGuid.equals(""))
4577 String title = null;
4578 if (selectedNoteGUIDs.size() == 1)
4579 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4581 // If we are deleting non-trash notes
4582 if (currentNote.isActive()) {
4583 if (Global.verifyDelete()) {
4585 if (selectedNoteGUIDs.size() > 1) {
4586 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4589 msg = new String(tr("Delete note \"") +title +"\"?");
4591 msg = new String(tr("Delete note selected note?"));
4593 if (QMessageBox.question(this, tr("Confirmation"), msg,
4594 QMessageBox.StandardButton.Yes,
4595 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4599 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4600 selectedNoteGUIDs.add(currentNoteGuid);
4601 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4602 listManager.deleteNote(selectedNoteGUIDs.get(i));
4605 // If we are deleting from the trash.
4606 if (Global.verifyDelete()) {
4608 if (selectedNoteGUIDs.size() > 1) {
4609 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4612 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4614 msg = new String(tr("Permanently delete note selected note?"));
4616 if (QMessageBox.question(this, "Confirmation", msg,
4617 QMessageBox.StandardButton.Yes,
4618 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4622 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4623 selectedNoteGUIDs.add(currentNoteGuid);
4624 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4625 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4626 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4627 if (modelIndex != null) {
4628 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4629 String tableGuid = (String)ix.values().toArray()[0];
4630 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4631 listManager.getNoteTableModel().removeRow(j);
4636 listManager.expungeNote(selectedNoteGUIDs.get(i));
4639 currentNoteGuid = "";
4640 listManager.loadNotesIndex();
4641 noteIndexUpdated(false);
4642 refreshEvernoteNote(true);
4643 scrollToGuid(currentNoteGuid);
4644 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4647 @SuppressWarnings("unused")
4648 private void addNote() {
4649 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4650 // browserWindow.setEnabled(true);
4651 browserWindow.setReadOnly(false);
4653 Calendar currentTime = new GregorianCalendar();
4654 StringBuffer noteString = new StringBuffer(100);
4655 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4656 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4659 if (Global.overrideDefaultFont()) {
4660 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4661 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4662 noteString.append("<br clear=\"none\" />\n");
4663 noteString.append("</span>\n</font>\n");
4665 noteString.append("<br clear=\"none\" />\n");
4666 noteString.append("</en-note>");
4668 Long l = new Long(currentTime.getTimeInMillis());
4669 String randint = new String(Long.toString(l));
4671 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4673 // for the first non-archived notebook. Finally, if nothing else we
4674 // pick the first notebook in the list.
4675 String notebook = null;
4676 listManager.getNotebookIndex().get(0).getGuid();
4677 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4678 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4679 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4680 notebook = currentSelectedNotebook.text(2);
4682 boolean found = false;
4683 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4684 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4685 boolean match = false;
4686 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4687 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4689 j = listManager.getArchiveNotebookIndex().size();
4693 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4694 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4696 // Now we have a list of good notebooks, so we can look for the default
4698 for (int i=0; i<goodNotebooks.size(); i++) {
4699 if (goodNotebooks.get(i).isDefaultNotebook()) {
4700 notebook = goodNotebooks.get(i).getGuid();
4702 i = goodNotebooks.size();
4706 if (goodNotebooks.size() > 0 && !found)
4707 notebook = goodNotebooks.get(0).getGuid();
4710 notebook = listManager.getNotebookIndex().get(0).getGuid();
4713 Note newNote = new Note();
4714 newNote.setUpdateSequenceNum(0);
4715 newNote.setGuid(randint);
4716 newNote.setNotebookGuid(notebook);
4717 newNote.setTitle("Untitled Note");
4718 newNote.setContent(noteString.toString());
4719 newNote.setDeleted(0);
4720 newNote.setCreated(System.currentTimeMillis());
4721 newNote.setUpdated(System.currentTimeMillis());
4722 newNote.setActive(true);
4723 NoteAttributes na = new NoteAttributes();
4724 na.setLatitude(0.0);
4725 na.setLongitude(0.0);
4726 na.setAltitude(0.0);
4727 newNote.setAttributes(new NoteAttributes());
4728 newNote.setTagGuids(new ArrayList<String>());
4729 newNote.setTagNames(new ArrayList<String>());
4731 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4732 if (Global.newNoteWithSelectedTags()) {
4733 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4734 QTreeWidgetItem currentSelection;
4735 for (int i=0; i<selections.size(); i++) {
4736 currentSelection = selections.get(i);
4737 newNote.getTagGuids().add(currentSelection.text(2));
4738 newNote.getTagNames().add(currentSelection.text(0));
4742 conn.getNoteTable().addNote(newNote, true);
4743 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4744 listManager.addNote(newNote);
4745 // noteTableView.insertRow(newNote, true, -1);
4747 currentNote = newNote;
4748 currentNoteGuid = currentNote.getGuid();
4749 noteTableView.clearSelection();
4750 refreshEvernoteNote(true);
4751 listManager.countNotebookResults(listManager.getNoteIndex());
4752 browserWindow.titleLabel.setFocus();
4753 browserWindow.titleLabel.selectAll();
4754 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4756 // If the window is hidden, then we want to popup this in an external window &
4760 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4762 // Restore a note from the trash;
4763 @SuppressWarnings("unused")
4764 private void restoreNote() {
4766 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4767 selectedNoteGUIDs.add(currentNoteGuid);
4768 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4769 listManager.restoreNote(selectedNoteGUIDs.get(i));
4771 currentNoteGuid = "";
4772 listManager.loadNotesIndex();
4773 noteIndexUpdated(false);
4776 // Search a note for specific txt
4777 @SuppressWarnings("unused")
4778 private void findText() {
4780 find.setFocusOnTextField();
4782 @SuppressWarnings("unused")
4783 private void doFindText() {
4784 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4787 @SuppressWarnings("unused")
4788 private void updateNoteTitle(String guid, String title) {
4789 listManager.setNoteSynchronized(guid, false);
4791 // Signal received that note content has changed. Normally we just need the guid to remove
4792 // it from the cache.
4793 @SuppressWarnings("unused")
4794 private void invalidateNoteCache(String guid, String content) {
4795 noteCache.remove(guid);
4796 refreshEvernoteNote(true);
4798 // Signal received that a note guid has changed
4799 @SuppressWarnings("unused")
4800 private void noteGuidChanged(String oldGuid, String newGuid) {
4801 if (noteCache.containsKey(oldGuid)) {
4802 if (!oldGuid.equals(currentNoteGuid)) {
4803 String cache = noteCache.get(oldGuid);
4804 noteCache.put(newGuid, cache);
4805 noteCache.remove(oldGuid);
4807 noteCache.remove(oldGuid);
4808 noteCache.put(newGuid, browserWindow.getContent());
4812 listManager.updateNoteGuid(oldGuid, newGuid, false);
4813 if (currentNoteGuid.equals(oldGuid)) {
4814 if (currentNote != null)
4815 currentNote.setGuid(newGuid);
4816 currentNoteGuid = newGuid;
4819 if (externalWindows.containsKey(oldGuid)) {
4820 ExternalBrowse b = externalWindows.get(oldGuid);
4821 externalWindows.remove(oldGuid);
4822 b.getBrowserWindow().getNote().setGuid(newGuid);
4823 externalWindows.put(newGuid, b);
4826 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4827 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4828 noteTableView.proxyModel.addGuid(newGuid);
4829 i=listManager.getNoteIndex().size();
4833 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4834 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4835 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4836 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4840 // Toggle the note editor button bar
4841 private void toggleEditorButtonBar() {
4842 if (browserWindow.buttonsVisible) {
4843 browserWindow.hideButtons();
4844 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4845 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4847 browserWindow.buttonsVisible = true;
4848 showEditorButtons(browserWindow);
4850 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4852 // Show editor buttons
4853 private void showEditorButtons(BrowserWindow browser) {
4854 browser.buttonLayout.setVisible(true);
4855 browser.undoAction.setVisible(false);
4857 browser.undoButton.setVisible(false);
4859 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4860 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4861 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4862 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4863 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4864 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4865 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4866 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4867 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4868 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4869 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4870 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4871 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4872 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4873 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4874 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4875 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4876 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4877 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4878 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4879 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4880 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4881 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4883 private void duplicateNote(String guid) {
4885 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4886 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4887 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4888 oldNote.setResources(resList);
4889 duplicateNote(oldNote);
4891 private void duplicateNote(Note oldNote) {
4893 // Now that we have a good notebook guid, we need to move the conflicting note
4894 // to the local notebook
4895 Calendar currentTime = new GregorianCalendar();
4896 Long l = new Long(currentTime.getTimeInMillis());
4897 String newGuid = new String(Long.toString(l));
4899 // Note newNote = oldNote.deepCopy();
4900 Note newNote = (Note)Global.deepCopy(oldNote);
4901 newNote.setUpdateSequenceNum(0);
4902 newNote.setGuid(newGuid);
4903 newNote.setDeleted(0);
4904 newNote.setActive(true);
4907 List<String> tagNames = new ArrayList<String>();
4908 List<String> tagGuids = new ArrayList<String>();;
4909 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4910 tagNames.add(oldNote.getTagNames().get(i));
4911 tagGuids.add(oldNote.getTagGuids().get(i));
4914 // Sort note Tags to make them look nice
4915 for (int i=0; i<tagNames.size()-1; i++) {
4916 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4917 String n1 = tagNames.get(i);
4918 String n2 = tagNames.get(i+1);
4919 tagNames.set(i, n2);
4920 tagNames.set(i+1, n1);
4923 newNote.setTagGuids(tagGuids);
4924 newNote.setTagNames(tagNames);
4926 // Add tag guids to note
4929 // Duplicate resources
4930 List<Resource> resList = oldNote.getResources();
4931 if (resList == null)
4932 resList = new ArrayList<Resource>();
4934 for (int i=0; i<resList.size(); i++) {
4936 while (l == prevGuid) {
4937 currentTime = new GregorianCalendar();
4938 l = new Long(currentTime.getTimeInMillis());
4941 String newResGuid = new String(Long.toString(l));
4942 resList.get(i).setNoteGuid(newGuid);
4943 resList.get(i).setGuid(newResGuid);
4944 resList.get(i).setUpdateSequenceNum(0);
4945 resList.get(i).setActive(true);
4946 conn.getNoteTable().noteResourceTable.saveNoteResource(
4947 (Resource)Global.deepCopy(resList.get(i)), true);
4949 newNote.setResources(resList);
4951 // Add note to the database
4952 listManager.addNote(newNote);
4953 conn.getNoteTable().addNote(newNote, true);
4954 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4955 noteTableView.insertRow(newNote, true, -1);
4956 currentNoteGuid = newNote.getGuid();
4957 currentNote = newNote;
4958 refreshEvernoteNote(true);
4959 listManager.countNotebookResults(listManager.getNoteIndex());
4963 @SuppressWarnings("unused")
4964 private void allNotes() {
4965 clearAttributeFilter();
4966 clearNotebookFilter();
4967 clearSavedSearchFilter();
4970 searchField.clear();
4971 if (Global.mimicEvernoteInterface) {
4972 notebookTree.selectGuid("");
4974 notebookTreeSelection();
4975 refreshEvernoteNote(true);
4978 @SuppressWarnings("unused")
4979 private void mergeNotes() {
4980 logger.log(logger.HIGH, "Merging notes");
4983 String masterGuid = null;
4984 List<String> sources = new ArrayList<String>();
4986 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4987 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4988 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4989 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4991 masterGuid = (String)ix.values().toArray()[0];
4993 sources.add((String)ix.values().toArray()[0]);
4996 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4997 logger.log(logger.EXTREME, "Children count: "+sources.size());
4998 mergeNoteContents(masterGuid, sources);
4999 currentNoteGuid = masterGuid;
5000 noteIndexUpdated(false);
5001 refreshEvernoteNote(true);
5004 private void mergeNoteContents(String targetGuid, List<String> sources) {
5005 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
5006 String newContent = target.getContent();
5007 newContent = newContent.replace("</en-note>", "<br></br>");
5009 for (int i=0; i<sources.size(); i++) {
5010 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
5011 if (source.isSetTitle()) {
5012 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
5014 String sourceContent = source.getContent();
5015 logger.log(logger.EXTREME, "Merging contents into note");
5016 logger.log(logger.EXTREME, sourceContent);
5017 logger.log(logger.EXTREME, "End of content");
5018 int startOfNote = sourceContent.indexOf("<en-note>");
5019 sourceContent = sourceContent.substring(startOfNote+9);
5020 int endOfNote = sourceContent.indexOf("</en-note>");
5021 sourceContent = sourceContent.substring(0,endOfNote);
5022 newContent = newContent + sourceContent;
5023 logger.log(logger.EXTREME, "New note content");
5024 logger.log(logger.EXTREME, newContent);
5025 logger.log(logger.EXTREME, "End of content");
5026 for (int j=0; j<source.getResourcesSize(); j++) {
5027 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
5028 Resource r = source.getResources().get(j);
5029 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
5031 Calendar currentTime = new GregorianCalendar();
5032 Long l = new Long(currentTime.getTimeInMillis());
5036 while (l == prevGuid) {
5037 currentTime = new GregorianCalendar();
5038 l = new Long(currentTime.getTimeInMillis());
5040 String newResGuid = new String(Long.toString(l));
5041 newRes.setNoteGuid(targetGuid);
5042 newRes.setGuid(newResGuid);
5043 newRes.setUpdateSequenceNum(0);
5044 newRes.setActive(true);
5045 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5048 logger.log(logger.EXTREME, "Updating note");
5049 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5050 for (int i=0; i<sources.size(); i++) {
5051 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5052 listManager.deleteNote(sources.get(i));
5054 logger.log(logger.EXTREME, "Exiting merge note");
5056 // A resource within a note has had a guid change
5057 @SuppressWarnings("unused")
5058 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5059 if (oldGuid != null && !oldGuid.equals(newGuid))
5060 Global.resourceMap.put(oldGuid, newGuid);
5062 // View a thumbnail of the note
5063 public void thumbnailView() {
5065 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5066 QFile thumbnail = new QFile(thumbnailName);
5067 if (!thumbnail.exists()) {
5069 QImage img = new QImage();
5070 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5071 thumbnailViewer.setThumbnail(img);
5073 thumbnailViewer.setThumbnail(thumbnailName);
5074 if (!thumbnailViewer.isVisible())
5075 thumbnailViewer.showFullScreen();
5077 // An error happened while saving a note. Inform the user
5078 @SuppressWarnings("unused")
5079 private void saveRunnerError(String guid, String msg) {
5081 String title = "*Unknown*";
5082 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5083 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5084 title = listManager.getMasterNoteIndex().get(i).getTitle();
5085 i=listManager.getMasterNoteIndex().size();
5088 msg = tr("An error has happened while saving the note \"") +title+
5089 tr("\".\n\nThis is probably due to a document that is too complex for NixNote to process. "+
5090 "As a result, changes to the note may not be saved properly in the database."+
5091 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5092 "\nbe lost. Please review the note to recover any critical data before restarting.");
5094 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5097 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5098 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5099 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5100 // Find an idle preview object
5101 for (int i=0; i<thumbGenerators.size(); i++) {
5102 if (thumbGenerators.get(i).mutex.tryLock()) {
5103 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5104 thumbGenerators.get(i).loadContent(guid, html, zoom);
5108 if (thumbGenerators.size() >= 1) {
5109 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5113 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5114 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5115 thumbGenerators.add(preview);
5117 if (preview.mutex.tryLock()) {
5118 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5119 preview.loadContent(guid, html, zoom);
5121 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5126 //**********************************************************
5127 //**********************************************************
5128 //* Online user actions
5129 //**********************************************************
5130 //**********************************************************
5131 private void setupOnlineMenu() {
5132 if (!Global.isConnected) {
5133 menuBar.noteOnlineHistoryAction.setEnabled(false);
5134 menuBar.selectiveSyncAction.setEnabled(false);
5137 menuBar.noteOnlineHistoryAction.setEnabled(true);
5138 menuBar.selectiveSyncAction.setEnabled(true);
5141 @SuppressWarnings("unused")
5142 private void viewNoteHistory() {
5143 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5145 if (currentNote.getUpdateSequenceNum() == 0) {
5146 setMessage(tr("Note has never been synchronized."));
5147 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5151 setMessage(tr("Getting Note History"));
5153 Note currentOnlineNote = null;
5156 if (Global.isPremium())
5157 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5159 versions = new ArrayList<NoteVersionId>();
5160 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5161 } catch (EDAMUserException e) {
5162 setMessage("EDAMUserException: " +e.getMessage());
5164 } catch (EDAMSystemException e) {
5165 setMessage("EDAMSystemException: " +e.getMessage());
5167 } catch (EDAMNotFoundException e) {
5168 setMessage(tr("Note not found on server."));
5169 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5171 } catch (TException e) {
5172 setMessage("EDAMTransactionException: " +e.getMessage());
5176 // If we've gotten this far, we have a good note.
5177 if (historyWindow == null) {
5178 historyWindow = new OnlineNoteHistory(logger, conn);
5179 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5180 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5181 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5183 historyWindow.historyCombo.clear();
5185 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5186 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5188 historyWindow.setCurrent(isDirty);
5190 loadHistoryWindowContent(currentOnlineNote);
5191 historyWindow.load(versions);
5192 setMessage(tr("History retrieved"));
5194 historyWindow.exec();
5196 private Note reloadHistoryWindow(String selection) {
5198 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5199 String dateTimeFormat = new String(fmt);
5200 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5204 for (int i=0; i<versions.size(); i++) {
5205 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5206 if (versionDate.toString().equals(selection))
5210 if (index > -1 || selection.indexOf("Current") > -1) {
5211 Note historyNote = null;
5214 usn = versions.get(index).getUpdateSequenceNum();
5215 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5217 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5218 } catch (EDAMUserException e) {
5219 setMessage("EDAMUserException: " +e.getMessage());
5222 } catch (EDAMSystemException e) {
5223 setMessage("EDAMSystemException: " +e.getMessage());
5226 } catch (EDAMNotFoundException e) {
5227 setMessage("EDAMNotFoundException: " +e.getMessage());
5230 } catch (TException e) {
5231 setMessage("EDAMTransactionException: " +e.getMessage());
5237 if (historyNote != null)
5238 historyWindow.setContent(historyNote);
5244 private void loadHistoryWindowContent(Note note) {
5245 note.setUpdateSequenceNum(0);
5246 historyWindow.setContent(note);
5248 @SuppressWarnings("unused")
5249 private void restoreHistoryNoteAsNew() {
5250 setMessage(tr("Restoring as new note."));
5251 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5252 setMessage(tr("Note has been restored as a new note."));
5254 @SuppressWarnings("unused")
5255 private void restoreHistoryNote() {
5256 setMessage(tr("Restoring note."));
5257 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5258 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5261 for (int i=0; i<n.getResourcesSize(); i++) {
5262 n.getResources().get(i).setActive(true);
5263 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5265 listManager.addNote(n);
5266 conn.getNoteTable().addNote(n, true);
5267 refreshEvernoteNote(true);
5268 setMessage(tr("Note has been restored."));
5270 @SuppressWarnings("unused")
5271 private void setupSelectiveSync() {
5273 // Get a list of valid notebooks
5274 List<Notebook> notebooks = null;
5275 List<Tag> tags = null;
5276 List<LinkedNotebook> linkedNotebooks = null;
5278 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5279 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5280 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5281 } catch (EDAMUserException e) {
5282 setMessage("EDAMUserException: " +e.getMessage());
5284 } catch (EDAMSystemException e) {
5285 setMessage("EDAMSystemException: " +e.getMessage());
5287 } catch (TException e) {
5288 setMessage("EDAMTransactionException: " +e.getMessage());
5290 } catch (EDAMNotFoundException e) {
5291 setMessage("EDAMNotFoundException: " +e.getMessage());
5295 // Split up notebooks into synchronized & non-synchronized
5296 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5297 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5299 for (int i=notebooks.size()-1; i>=0; i--) {
5300 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5301 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5302 ignoredBooks.add(notebooks.get(i));
5303 j=dbIgnoredNotebooks.size();
5308 // split up tags into synchronized & non-synchronized
5309 List<Tag> ignoredTags = new ArrayList<Tag>();
5310 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5312 for (int i=tags.size()-1; i>=0; i--) {
5313 for (int j=0; j<dbIgnoredTags.size(); j++) {
5314 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5315 ignoredTags.add(tags.get(i));
5316 j=dbIgnoredTags.size();
5321 // split up linked notebooks into synchronized & non-synchronized
5322 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5323 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5324 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5325 String notebookGuid = linkedNotebooks.get(i).getGuid();
5326 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5327 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5328 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5329 j=dbIgnoredLinkedNotebooks.size();
5334 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5336 if (!ignore.okClicked())
5341 // Clear out old notebooks & add the new ones
5342 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5343 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5344 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5347 List<String> newNotebooks = new ArrayList<String>();
5348 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5349 String text = ignore.getIgnoredBookList().takeItem(i).text();
5350 for (int j=0; j<notebooks.size(); j++) {
5351 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5352 Notebook n = notebooks.get(j);
5353 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5355 newNotebooks.add(n.getGuid());
5360 // Clear out old tags & add new ones
5361 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5362 for (int i=0; i<oldIgnoreTags.size(); i++) {
5363 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5366 List<String> newTags = new ArrayList<String>();
5367 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5368 String text = ignore.getIgnoredTagList().takeItem(i).text();
5369 for (int j=0; j<tags.size(); j++) {
5370 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5371 Tag t = tags.get(j);
5372 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5373 newTags.add(t.getGuid());
5379 // Clear out old tags & add new ones
5380 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5381 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5382 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5385 List<String> newLinked = new ArrayList<String>();
5386 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5387 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5388 for (int j=0; j<linkedNotebooks.size(); j++) {
5389 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5390 LinkedNotebook t = linkedNotebooks.get(j);
5391 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5392 newLinked.add(t.getGuid());
5393 j=linkedNotebooks.size();
5398 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5404 //**********************************************************
5405 //**********************************************************
5406 //* XML Modifying methods
5407 //**********************************************************
5408 //**********************************************************
5409 // An error has happended fetching a resource. let the user know
5410 private void resourceErrorMessage() {
5414 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5415 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5416 "In a perfect world this wouldn't happen, but it has.\n" +
5417 "It is embarasing when a program like me, designed to save all your\n"+
5418 "precious data, has a problem finding data.\n\n" +
5419 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5420 "In the mean time, I'm not going to let you make changes to this note.\n" +
5421 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5422 "this note on the Evernote servers. Sorry."+
5423 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5425 browserWindow.setReadOnly(true);
5432 //**********************************************************
5433 //**********************************************************
5435 //**********************************************************
5436 //**********************************************************
5437 // We should now do a sync with Evernote
5438 private void syncTimer() {
5439 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5440 syncRunner.syncNeeded = true;
5441 syncRunner.disableUploads = Global.disableUploads;
5443 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5445 private void syncStart() {
5446 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5448 if (!syncRunning && Global.isConnected) {
5449 syncRunner.setConnected(true);
5450 syncRunner.setKeepRunning(Global.keepRunning);
5451 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5453 if (syncThreadsReady > 0) {
5454 thumbnailRunner.interrupt = true;
5455 saveNoteIndexWidth();
5456 saveNoteColumnPositions();
5457 if (syncRunner.addWork("SYNC")) {
5459 syncRunner.syncNeeded = true;
5464 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5466 @SuppressWarnings("unused")
5467 private void syncThreadComplete(Boolean refreshNeeded) {
5468 setMessage(tr("Finalizing Synchronization"));
5470 syncRunning = false;
5471 syncRunner.syncNeeded = false;
5472 synchronizeAnimationTimer.stop();
5473 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5475 if (currentNote == null) {
5476 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5478 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5479 noteIndexUpdated(false);
5480 noteTableView.selectionModel().blockSignals(true);
5481 scrollToGuid(currentNoteGuid);
5482 noteTableView.selectionModel().blockSignals(false);
5483 refreshEvernoteNote(false);
5484 scrollToGuid(currentNoteGuid);
5487 // Check to see if there were any shared notebook errors
5488 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5489 String guid = syncRunner.errorSharedNotebooks.get(0);
5490 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5491 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5492 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5494 if (syncDialog.okPressed()) {
5495 if (syncDialog.doNothing.isChecked()) {
5496 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5499 if (syncDialog.deleteNotebook.isChecked()) {
5500 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5501 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5502 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5503 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5506 /* if (syncDialog.convertToLocal.isChecked()) {
5507 conn.getNotebookTable().convertFromSharedNotebook(notebookGuid, true);
5508 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5511 if (syncDialog.convertToShared.isChecked()) {
5512 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5513 conn.getNotebookTable().convertFromSharedNotebook(notebookGuid, false);
5521 // Finalize the synchronization
5522 if (!syncRunner.error)
5523 setMessage(tr("Synchronization Complete"));
5525 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5526 logger.log(logger.MEDIUM, "Sync complete.");
5528 public void saveUploadAmount(long t) {
5529 Global.saveUploadAmount(t);
5531 public void saveUserInformation(User user) {
5532 Global.saveUserInformation(user);
5534 public void saveEvernoteUpdateCount(int i) {
5535 Global.saveEvernoteUpdateCount(i);
5537 public void refreshLists() {
5538 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5540 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5541 tagIndexUpdated(true);
5542 notebookIndexUpdated();
5543 savedSearchIndexUpdated();
5544 listManager.loadNotesIndex();
5546 noteTableView.selectionModel().blockSignals(true);
5547 noteIndexUpdated(true);
5548 noteTableView.selectionModel().blockSignals(false);
5549 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5553 @SuppressWarnings("unused")
5554 private void authTimer() {
5555 Calendar cal = Calendar.getInstance();
5557 // If we are not connected let's get out of here
5558 if (!Global.isConnected)
5561 // If this is the first time through, then we need to set this
5562 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5563 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5565 // long now = new Date().getTime();
5566 // if (now > Global.authRefreshTime && Global.isConnected) {
5567 syncRunner.authRefreshNeeded = true;
5571 @SuppressWarnings("unused")
5572 private void authRefreshComplete(boolean goodSync) {
5573 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5574 Global.isConnected = syncRunner.isConnected;
5576 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5577 authTimer.start(1000*60*15);
5578 logger.log(logger.LOW, "Authentication token has been renewed");
5579 // setMessage("Authentication token has been renewed.");
5581 authTimer.start(1000*60*5);
5582 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5583 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5585 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5589 @SuppressWarnings("unused")
5590 private synchronized void indexTimer() {
5591 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5594 if (!indexDisabled && indexRunner.idle) {
5595 thumbnailRunner.interrupt = true;
5596 indexRunner.addWork("SCAN");
5598 logger.log(logger.EXTREME, "Leaving NixNote index timer");
5601 @SuppressWarnings("unused")
5602 private void indexStarted() {
5603 setMessage(tr("Indexing notes"));
5605 @SuppressWarnings("unused")
5606 private void indexComplete() {
5607 setMessage(tr("Index complete"));
5609 @SuppressWarnings("unused")
5610 private synchronized void toggleNoteIndexing() {
5611 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5612 indexDisabled = !indexDisabled;
5614 setMessage(tr("Indexing is now enabled."));
5616 setMessage(tr("Indexing is now disabled."));
5617 menuBar.disableIndexing.setChecked(indexDisabled);
5618 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5621 @SuppressWarnings("unused")
5622 private void threadMonitorCheck() {
5627 alive = listManager.threadCheck(Global.tagCounterThreadId);
5630 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5631 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died. I recommend "+
5632 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5633 disableTagThreadCheck = true;
5638 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5640 notebookThreadDeadCount++;
5641 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5642 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died. I recommend "+
5643 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5644 disableNotebookThreadCheck=true;
5647 notebookThreadDeadCount=0;
5649 alive = listManager.threadCheck(Global.trashCounterThreadId);
5652 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5653 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died. I recommend "+
5654 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5655 disableTrashThreadCheck = true;
5660 alive = listManager.threadCheck(Global.saveThreadId);
5662 saveThreadDeadCount++;
5663 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5664 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died. I recommend "+
5665 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5666 disableSaveThreadCheck = true;
5669 saveThreadDeadCount=0;
5671 if (!syncThread.isAlive()) {
5672 syncThreadDeadCount++;
5673 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5674 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died. I recommend "+
5675 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5676 disableSyncThreadCheck = true;
5679 syncThreadDeadCount=0;
5681 if (!indexThread.isAlive()) {
5682 indexThreadDeadCount++;
5683 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5684 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died. I recommend "+
5685 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5686 disableIndexThreadCheck = true;
5689 indexThreadDeadCount=0;
5694 private void thumbnailTimer() {
5695 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5696 thumbnailRunner.addWork("SCAN");
5700 //**************************************************
5701 //* Backup & Restore
5702 //**************************************************
5703 @SuppressWarnings("unused")
5704 private void databaseBackup() {
5705 QFileDialog fd = new QFileDialog(this);
5706 fd.setFileMode(FileMode.AnyFile);
5707 fd.setConfirmOverwrite(true);
5708 fd.setWindowTitle(tr("Backup Database"));
5709 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5710 fd.setAcceptMode(AcceptMode.AcceptSave);
5711 if (saveLastPath == null || saveLastPath.equals(""))
5712 fd.setDirectory(System.getProperty("user.home"));
5714 fd.setDirectory(saveLastPath);
5715 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5721 saveLastPath = fd.selectedFiles().get(0);
5722 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5723 setMessage(tr("Backing up database"));
5725 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5727 ExportData noteWriter = new ExportData(conn, true);
5728 String fileName = fd.selectedFiles().get(0);
5730 if (!fileName.endsWith(".nnex"))
5731 fileName = fileName +".nnex";
5732 noteWriter.exportData(fileName);
5733 setMessage(tr("Database backup completed."));
5738 @SuppressWarnings("unused")
5739 private void databaseRestore() {
5740 if (QMessageBox.question(this, tr("Confirmation"),
5741 tr("This is used to restore a database from backups.\n" +
5742 "It is HIGHLY recommened that this only be used to populate\n" +
5743 "an empty database. Restoring into a database that\n already has data" +
5744 " can cause problems.\n\nAre you sure you want to continue?"),
5745 QMessageBox.StandardButton.Yes,
5746 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5751 QFileDialog fd = new QFileDialog(this);
5752 fd.setFileMode(FileMode.ExistingFile);
5753 fd.setConfirmOverwrite(true);
5754 fd.setWindowTitle(tr("Restore Database"));
5755 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5756 fd.setAcceptMode(AcceptMode.AcceptOpen);
5757 if (saveLastPath == null || saveLastPath.equals(""))
5758 fd.setDirectory(System.getProperty("user.home"));
5760 fd.setDirectory(saveLastPath);
5761 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5767 saveLastPath = fd.selectedFiles().get(0);
5768 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5770 setMessage(tr("Restoring database"));
5771 ImportData noteReader = new ImportData(conn, true);
5772 noteReader.importData(fd.selectedFiles().get(0));
5774 if (noteReader.lastError != 0) {
5775 setMessage(noteReader.getErrorMessage());
5776 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5781 listManager.loadNoteTitleColors();
5783 refreshEvernoteNote(true);
5784 setMessage(tr("Database has been restored."));
5787 @SuppressWarnings("unused")
5788 private void exportNotes() {
5789 QFileDialog fd = new QFileDialog(this);
5790 fd.setFileMode(FileMode.AnyFile);
5791 fd.setConfirmOverwrite(true);
5792 fd.setWindowTitle(tr("Backup Database"));
5793 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5794 fd.setAcceptMode(AcceptMode.AcceptSave);
5795 fd.setDirectory(System.getProperty("user.home"));
5796 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5802 setMessage(tr("Exporting Notes"));
5805 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5806 selectedNoteGUIDs.add(currentNoteGuid);
5808 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5809 String fileName = fd.selectedFiles().get(0);
5811 if (!fileName.endsWith(".nnex"))
5812 fileName = fileName +".nnex";
5813 noteWriter.exportData(fileName);
5814 setMessage(tr("Export completed."));
5820 @SuppressWarnings("unused")
5821 private void importNotes() {
5822 QFileDialog fd = new QFileDialog(this);
5823 fd.setFileMode(FileMode.ExistingFile);
5824 fd.setConfirmOverwrite(true);
5825 fd.setWindowTitle(tr("Import Notes"));
5826 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5827 fd.setAcceptMode(AcceptMode.AcceptOpen);
5828 if (saveLastPath == null || saveLastPath.equals(""))
5829 fd.setDirectory(System.getProperty("user.home"));
5831 fd.setDirectory(saveLastPath);
5832 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5838 setMessage(tr("Importing Notes"));
5841 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5842 selectedNoteGUIDs.add(currentNoteGuid);
5844 ImportData noteReader = new ImportData(conn, false);
5845 String fileName = fd.selectedFiles().get(0);
5846 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5848 if (!fileName.endsWith(".nnex"))
5849 fileName = fileName +".nnex";
5850 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5851 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5853 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5855 noteReader.importData(fileName);
5857 if (noteReader.lastError != 0) {
5858 setMessage(noteReader.getErrorMessage());
5859 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5864 listManager.loadNoteTitleColors();
5866 refreshEvernoteNote(false);
5867 setMessage(tr("Notes have been imported."));
5870 setMessage(tr("Import completed."));
5877 //**************************************************
5878 //* Duplicate a note
5879 //**************************************************
5880 @SuppressWarnings("unused")
5881 private void duplicateNote() {
5883 duplicateNote(currentNoteGuid);
5886 //**************************************************
5887 //* Action from when a user clicks Copy As URL
5888 //**************************************************
5889 @SuppressWarnings("unused")
5890 private void copyAsUrlClicked() {
5891 QClipboard clipboard = QApplication.clipboard();
5892 QMimeData mime = new QMimeData();
5894 mime.setText(currentNoteGuid);
5895 List<QUrl> urls = new ArrayList<QUrl>();
5897 // Start building the URL
5898 User user = Global.getUserInformation();
5900 // Check that we have everything we need
5901 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
5902 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
5904 if (!warning.neverSynchronize())
5907 Global.setBypassSynchronizationWarning(true);
5908 user.setShardId("s0");
5914 // Start building a list of URLs based upon the selected notes
5915 noteTableView.showColumn(Global.noteTableGuidPosition);
5917 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
5918 if (!Global.isColumnVisible("guid"))
5919 noteTableView.hideColumn(Global.noteTableGuidPosition);
5921 // Check that the note is either synchronized, or in a local notebook
5922 for (int i=0; i<selections.size(); i++) {
5924 int row = selections.get(i).row();
5925 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5926 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5927 String selectedGuid = (String)ix.values().toArray()[0];
5929 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5930 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
5931 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
5932 "new notes to a local notebook."));
5937 // Start building the URLs
5938 for (int i=0; i<selections.size(); i++) {
5940 int row = selections.get(i).row();
5941 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5942 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5943 String selectedGuid = (String)ix.values().toArray()[0];
5944 mime.setText(selectedGuid);
5948 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5949 if (selectedNote.getUpdateSequenceNum() > 0) {
5953 gid = "00000000-0000-0000-0000-000000000000";
5956 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
5958 urls.add(new QUrl(url));
5961 clipboard.setMimeData(mime);
5965 //**************************************************
5967 //**************************************************
5968 public void setupFolderImports() {
5969 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5971 if (importKeepWatcher == null)
5972 importKeepWatcher = new QFileSystemWatcher();
5973 if (importDeleteWatcher == null) {
5974 importDeleteWatcher = new QFileSystemWatcher();
5975 for (int i=0; i<records.size(); i++) {
5976 if (!records.get(i).keep)
5977 folderImportDelete(records.get(i).folder);
5983 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5984 for (int i=0; i<records.size(); i++) {
5985 if (records.get(i).keep)
5986 importKeepWatcher.addPath(records.get(i).folder);
5988 importDeleteWatcher.addPath(records.get(i).folder);
5991 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5992 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5994 // Look at the files already there so we don't import them again if a new file is created
5995 if (importedFiles == null) {
5996 importedFiles = new ArrayList<String>();
5997 for (int j=0; j<records.size(); j++) {
5998 QDir dir = new QDir(records.get(j).folder);
5999 List<QFileInfo> list = dir.entryInfoList();
6000 for (int k=0; k<list.size(); k++) {
6001 if (list.get(k).isFile())
6002 importedFiles.add(list.get(k).absoluteFilePath());
6007 public void folderImport() {
6008 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
6009 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
6011 if (!dialog.okClicked())
6014 // We have some sort of update.
6015 if (importKeepWatcher.directories().size() > 0)
6016 importKeepWatcher.removePaths(importKeepWatcher.directories());
6017 if (importDeleteWatcher.directories().size() > 0)
6018 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
6020 conn.getWatchFolderTable().expungeAll();
6021 // Start building from the table
6022 for (int i=0; i<dialog.table.rowCount(); i++) {
6023 QTableWidgetItem item = dialog.table.item(i, 0);
6024 String dir = item.text();
6025 item = dialog.table.item(i, 1);
6026 String notebook = item.text();
6027 item = dialog.table.item(i, 2);
6029 if (item.text().equalsIgnoreCase("Keep"))
6034 String guid = conn.getNotebookTable().findNotebookByName(notebook);
6035 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
6037 setupFolderImports();
6040 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
6042 String whichOS = System.getProperty("os.name");
6043 if (whichOS.contains("Windows"))
6044 dirName = dirName.replace('/','\\');
6046 FileImporter importer = new FileImporter(logger, conn);
6048 QDir dir = new QDir(dirName);
6049 List<QFileInfo> list = dir.entryInfoList();
6050 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6052 for (int i=0; i<list.size(); i++){
6054 boolean redundant = false;
6055 // Check if we've already imported this one or if it existed before
6056 for (int j=0; j<importedFiles.size(); j++) {
6057 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6062 importer.setFileInfo(list.get(i));
6063 importer.setFileName(list.get(i).absoluteFilePath());
6066 if (list.get(i).isFile() && importer.isValidType()) {
6068 if (!importer.importFile()) {
6069 // If we can't get to the file, it is probably locked. We'll try again later.
6070 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6071 importFilesKeep.add(list.get(i).absoluteFilePath());
6075 Note newNote = importer.getNote();
6076 newNote.setNotebookGuid(notebook);
6077 newNote.setTitle(dir.at(i));
6078 listManager.addNote(newNote);
6079 conn.getNoteTable().addNote(newNote, true);
6080 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
6081 noteTableView.insertRow(newNote, true, -1);
6082 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6083 listManager.countNotebookResults(listManager.getNoteIndex());
6084 importedFiles.add(list.get(i).absoluteFilePath());
6092 public void folderImportDelete(String dirName) {
6094 String whichOS = System.getProperty("os.name");
6095 if (whichOS.contains("Windows"))
6096 dirName = dirName.replace('/','\\');
6098 FileImporter importer = new FileImporter(logger, conn);
6099 QDir dir = new QDir(dirName);
6100 List<QFileInfo> list = dir.entryInfoList();
6101 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6103 for (int i=0; i<list.size(); i++){
6104 importer.setFileInfo(list.get(i));
6105 importer.setFileName(list.get(i).absoluteFilePath());
6107 if (list.get(i).isFile() && importer.isValidType()) {
6109 if (!importer.importFile()) {
6110 // If we can't get to the file, it is probably locked. We'll try again later.
6111 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6112 importFilesKeep.add(list.get(i).absoluteFilePath());
6116 Note newNote = importer.getNote();
6117 newNote.setNotebookGuid(notebook);
6118 newNote.setTitle(dir.at(i));
6119 listManager.addNote(newNote);
6120 conn.getNoteTable().addNote(newNote, true);
6121 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
6122 noteTableView.insertRow(newNote, true, -1);
6123 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6124 listManager.countNotebookResults(listManager.getNoteIndex());
6125 dir.remove(dir.at(i));
6131 //**************************************************
6133 //**************************************************
6134 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6135 logger.log(logger.HIGH, "Entering exernalFileEdited");
6137 // Strip URL prefix and base dir path
6138 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6139 String name = fileName.replace(dPath, "");
6140 int pos = name.lastIndexOf('.');
6143 guid = guid.substring(0,pos);
6145 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6147 guid = name.substring(0, pos);
6150 QFile file = new QFile(fileName);
6151 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6152 // If we can't get to the file, it is probably locked. We'll try again later.
6153 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6154 externalFiles.add(fileName);
6157 QByteArray binData = file.readAll();
6159 if (binData.size() == 0) {
6160 // If we can't get to the file, it is probably locked. We'll try again later.
6161 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6162 externalFiles.add(fileName);
6166 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6168 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6169 if (r == null || r.getData() == null || r.getData().getBody() == null)
6171 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6172 MessageDigest md = MessageDigest.getInstance("MD5");
6173 md.update(binData.toByteArray());
6174 byte[] hash = md.digest();
6175 String newHash = Global.byteArrayToHexString(hash);
6176 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6177 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6179 if (externalWindows.containsKey(r.getNoteGuid())) {
6180 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6181 r.getGuid(), oldHash, newHash);
6183 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6184 Data data = r.getData();
6185 data.setBody(binData.toByteArray());
6186 data.setBodyHash(hash);
6187 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6189 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6191 if (r.getNoteGuid().equals(currentNoteGuid)) {
6192 QWebSettings.setMaximumPagesInCache(0);
6193 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6194 refreshEvernoteNote(true);
6195 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6198 if (externalWindows.containsKey(r.getNoteGuid())) {
6199 QWebSettings.setMaximumPagesInCache(0);
6200 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6201 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6205 logger.log(logger.HIGH, "Exiting externalFielEdited");
6207 // This is a timer event that tries to save any external files that were edited. This
6208 // is only needed if we couldn't save a file earlier.
6209 public void externalFileEditedSaver() {
6210 for (int i=externalFiles.size()-1; i>=0; i--) {
6212 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6213 externalFileEdited(externalFiles.get(i));
6214 externalFiles.remove(i);
6215 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6217 for (int i=0; i<importFilesKeep.size(); i++) {
6219 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6220 folderImportKeep(importFilesKeep.get(i));
6221 importFilesKeep.remove(i);
6222 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6224 for (int i=0; i<importFilesDelete.size(); i++) {
6225 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6226 folderImportDelete(importFilesDelete.get(i));
6227 importFilesDelete.remove(i);
6234 // If an attachment on the current note was edited, we need to update the current notes's hash
6235 // Update a note content's hash. This happens if a resource is edited outside of NN
6236 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6237 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6239 for (;position>-1;) {
6240 endPos = browser.getContent().indexOf(">", position+1);
6241 String oldSegment = browser.getContent().substring(position,endPos);
6242 int hashPos = oldSegment.indexOf("hash=\"");
6243 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6244 String hash = oldSegment.substring(hashPos+6, hashEnd);
6245 if (hash.equalsIgnoreCase(oldHash)) {
6246 String newSegment = oldSegment.replace(oldHash, newHash);
6247 String content = browser.getContent().substring(0,position) +
6249 browser.getContent().substring(endPos);
6250 browser.setContent(new QByteArray(content));;
6253 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6258 //*************************************************
6259 //* Minimize to tray
6260 //*************************************************
6262 public void changeEvent(QEvent e) {
6263 if (e.type() == QEvent.Type.WindowStateChange) {
6264 if (isMinimized() && Global.showTrayIcon()) {
6266 QTimer.singleShot(10, this, "hide()");
6270 windowMaximized = true;
6272 windowMaximized = false;
6276 //*************************************************
6277 //* Check database userid & passwords
6278 //*************************************************
6279 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6280 Connection connection;
6283 Class.forName("org.h2.Driver");
6284 } catch (ClassNotFoundException e1) {
6285 e1.printStackTrace();
6290 String passwordString = null;
6291 if (cypherPassword==null || cypherPassword.trim().equals(""))
6292 passwordString = userPassword;
6294 passwordString = cypherPassword+" "+userPassword;
6295 connection = DriverManager.getConnection(url,userid,passwordString);
6296 } catch (SQLException e) {
6301 } catch (SQLException e) {
6302 e.printStackTrace();
6307 //*************************************************
6308 //* View / Hide source HTML for a note
6309 //*************************************************
6310 public void viewSource() {
6311 browserWindow.showSource(menuBar.viewSource.isChecked());
6313 //*************************************************
6314 // Block the program. This is used for things
6315 // like async web calls.
6316 //*************************************************
6317 @SuppressWarnings("unused")
6318 private void blockApplication(BrowserWindow b) {
6319 // Block all signals
6323 blockTimer = new QTimer();
6324 blockTimer.setSingleShot(true);
6325 blockTimer.setInterval(15000);
6326 blockTimer.timeout.connect(this, "unblockApplication()");
6331 @SuppressWarnings("unused")
6332 private void unblockApplication() {
6334 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6335 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6336 blockingWindow.unblockTime = -1;
6337 blockingWindow.awaitingHttpResponse = false;
6339 blockingWindow = null;
6340 blockSignals(false);