2 * This file is part of NeverNote
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.QModelIndex;
79 import com.trolltech.qt.core.QSize;
80 import com.trolltech.qt.core.QTemporaryFile;
81 import com.trolltech.qt.core.QTextCodec;
82 import com.trolltech.qt.core.QThreadPool;
83 import com.trolltech.qt.core.QTimer;
84 import com.trolltech.qt.core.QTranslator;
85 import com.trolltech.qt.core.QUrl;
86 import com.trolltech.qt.core.Qt;
87 import com.trolltech.qt.core.Qt.BGMode;
88 import com.trolltech.qt.core.Qt.ItemDataRole;
89 import com.trolltech.qt.core.Qt.SortOrder;
90 import com.trolltech.qt.core.Qt.WidgetAttribute;
91 import com.trolltech.qt.gui.QAbstractItemView;
92 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
93 import com.trolltech.qt.gui.QAction;
94 import com.trolltech.qt.gui.QApplication;
95 import com.trolltech.qt.gui.QCloseEvent;
96 import com.trolltech.qt.gui.QColor;
97 import com.trolltech.qt.gui.QComboBox;
98 import com.trolltech.qt.gui.QCursor;
99 import com.trolltech.qt.gui.QDesktopServices;
100 import com.trolltech.qt.gui.QDialog;
101 import com.trolltech.qt.gui.QFileDialog;
102 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
103 import com.trolltech.qt.gui.QFileDialog.FileMode;
104 import com.trolltech.qt.gui.QGridLayout;
105 import com.trolltech.qt.gui.QHBoxLayout;
106 import com.trolltech.qt.gui.QIcon;
107 import com.trolltech.qt.gui.QImage;
108 import com.trolltech.qt.gui.QKeySequence;
109 import com.trolltech.qt.gui.QLabel;
110 import com.trolltech.qt.gui.QMainWindow;
111 import com.trolltech.qt.gui.QMenu;
112 import com.trolltech.qt.gui.QMessageBox;
113 import com.trolltech.qt.gui.QMessageBox.StandardButton;
114 import com.trolltech.qt.gui.QPainter;
115 import com.trolltech.qt.gui.QPalette.ColorRole;
116 import com.trolltech.qt.gui.QPixmap;
117 import com.trolltech.qt.gui.QPrintDialog;
118 import com.trolltech.qt.gui.QPrinter;
119 import com.trolltech.qt.gui.QShortcut;
120 import com.trolltech.qt.gui.QSizePolicy;
121 import com.trolltech.qt.gui.QSizePolicy.Policy;
122 import com.trolltech.qt.gui.QSpinBox;
123 import com.trolltech.qt.gui.QSplashScreen;
124 import com.trolltech.qt.gui.QSplitter;
125 import com.trolltech.qt.gui.QStatusBar;
126 import com.trolltech.qt.gui.QSystemTrayIcon;
127 import com.trolltech.qt.gui.QTableWidgetItem;
128 import com.trolltech.qt.gui.QTextEdit;
129 import com.trolltech.qt.gui.QToolBar;
130 import com.trolltech.qt.gui.QTreeWidgetItem;
131 import com.trolltech.qt.network.QNetworkAccessManager;
132 import com.trolltech.qt.network.QNetworkReply;
133 import com.trolltech.qt.network.QNetworkRequest;
134 import com.trolltech.qt.webkit.QWebPage.WebAction;
135 import com.trolltech.qt.webkit.QWebSettings;
137 import cx.fbn.nevernote.config.InitializationException;
138 import cx.fbn.nevernote.config.StartupConfig;
139 import cx.fbn.nevernote.dialog.AccountDialog;
140 import cx.fbn.nevernote.dialog.ConfigDialog;
141 import cx.fbn.nevernote.dialog.DBEncryptDialog;
142 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
143 import cx.fbn.nevernote.dialog.DatabaseStatus;
144 import cx.fbn.nevernote.dialog.FindDialog;
145 import cx.fbn.nevernote.dialog.IgnoreSync;
146 import cx.fbn.nevernote.dialog.LogFileDialog;
147 import cx.fbn.nevernote.dialog.LoginDialog;
148 import cx.fbn.nevernote.dialog.NotebookArchive;
149 import cx.fbn.nevernote.dialog.NotebookEdit;
150 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
151 import cx.fbn.nevernote.dialog.PublishNotebook;
152 import cx.fbn.nevernote.dialog.SavedSearchEdit;
153 import cx.fbn.nevernote.dialog.SetIcon;
154 import cx.fbn.nevernote.dialog.ShareNotebook;
155 import cx.fbn.nevernote.dialog.StackNotebook;
156 import cx.fbn.nevernote.dialog.TagEdit;
157 import cx.fbn.nevernote.dialog.ThumbnailViewer;
158 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
159 import cx.fbn.nevernote.dialog.WatchFolder;
160 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
161 import cx.fbn.nevernote.filters.FilterEditorTags;
162 import cx.fbn.nevernote.gui.AttributeTreeWidget;
163 import cx.fbn.nevernote.gui.BrowserWindow;
164 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
165 import cx.fbn.nevernote.gui.ExternalBrowse;
166 import cx.fbn.nevernote.gui.MainMenuBar;
167 import cx.fbn.nevernote.gui.NotebookTreeWidget;
168 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
169 import cx.fbn.nevernote.gui.SearchPanel;
170 import cx.fbn.nevernote.gui.TableView;
171 import cx.fbn.nevernote.gui.TagTreeWidget;
172 import cx.fbn.nevernote.gui.Thumbnailer;
173 import cx.fbn.nevernote.gui.TrashTreeWidget;
174 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
175 import cx.fbn.nevernote.sql.DatabaseConnection;
176 import cx.fbn.nevernote.sql.WatchFolderRecord;
177 import cx.fbn.nevernote.threads.IndexRunner;
178 import cx.fbn.nevernote.threads.SyncRunner;
179 import cx.fbn.nevernote.threads.ThumbnailRunner;
180 import cx.fbn.nevernote.utilities.AESEncrypter;
181 import cx.fbn.nevernote.utilities.ApplicationLogger;
182 import cx.fbn.nevernote.utilities.FileImporter;
183 import cx.fbn.nevernote.utilities.FileUtils;
184 import cx.fbn.nevernote.utilities.ListManager;
185 import cx.fbn.nevernote.utilities.SyncTimes;
186 import cx.fbn.nevernote.xml.ExportData;
187 import cx.fbn.nevernote.xml.ImportData;
188 import cx.fbn.nevernote.xml.NoteFormatter;
191 public class NeverNote extends QMainWindow{
193 QStatusBar statusBar; // Application status bar
195 DatabaseConnection conn;
197 MainMenuBar menuBar; // Main menu bar
198 FindDialog find; // Text search in note dialog
199 List<String> emitLog; // Messages displayed in the status bar;
200 QSystemTrayIcon trayIcon; // little tray icon
201 QMenu trayMenu; // System tray menu
202 QAction trayExitAction; // Exit the application
203 QAction trayShowAction; // toggle the show/hide action
204 QAction trayAddNoteAction; // Add a note from the system tray
205 QNetworkAccessManager versionChecker; // Used when checking for new versions
207 NotebookTreeWidget notebookTree; // List of notebooks
208 AttributeTreeWidget attributeTree; // List of note attributes
209 TagTreeWidget tagTree; // list of user created tags
210 SavedSearchTreeWidget savedSearchTree; // list of saved searches
211 TrashTreeWidget trashTree; // Trashcan
212 TableView noteTableView; // List of notes (the widget).
214 public BrowserWindow browserWindow; // Window containing browser & labels
215 public QToolBar toolBar; // The tool bar under the menu
216 QComboBox searchField; // search filter bar on the toolbar;
217 QShortcut searchShortcut; // Shortcut to search bar
218 boolean searchPerformed = false; // Search was done?
219 QuotaProgressBar quotaBar; // The current quota usage
221 ApplicationLogger logger;
222 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
223 List<String> selectedTagGUIDs; // List of selected tag GUIDs
224 List<String> selectedNoteGUIDs; // List of selected notes
225 String selectedSavedSearchGUID; // Currently selected saved searches
226 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
228 NoteFilter filter; // Note filter
229 String currentNoteGuid; // GUID of the current note
230 Note currentNote; // The currently viewed note
231 boolean noteDirty; // Has the note been changed?
232 boolean inkNote; // if this is an ink note, it is read only
233 boolean readOnly; // Is this note read-only?
236 ListManager listManager; // DB runnable task
238 List<QTemporaryFile> tempFiles; // Array of temporary files;
240 QTimer indexTimer; // timer to start the index thread
241 IndexRunner indexRunner; // thread to index notes
244 QTimer syncTimer; // Sync on an interval
245 QTimer syncDelayTimer; // Sync delay to free up database
246 SyncRunner syncRunner; // thread to do a sync.
247 QThread syncThread; // Thread which talks to evernote
248 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
249 QThread thumbnailThread; // Thread that generates pretty pictures
250 QTimer saveTimer; // Timer to save note contents
252 QTimer authTimer; // Refresh authentication
253 QTimer externalFileSaveTimer; // Save files altered externally
254 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
255 List<String> externalFiles; // External files to save later
256 List<String> importFilesKeep; // Auto-import files to save later
257 List<String> importFilesDelete; // Auto-import files to save later
259 int indexTime; // how often to try and index
260 boolean indexRunning; // Is indexing running?
261 boolean indexDisabled; // Is indexing disabled?
263 int syncThreadsReady; // number of sync threads that are free
264 int syncTime; // Sync interval
265 boolean syncRunning; // Is sync running?
266 boolean automaticSync; // do sync automatically?
267 QTreeWidgetItem attributeTreeSelected;
269 QAction prevButton; // Go to the previous item viewed
270 QAction nextButton; // Go to the next item in the history
271 QAction downButton; // Go to the next item in the list
272 QAction upButton; // Go to the prev. item in the list;
273 QAction synchronizeButton; // Synchronize with Evernote
274 QAction allNotesButton; // Reset & view all notes
275 QTimer synchronizeAnimationTimer; // Timer to change animation button
276 int synchronizeIconAngle; // Used to rotate sync icon
277 QAction printButton; // Print Button
278 QAction tagButton; // Tag edit button
279 QAction attributeButton; // Attribute information button
280 QAction emailButton; // Email button
281 QAction deleteButton; // Delete button
282 QAction newButton; // new Note Button;
283 QSpinBox zoomSpinner; // Zoom zoom
284 QAction searchClearButton; // Clear the search field
286 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
288 QSplitter mainLeftRightSplitter; // main splitter for left/right side
289 QSplitter leftSplitter1; // first left hand splitter
290 QSplitter browserIndexSplitter; // splitter between note index & note text
292 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
293 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
294 List<String> importedFiles; // History of imported files (so we don't import twice)
296 OnlineNoteHistory historyWindow; // online history window
297 List<NoteVersionId> versions; // history versions
299 QTimer threadMonitorTimer; // Timer to watch threads.
300 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
301 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
302 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
303 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
304 int tagDeadCount=0; // number of consecutive dead times for the tag thread
305 int trashDeadCount=0; // number of consecutive dead times for the trash thread
306 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
307 boolean disableTagThreadCheck=false;
308 boolean disableNotebookThreadCheck=false;
309 boolean disableTrashThreadCheck=false;
310 boolean disableSaveThreadCheck=false;
311 boolean disableSyncThreadCheck=false;
312 boolean disableIndexThreadCheck=false;
314 HashMap<String, String> noteCache; // Cash of note content
315 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
316 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
317 List<String> historyGuids; // GUIDs of previously viewed items
318 int historyPosition; // Position within the viewed items
319 boolean fromHistory; // Is this from the history queue?
320 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
321 List<Thumbnailer> thumbGenerators; // generate preview image
322 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
323 boolean encryptOnShutdown; // should I encrypt when I close?
324 boolean decryptOnShutdown; // should I decrypt on shutdown;
325 String encryptCipher; // What cipher should I use?
326 Signal0 minimizeToTray;
327 boolean windowMaximized = false; // Keep track of the window state for restores
328 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
329 List<QPixmap> syncIcons; // Array of icons used in sync animation
330 private boolean closeAction = false; // Used to say when to close or when to minimize
331 private static Logger log = Logger.getLogger(NeverNote.class);
332 private String saveLastPath; // last path we used
333 private final QTimer messageTimer; // Timer to clear the status message.
336 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
339 //***************************************************************
340 //***************************************************************
341 //** Constructor & main entry point
342 //***************************************************************
343 //***************************************************************
344 // Application Constructor
345 @SuppressWarnings("static-access")
346 public NeverNote(DatabaseConnection dbConn) {
348 if (conn.getConnection() == null) {
349 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
350 "is accessing the database or NeverNote is already running.\n\n" +
351 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
353 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
357 // thread().setPriority(Thread.MAX_PRIORITY);
359 logger = new ApplicationLogger("nevernote.log");
360 logger.log(logger.HIGH, "Starting Application");
362 decryptOnShutdown = false;
363 encryptOnShutdown = false;
364 conn.checkDatabaseVersion();
368 // Start building the invalid XML tables
369 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
370 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
372 for (int i=0; i<elements.size(); i++) {
373 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
376 logger.log(logger.EXTREME, "Starting GUI build");
378 QTranslator nevernoteTranslator = new QTranslator();
379 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
380 QApplication.instance().installTranslator(nevernoteTranslator);
382 Global.originalPalette = QApplication.palette();
383 QApplication.setStyle(Global.getStyle());
384 if (Global.useStandardPalette())
385 QApplication.setPalette(QApplication.style().standardPalette());
386 setWindowTitle("NeverNote");
388 mainLeftRightSplitter = new QSplitter();
389 setCentralWidget(mainLeftRightSplitter);
390 leftSplitter1 = new QSplitter();
391 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
393 browserIndexSplitter = new QSplitter();
394 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
396 //* Setup threads & thread timers
397 int indexRunnerCount = Global.getIndexThreads();
398 indexRunnerCount = 1;
399 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
401 logger.log(logger.EXTREME, "Building list manager");
402 listManager = new ListManager(conn, logger);
404 logger.log(logger.EXTREME, "Building index runners & timers");
405 indexRunner = new IndexRunner("indexRunner.log",
406 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
407 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
408 indexThread = new QThread(indexRunner, "Index Thread");
409 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
412 synchronizeAnimationTimer = new QTimer();
413 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
415 indexTimer = new QTimer();
416 indexTime = 1000*Global.getIndexThreadSleepInterval();
417 indexTimer.start(indexTime); // Start indexing timer
418 indexTimer.timeout.connect(this, "indexTimer()");
419 indexDisabled = false;
420 indexRunning = false;
422 logger.log(logger.EXTREME, "Setting sync thread & timers");
424 syncRunner = new SyncRunner("syncRunner.log",
425 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
426 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
427 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
428 syncTimer = new QTimer();
429 syncTimer.timeout.connect(this, "syncTimer()");
430 syncRunner.status.message.connect(this, "setMessage(String)");
431 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
432 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
435 automaticSync = true;
436 syncTimer.start(syncTime*60*1000);
438 automaticSync = false;
441 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
442 syncThread = new QThread(syncRunner, "Synchronization Thread");
446 logger.log(logger.EXTREME, "Starting thumnail thread");
447 pdfReadyQueue = new ArrayList<String>();
448 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
449 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
450 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
451 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
452 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
453 thumbnailThread.start();
454 thumbGenerators = new ArrayList<Thumbnailer>();
455 thumbnailTimer = new QTimer();
456 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
458 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
459 thumbnailTimer.start();
461 logger.log(logger.EXTREME, "Starting authentication timer");
462 authTimer = new QTimer();
463 authTimer.timeout.connect(this, "authTimer()");
464 authTimer.start(1000*60*15);
465 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
467 logger.log(logger.EXTREME, "Setting save note timer");
468 saveTimer = new QTimer();
469 saveTimer.timeout.connect(this, "saveNote()");
470 if (Global.getAutoSaveInterval() > 0) {
471 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
474 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
476 logger.log(logger.EXTREME, "Starting external file monitor timer");
477 externalFileSaveTimer = new QTimer();
478 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
479 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
480 externalFiles = new ArrayList<String>();
481 importFilesDelete = new ArrayList<String>();
482 importFilesKeep = new ArrayList<String>();
483 externalFileSaveTimer.start();
485 notebookTree = new NotebookTreeWidget(conn);
486 attributeTree = new AttributeTreeWidget();
487 tagTree = new TagTreeWidget(conn);
488 savedSearchTree = new SavedSearchTreeWidget();
489 trashTree = new TrashTreeWidget();
490 noteTableView = new TableView(logger, listManager);
493 searchField = new QComboBox();
494 searchField.setObjectName("searchField");
495 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
496 searchField.setEditable(true);
497 searchField.activatedIndex.connect(this, "searchFieldChanged()");
498 searchField.setDuplicatesEnabled(false);
499 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
500 searchShortcut = new QShortcut(this);
501 setupShortcut(searchShortcut, "Focus_Search");
502 searchShortcut.activated.connect(this, "focusSearch()");
504 quotaBar = new QuotaProgressBar();
506 zoomSpinner = new QSpinBox();
507 zoomSpinner.setMinimum(10);
508 zoomSpinner.setMaximum(1000);
509 zoomSpinner.setAccelerated(true);
510 zoomSpinner.setSingleStep(10);
511 zoomSpinner.setValue(100);
512 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
514 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
517 QGridLayout leftGrid = new QGridLayout();
518 leftSplitter1.setContentsMargins(5, 0, 0, 7);
519 leftSplitter1.setLayout(leftGrid);
520 leftGrid.addWidget(searchLayout,1,1);
521 leftGrid.addWidget(tagTree,2,1);
522 leftGrid.addWidget(attributeTree,3,1);
523 leftGrid.addWidget(savedSearchTree,4,1);
524 leftGrid.addWidget(trashTree,5, 1);
526 // Setup the browser window
527 noteCache = new HashMap<String,String>();
528 readOnlyCache = new HashMap<String, Boolean>();
529 inkNoteCache = new HashMap<String, Boolean>();
530 browserWindow = new BrowserWindow(conn);
532 mainLeftRightSplitter.addWidget(leftSplitter1);
533 mainLeftRightSplitter.addWidget(browserIndexSplitter);
535 if (Global.getListView() == Global.View_List_Wide) {
536 browserIndexSplitter.addWidget(noteTableView);
537 browserIndexSplitter.addWidget(browserWindow);
539 mainLeftRightSplitter.addWidget(noteTableView);
540 mainLeftRightSplitter.addWidget(browserWindow);
543 // Setup the thumbnail viewer
544 thumbnailViewer = new ThumbnailViewer();
545 thumbnailViewer.upArrow.connect(this, "upAction()");
546 thumbnailViewer.downArrow.connect(this, "downAction()");
547 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
548 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
550 //Setup external browser manager
551 externalWindows = new HashMap<String, ExternalBrowse>();
553 listManager.loadNotesIndex();
554 initializeNotebookTree();
556 initializeSavedSearchTree();
557 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
558 attributeTreeSelected = null;
559 initializeNoteTable();
561 selectedNoteGUIDs = new ArrayList<String>();
562 statusBar = new QStatusBar();
563 setStatusBar(statusBar);
564 menuBar = new MainMenuBar(this);
565 emitLog = new ArrayList<String>();
567 tagTree.setDeleteAction(menuBar.tagDeleteAction);
568 tagTree.setEditAction(menuBar.tagEditAction);
569 tagTree.setAddAction(menuBar.tagAddAction);
570 tagTree.setIconAction(menuBar.tagIconAction);
571 tagTree.setVisible(Global.isWindowVisible("tagTree"));
572 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
573 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
574 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
575 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
577 if (!Global.isWindowVisible("zoom")) {
578 searchLayout.hideZoom();
579 menuBar.hideZoom.setChecked(false);
582 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
583 notebookTree.setEditAction(menuBar.notebookEditAction);
584 notebookTree.setAddAction(menuBar.notebookAddAction);
585 notebookTree.setIconAction(menuBar.notebookIconAction);
586 notebookTree.setStackAction(menuBar.notebookStackAction);
587 notebookTree.setPublishAction(menuBar.notebookPublishAction);
588 notebookTree.setShareAction(menuBar.notebookShareAction);
589 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
590 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
591 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
592 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
593 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
595 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
596 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
597 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
598 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
599 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
600 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
601 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
603 noteTableView.setAddAction(menuBar.noteAdd);
604 noteTableView.setDeleteAction(menuBar.noteDelete);
605 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
606 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
607 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
608 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
609 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
610 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
611 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
613 quotaBar.setMouseClickAction(menuBar.accountAction);
616 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
617 trashTree.setEmptyAction(menuBar.emptyTrashAction);
618 trashTree.setVisible(Global.isWindowVisible("trashTree"));
619 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
620 trashTree.updateCounts(listManager.getTrashCount());
621 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
622 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
624 noteTableView.setVisible(Global.isWindowVisible("noteList"));
625 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
627 if (!Global.isWindowVisible("editorButtonBar"))
628 toggleEditorButtonBar();
629 if (!Global.isWindowVisible("leftPanel"))
630 menuBar.hideLeftSide.setChecked(true);
631 if (Global.isWindowVisible("noteInformation"))
632 toggleNoteInformation();
633 quotaBar.setVisible(Global.isWindowVisible("quota"));
634 if (!quotaBar.isVisible())
635 menuBar.hideQuota.setChecked(false);
636 searchField.setVisible(Global.isWindowVisible("searchField"));
637 if (!searchField.isVisible())
638 menuBar.hideSearch.setChecked(false);
640 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
645 find = new FindDialog();
646 find.getOkButton().clicked.connect(this, "doFindText()");
648 // Setup the tray icon menu bar
649 trayShowAction = new QAction("Show/Hide", this);
650 trayExitAction = new QAction("Exit", this);
651 trayAddNoteAction = new QAction("Add Note", this);
653 trayExitAction.triggered.connect(this, "closeNeverNote()");
654 trayAddNoteAction.triggered.connect(this, "addNote()");
655 trayShowAction.triggered.connect(this, "trayToggleVisible()");
657 trayMenu = new QMenu(this);
658 trayMenu.addAction(trayAddNoteAction);
659 trayMenu.addAction(trayShowAction);
660 trayMenu.addAction(trayExitAction);
663 trayIcon = new QSystemTrayIcon(this);
664 trayIcon.setToolTip("NeverNote");
665 trayIcon.setContextMenu(trayMenu);
666 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
669 currentNoteGuid = Global.getLastViewedNoteGuid();
670 historyGuids = new ArrayList<String>();
674 if (!currentNoteGuid.trim().equals("")) {
675 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
678 noteIndexUpdated(true);
680 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
681 if (menuBar.showEditorBar.isChecked())
682 showEditorButtons(browserWindow);
683 tagIndexUpdated(true);
684 savedSearchIndexUpdated();
685 notebookIndexUpdated();
687 setupSyncSignalListeners();
688 setupBrowserSignalListeners();
689 setupIndexListeners();
692 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
693 tagTree.showAllTags(true);
695 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
696 setWindowIcon(appIcon);
697 trayIcon.setIcon(appIcon);
698 if (Global.showTrayIcon())
703 scrollToGuid(currentNoteGuid);
704 if (Global.automaticLogin()) {
706 if (Global.isConnected)
709 setupFolderImports();
712 restoreWindowState(true);
714 if (Global.mimicEvernoteInterface) {
715 notebookTree.selectGuid("");
718 threadMonitorTimer = new QTimer();
719 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
720 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
722 historyGuids.add(currentNoteGuid);
725 menuBar.blockSignals(true);
726 menuBar.narrowListView.blockSignals(true);
727 menuBar.wideListView.blockSignals(true);
728 if (Global.getListView() == Global.View_List_Narrow) {
729 menuBar.narrowListView.setChecked(true);
732 menuBar.wideListView.setChecked(true);
734 menuBar.blockSignals(false);
735 menuBar.narrowListView.blockSignals(false);
736 menuBar.wideListView.blockSignals(false);
738 if (Global.getListView() == Global.View_List_Wide) {
739 browserIndexSplitter.addWidget(noteTableView);
740 browserIndexSplitter.addWidget(browserWindow);
742 mainLeftRightSplitter.addWidget(noteTableView);
743 mainLeftRightSplitter.addWidget(browserWindow);
746 messageTimer = new QTimer();
747 messageTimer.timeout.connect(this, "clearMessage()");
748 messageTimer.setInterval(1000*15);
751 int sortCol = Global.getSortColumn();
752 int sortOrder = Global.getSortOrder();
753 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
754 if (Global.checkVersionUpgrade())
759 public static void main(String[] args) {
760 log.setLevel(Level.FATAL);
761 QApplication.initialize(args);
762 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
763 QSplashScreen splash = new QSplashScreen(pixmap);
766 DatabaseConnection dbConn;
769 initializeGlobalSettings(args);
771 showSplash = Global.isWindowVisible("SplashScreen");
775 dbConn = setupDatabaseConnection();
777 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
778 Global.getFileManager().purgeResDirectory(true);
780 } catch (InitializationException e) {
783 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
787 NeverNote application = new NeverNote(dbConn);
789 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
790 if (Global.startMinimized())
791 application.showMinimized();
793 if (Global.wasWindowMaximized())
794 application.showMaximized();
800 splash.finish(application);
802 System.out.println("Goodbye.");
807 * Open the internal database, or create if not present
809 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
811 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
812 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
814 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
815 boolean dbExists = f.exists();
817 Global.setDatabaseUrl("");
819 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
820 boolean goodCheck = false;
822 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
824 if (!dialog.okPressed())
826 Global.cipherPassword = dialog.getPassword();
827 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
828 Global.getDatabaseUserPassword(), Global.cipherPassword);
831 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
832 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
833 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
837 // Encrypt the database upon shutdown
838 private void encryptOnShutdown() {
839 String dbPath= Global.getFileManager().getDbDirPath("");
840 String dbName = "NeverNote";
842 Statement st = conn.getConnection().createStatement();
843 st.execute("shutdown");
844 if (QMessageBox.question(this, tr("Are you sure"),
845 tr("Are you sure you wish to encrypt the database?"),
846 QMessageBox.StandardButton.Yes,
847 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
848 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
849 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
850 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
852 } catch (SQLException e) {
857 // Decrypt the database upon shutdown
858 private void decryptOnShutdown() {
859 String dbPath= Global.getFileManager().getDbDirPath("");
860 String dbName = "NeverNote";
862 Statement st = conn.getConnection().createStatement();
863 st.execute("shutdown");
864 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
865 encryptCipher = "AES";
867 encryptCipher = "XTEA";
868 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
869 "Are you sure you wish to decrypt the database?"),
870 QMessageBox.StandardButton.Yes,
871 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
873 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
874 Global.setDatabaseUrl("");
875 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
877 } catch (SQLException e) {
882 * Encrypt/Decrypt the local database
884 public void doDatabaseEncrypt() {
885 // The database is not currently encrypted
886 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
887 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
888 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
889 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
890 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
891 "Do you wish to proceed?"),
892 QMessageBox.StandardButton.Yes,
893 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
896 DBEncryptDialog dialog = new DBEncryptDialog();
898 if (dialog.okPressed()) {
899 Global.cipherPassword = dialog.getPassword();
900 encryptOnShutdown = true;
901 encryptCipher = dialog.getEncryptionMethod();
904 DBEncryptDialog dialog = new DBEncryptDialog();
905 dialog.setWindowTitle("Database Decryption");
906 dialog.hideEncryption();
908 if (dialog.okPressed()) {
909 if (!dialog.getPassword().equals(Global.cipherPassword)) {
910 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
913 decryptOnShutdown = true;
920 private static void initializeGlobalSettings(String[] args) throws InitializationException {
921 StartupConfig startupConfig = new StartupConfig();
923 for (String arg : args) {
924 String lower = arg.toLowerCase();
925 if (lower.startsWith("--name="))
926 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
927 if (lower.startsWith("--home="))
928 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
929 if (lower.startsWith("--disable-viewing"))
930 startupConfig.setDisableViewing(true);
932 Global.setup(startupConfig);
937 public void closeEvent(QCloseEvent event) {
938 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
943 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
946 if (currentNote!= null & browserWindow!=null) {
947 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
948 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
951 setMessage(tr("Beginning shutdown."));
953 // Close down external windows
954 Collection<ExternalBrowse> windows = externalWindows.values();
955 Iterator<ExternalBrowse> iterator = windows.iterator();
956 while (iterator.hasNext()) {
957 ExternalBrowse browser = iterator.next();
958 browser.windowClosing.disconnect();
963 externalFileEditedSaver();
964 if (Global.isConnected && Global.synchronizeOnClose()) {
965 setMessage(tr("Performing synchronization before closing."));
966 syncRunner.syncNeeded = true;
967 syncRunner.addWork("SYNC");
969 syncRunner.keepRunning = false;
971 syncRunner.addWork("STOP");
972 setMessage("Closing Program.");
973 threadMonitorTimer.stop();
975 thumbnailRunner.addWork("STOP");
976 indexRunner.addWork("STOP");
981 if (tempFiles != null)
984 browserWindow.noteSignal.tagsChanged.disconnect();
985 browserWindow.noteSignal.titleChanged.disconnect();
986 browserWindow.noteSignal.noteChanged.disconnect();
987 browserWindow.noteSignal.notebookChanged.disconnect();
988 browserWindow.noteSignal.createdDateChanged.disconnect();
989 browserWindow.noteSignal.alteredDateChanged.disconnect();
990 syncRunner.searchSignal.listChanged.disconnect();
991 syncRunner.tagSignal.listChanged.disconnect();
992 syncRunner.notebookSignal.listChanged.disconnect();
993 syncRunner.noteIndexSignal.listChanged.disconnect();
996 Global.saveWindowVisible("toolBar", toolBar.isVisible());
997 saveNoteColumnPositions();
998 saveNoteIndexWidth();
1000 int width = notebookTree.columnWidth(0);
1001 Global.setColumnWidth("notebookTreeName", width);
1002 width = tagTree.columnWidth(0);
1003 Global.setColumnWidth("tagTreeName", width);
1005 Global.saveWindowMaximized(isMaximized());
1006 Global.saveCurrentNoteGuid(currentNoteGuid);
1008 int sortCol = noteTableView.proxyModel.sortColumn();
1009 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1010 Global.setSortColumn(sortCol);
1011 Global.setSortOrder(sortOrder);
1015 Global.keepRunning = false;
1017 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1018 if (indexRunner.thread().isAlive())
1019 indexRunner.thread().join(50);
1020 if (!indexRunner.thread().isAlive())
1021 logger.log(logger.MEDIUM, "Index thread has stopped");
1023 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1024 indexRunner.thread().interrupt();
1026 } catch (InterruptedException e1) {
1027 e1.printStackTrace();
1030 if (!syncRunner.thread().isAlive()) {
1031 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1032 if (syncRunner.thread().isAlive()) {
1033 System.out.println(tr("Synchronizing. Please be patient."));
1034 for(;syncRunner.thread().isAlive();) {
1037 } catch (InterruptedException e) {
1038 e.printStackTrace();
1042 logger.log(logger.MEDIUM, "Sync thread has stopped");
1045 if (encryptOnShutdown) {
1046 encryptOnShutdown();
1048 if (decryptOnShutdown) {
1049 decryptOnShutdown();
1052 Global.getFileManager().purgeResDirectory(false);
1053 } catch (InitializationException e) {
1054 System.out.println(tr("Empty res directory purge failed"));
1055 e.printStackTrace();
1057 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1060 @SuppressWarnings("unused")
1061 private void closeNeverNote() {
1065 public void setMessage(String s) {
1066 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1069 logger.log(logger.HIGH, "Message: " +s);
1070 statusBar.showMessage(s);
1074 messageTimer.stop();
1075 messageTimer.setSingleShot(true);
1076 messageTimer.start();
1079 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1082 private void clearMessage() {
1083 statusBar.clearMessage();
1087 private void waitCursor(boolean wait) {
1089 if (QApplication.overrideCursor() == null)
1090 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1093 while (QApplication.overrideCursor() != null)
1094 QApplication.restoreOverrideCursor();
1096 listManager.refreshCounters();
1099 private void setupIndexListeners() {
1100 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1101 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1102 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1103 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1105 private void setupSyncSignalListeners() {
1106 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1107 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1108 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1109 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1110 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1112 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1113 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1114 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1116 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1117 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1118 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1119 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1120 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1122 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1125 private void setupBrowserSignalListeners() {
1126 setupBrowserWindowListeners(browserWindow, true);
1129 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1130 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1131 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1132 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1133 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1134 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1135 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1136 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1137 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1138 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1139 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1140 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1141 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1142 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1143 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1144 if (master) browser.focusLost.connect(this, "saveNote()");
1145 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1148 //**************************************************
1150 //**************************************************
1151 private void setupShortcut(QShortcut action, String text) {
1152 if (!Global.shortcutKeys.containsAction(text))
1154 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1157 //***************************************************************
1158 //***************************************************************
1159 //* Settings and look & feel
1160 //***************************************************************
1161 //***************************************************************
1162 @SuppressWarnings("unused")
1163 private void settings() {
1164 logger.log(logger.HIGH, "Entering NeverNote.settings");
1165 saveNoteColumnPositions();
1166 saveNoteIndexWidth();
1168 ConfigDialog settings = new ConfigDialog(this);
1169 String dateFormat = Global.getDateFormat();
1170 String timeFormat = Global.getTimeFormat();
1172 indexTime = 1000*Global.getIndexThreadSleepInterval();
1173 indexTimer.start(indexTime); // reset indexing timer
1176 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1177 if (Global.showTrayIcon())
1182 if (menuBar.showEditorBar.isChecked())
1183 showEditorButtons(browserWindow);
1185 // Reset the save timer
1186 if (Global.getAutoSaveInterval() > 0)
1187 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1191 // This is a hack to force a reload of the index in case the date or time changed.
1192 // if (!dateFormat.equals(Global.getDateFormat()) ||
1193 // !timeFormat.equals(Global.getTimeFormat())) {
1195 readOnlyCache.clear();
1196 inkNoteCache.clear();
1197 noteIndexUpdated(true);
1200 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1202 // Restore things to the way they were
1203 private void restoreWindowState(boolean mainWindow) {
1204 // We need to name things or this doesn't work.
1205 setObjectName("NeverNote");
1206 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1207 browserIndexSplitter.setObjectName("browserIndexSplitter");
1208 leftSplitter1.setObjectName("leftSplitter1");
1210 // Restore the actual positions.
1212 restoreGeometry(Global.restoreGeometry(objectName()));
1213 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1214 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1215 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1218 // Save window positions for the next start
1219 private void saveWindowState() {
1220 Global.saveGeometry(objectName(), saveGeometry());
1221 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1222 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1223 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1225 // Load the style sheet
1226 private void loadStyleSheet() {
1227 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1228 fileName = Global.getFileManager().getQssDirPath("default.qss");
1229 QFile file = new QFile(fileName);
1231 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1232 if (!file.exists()) {
1233 fileName = Global.getFileManager().getQssDirPath("default.qss");
1234 file = new QFile(fileName);
1236 file.open(OpenModeFlag.ReadOnly);
1237 String styleSheet = file.readAll().toString();
1239 setStyleSheet(styleSheet);
1241 // Save column positions for the next time
1242 private void saveNoteColumnPositions() {
1243 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1244 Global.setColumnPosition("noteTableCreationPosition", position);
1245 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1246 Global.setColumnPosition("noteTableTagPosition", position);
1247 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1248 Global.setColumnPosition("noteTableNotebookPosition", position);
1249 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1250 Global.setColumnPosition("noteTableChangedPosition", position);
1251 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1252 Global.setColumnPosition("noteTableAuthorPosition", position);
1253 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1254 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1255 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1256 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1257 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1258 Global.setColumnPosition("noteTableTitlePosition", position);
1259 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1260 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1261 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1262 Global.setColumnPosition("noteTableGuidPosition", position);
1263 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1264 Global.setColumnPosition("noteTableThumbnailPosition", position);
1267 // Save column widths for the next time
1268 private void saveNoteIndexWidth() {
1270 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1271 Global.setColumnWidth("noteTableCreationPosition", width);
1272 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1273 Global.setColumnWidth("noteTableChangedPosition", width);
1274 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1275 Global.setColumnWidth("noteTableGuidPosition", width);
1276 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1277 Global.setColumnWidth("noteTableNotebookPosition", width);
1278 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1279 Global.setColumnWidth("noteTableTagPosition", width);
1280 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1281 Global.setColumnWidth("noteTableTitlePosition", width);
1282 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1283 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1284 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1285 Global.setColumnWidth("noteTableAuthorPosition", width);
1286 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1287 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1288 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1289 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1290 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1291 Global.setColumnWidth("noteTableThumbnailPosition", width);
1292 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1293 Global.setColumnWidth("noteTableGuidPosition", width);
1296 private void toggleSearchWindow() {
1297 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1298 searchLayout.toggleSearchField();
1299 menuBar.hideSearch.setChecked(searchField.isVisible());
1300 Global.saveWindowVisible("searchField", searchField.isVisible());
1301 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1303 private void toggleQuotaWindow() {
1304 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1305 searchLayout.toggleQuotaBar();
1306 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1307 Global.saveWindowVisible("quota", quotaBar.isVisible());
1308 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1310 private void toggleZoomWindow() {
1311 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1312 searchLayout.toggleZoom();
1313 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1314 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1315 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1320 //***************************************************************
1321 //***************************************************************
1322 //** These functions deal with Notebook menu items
1323 //***************************************************************
1324 //***************************************************************
1325 // Setup the tree containing the user's notebooks.
1326 private void initializeNotebookTree() {
1327 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1328 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1329 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1330 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1331 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1333 // Listener when a notebook is selected
1334 private void notebookTreeSelection() {
1335 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1338 clearAttributeFilter();
1339 clearSavedSearchFilter();
1340 if (Global.mimicEvernoteInterface) {
1342 searchField.clear();
1344 menuBar.noteRestoreAction.setVisible(false);
1345 menuBar.notebookEditAction.setEnabled(true);
1346 menuBar.notebookDeleteAction.setEnabled(true);
1347 menuBar.notebookPublishAction.setEnabled(true);
1348 menuBar.notebookShareAction.setEnabled(true);
1349 menuBar.notebookIconAction.setEnabled(true);
1350 menuBar.notebookStackAction.setEnabled(true);
1351 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1352 selectedNotebookGUIDs.clear();
1354 String stackName = "";
1355 if (selections.size() > 0) {
1356 guid = (selections.get(0).text(2));
1357 stackName = selections.get(0).text(0);
1359 if (!Global.mimicEvernoteInterface) {
1360 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1361 if (selections.size()==0) {
1362 selectedNotebookGUIDs.clear();
1363 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1364 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1366 menuBar.notebookEditAction.setEnabled(false);
1367 menuBar.notebookDeleteAction.setEnabled(false);
1368 menuBar.notebookStackAction.setEnabled(false);
1369 menuBar.notebookIconAction.setEnabled(false);
1372 if (!guid.equals("") && !guid.equals("STACK")) {
1373 selectedNotebookGUIDs.add(guid);
1374 menuBar.notebookIconAction.setEnabled(true);
1376 menuBar.notebookIconAction.setEnabled(true);
1377 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1378 Notebook book = listManager.getNotebookIndex().get(j);
1379 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1380 selectedNotebookGUIDs.add(book.getGuid());
1383 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1384 listManager.loadNotesIndex();
1385 noteIndexUpdated(false);
1386 listManager.refreshCounters = true;
1387 listManager.refreshCounters();
1388 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1391 private void clearNotebookFilter() {
1392 notebookTree.blockSignals(true);
1393 notebookTree.clearSelection();
1394 menuBar.noteRestoreAction.setVisible(false);
1395 menuBar.notebookEditAction.setEnabled(false);
1396 menuBar.notebookDeleteAction.setEnabled(false);
1397 selectedNotebookGUIDs.clear();
1398 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1399 notebookTree.blockSignals(false);
1401 // Triggered when the notebook DB has been updated
1402 private void notebookIndexUpdated() {
1403 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1405 // Get the possible icons
1406 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1407 notebookTree.setIcons(icons);
1409 if (selectedNotebookGUIDs == null)
1410 selectedNotebookGUIDs = new ArrayList<String>();
1411 List<Notebook> books = conn.getNotebookTable().getAll();
1412 for (int i=books.size()-1; i>=0; i--) {
1413 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1414 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1416 j=listManager.getArchiveNotebookIndex().size();
1422 listManager.countNotebookResults(listManager.getNoteIndex());
1423 notebookTree.blockSignals(true);
1424 notebookTree.load(books, listManager.getLocalNotebooks());
1425 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1426 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1428 selectedNotebookGUIDs.remove(i);
1430 listManager.refreshCounters = true;
1431 listManager.refreshCounters();
1432 notebookTree.blockSignals(false);
1434 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1436 // Show/Hide note information
1437 private void toggleNotebookWindow() {
1438 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1439 searchLayout.toggleNotebook();
1440 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1441 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1442 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1444 // Add a new notebook
1445 @SuppressWarnings("unused")
1446 private void addNotebook() {
1447 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1448 NotebookEdit edit = new NotebookEdit();
1449 edit.setNotebooks(listManager.getNotebookIndex());
1452 if (!edit.okPressed())
1455 Calendar currentTime = new GregorianCalendar();
1456 Long l = new Long(currentTime.getTimeInMillis());
1457 String randint = new String(Long.toString(l));
1459 Notebook newBook = new Notebook();
1460 newBook.setUpdateSequenceNum(0);
1461 newBook.setGuid(randint);
1462 newBook.setName(edit.getNotebook());
1463 newBook.setServiceCreated(new Date().getTime());
1464 newBook.setServiceUpdated(new Date().getTime());
1465 newBook.setDefaultNotebook(false);
1466 newBook.setPublished(false);
1468 listManager.getNotebookIndex().add(newBook);
1470 listManager.getLocalNotebooks().add(newBook.getGuid());
1471 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1472 notebookIndexUpdated();
1473 listManager.countNotebookResults(listManager.getNoteIndex());
1474 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1475 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1477 // Edit an existing notebook
1478 @SuppressWarnings("unused")
1479 private void stackNotebook() {
1480 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1481 StackNotebook edit = new StackNotebook();
1483 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1484 QTreeWidgetItem currentSelection;
1485 for (int i=0; i<selections.size(); i++) {
1486 currentSelection = selections.get(0);
1487 String guid = currentSelection.text(2);
1488 if (guid.equalsIgnoreCase("")) {
1489 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1492 if (guid.equalsIgnoreCase("STACK")) {
1493 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1498 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1503 if (!edit.okPressed())
1506 String stack = edit.getStackName();
1508 for (int i=0; i<selections.size(); i++) {
1509 currentSelection = selections.get(i);
1510 String guid = currentSelection.text(2);
1511 listManager.updateNotebookStack(guid, stack);
1513 notebookIndexUpdated();
1514 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1516 // Edit an existing notebook
1517 @SuppressWarnings("unused")
1518 private void editNotebook() {
1519 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1520 NotebookEdit edit = new NotebookEdit();
1522 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1523 QTreeWidgetItem currentSelection;
1524 currentSelection = selections.get(0);
1525 edit.setNotebook(currentSelection.text(0));
1527 String guid = currentSelection.text(2);
1528 if (!guid.equalsIgnoreCase("STACK")) {
1529 edit.setTitle(tr("Edit Notebook"));
1530 edit.setNotebooks(listManager.getNotebookIndex());
1531 edit.setLocalCheckboxEnabled(false);
1532 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1533 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1534 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1535 i=listManager.getNotebookIndex().size();
1539 edit.setTitle(tr("Edit Stack"));
1540 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1541 edit.hideLocalCheckbox();
1542 edit.hideDefaultCheckbox();
1547 if (!edit.okPressed())
1551 if (guid.equalsIgnoreCase("STACK")) {
1552 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1553 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1554 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1555 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1556 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1558 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1559 currentSelection.setText(0, edit.getNotebook());
1563 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1564 currentSelection.setText(0, edit.getNotebook());
1566 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1567 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1568 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1569 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1570 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1571 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1572 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1573 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1575 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1576 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1577 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1578 linkedNotebook.setShareName(edit.getNotebook());
1579 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1581 i=listManager.getNotebookIndex().size();
1585 // Build a list of non-closed notebooks
1586 List<Notebook> nbooks = new ArrayList<Notebook>();
1587 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1588 boolean found=false;
1589 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1590 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1594 nbooks.add(listManager.getNotebookIndex().get(i));
1598 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1599 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1600 browserWindow.setNotebookList(filteredBooks);
1601 Iterator<String> set = externalWindows.keySet().iterator();
1602 while(set.hasNext())
1603 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1604 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1606 // Publish a notebook
1607 @SuppressWarnings("unused")
1608 private void publishNotebook() {
1609 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1610 QTreeWidgetItem currentSelection;
1611 currentSelection = selections.get(0);
1612 String guid = currentSelection.text(2);
1614 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1619 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1620 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1621 n = listManager.getNotebookIndex().get(i);
1623 i = listManager.getNotebookIndex().size();
1629 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1632 if (!publish.okClicked())
1635 Publishing p = publish.getPublishing();
1636 boolean isPublished = !publish.isStopPressed();
1637 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1638 n.setPublished(isPublished);
1640 listManager.getNotebookIndex().set(position, n);
1641 notebookIndexUpdated();
1643 // Publish a notebook
1644 @SuppressWarnings("unused")
1645 private void shareNotebook() {
1646 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1647 QTreeWidgetItem currentSelection;
1648 currentSelection = selections.get(0);
1649 String guid = currentSelection.text(2);
1651 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1655 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1656 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1657 n = listManager.getNotebookIndex().get(i);
1658 i = listManager.getNotebookIndex().size();
1662 String authToken = null;
1663 if (syncRunner.isConnected)
1664 authToken = syncRunner.authToken;
1665 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1670 // Delete an existing notebook
1671 @SuppressWarnings("unused")
1672 private void deleteNotebook() {
1673 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1674 boolean stacksFound = false;
1675 boolean notebooksFound = false;
1676 boolean assigned = false;
1677 // Check if any notes have this notebook
1678 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1679 for (int i=0; i<selections.size(); i++) {
1680 QTreeWidgetItem currentSelection;
1681 currentSelection = selections.get(i);
1682 String guid = currentSelection.text(2);
1683 if (!guid.equalsIgnoreCase("STACK")) {
1684 notebooksFound = true;
1685 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1686 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1687 if (noteGuid.equals(guid)) {
1689 j=listManager.getNoteIndex().size();
1690 i=selections.size();
1698 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1699 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1703 if (conn.getNotebookTable().getAll().size() == 1) {
1704 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1708 // If all notebooks are clear, verify the delete
1709 String msg1 = new String(tr("Delete selected notebooks?"));
1710 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1711 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1712 " not deleted unless selected?"));
1714 if (stacksFound && notebooksFound)
1716 if (!stacksFound && notebooksFound)
1718 if (stacksFound && !notebooksFound)
1720 if (QMessageBox.question(this, tr("Confirmation"), msg,
1721 QMessageBox.StandardButton.Yes,
1722 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1726 // If confirmed, delete the notebook
1727 for (int i=selections.size()-1; i>=0; i--) {
1728 QTreeWidgetItem currentSelection;
1729 currentSelection = selections.get(i);
1730 String guid = currentSelection.text(2);
1731 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1732 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1733 listManager.renameStack(currentSelection.text(0), "");
1735 conn.getNotebookTable().expungeNotebook(guid, true);
1736 listManager.deleteNotebook(guid);
1740 notebookIndexUpdated();
1741 // notebookTreeSelection();
1742 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1743 // listManager.countNotebookResults(listManager.getNoteIndex());
1744 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1746 // A note's notebook has been updated
1747 @SuppressWarnings("unused")
1748 private void updateNoteNotebook(String guid, String notebookGuid) {
1750 // Update the list manager
1751 listManager.updateNoteNotebook(guid, notebookGuid);
1752 listManager.countNotebookResults(listManager.getNoteIndex());
1753 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1755 // Find the name of the notebook
1756 String notebookName = null;
1757 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1758 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1759 notebookName = listManager.getNotebookIndex().get(i).getName();
1764 // If we found the name, update the browser window
1765 if (notebookName != null) {
1766 updateListNoteNotebook(guid, notebookName);
1767 if (guid.equals(currentNoteGuid)) {
1768 int pos = browserWindow.notebookBox.findText(notebookName);
1770 browserWindow.notebookBox.setCurrentIndex(pos);
1774 // If we're dealing with the current note, then we need to be sure and update the notebook there
1775 if (guid.equals(currentNoteGuid)) {
1776 if (currentNote != null) {
1777 currentNote.setNotebookGuid(notebookGuid);
1781 // Open/close notebooks
1782 @SuppressWarnings("unused")
1783 private void closeNotebooks() {
1784 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1786 if (!na.okClicked())
1790 listManager.getArchiveNotebookIndex().clear();
1792 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1793 String text = na.getClosedBookList().takeItem(i).text();
1794 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1795 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1796 Notebook n = listManager.getNotebookIndex().get(j);
1797 conn.getNotebookTable().setArchived(n.getGuid(),true);
1798 listManager.getArchiveNotebookIndex().add(n);
1799 j=listManager.getNotebookIndex().size();
1804 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1805 String text = na.getOpenBookList().takeItem(i).text();
1806 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1807 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1808 Notebook n = listManager.getNotebookIndex().get(j);
1809 conn.getNotebookTable().setArchived(n.getGuid(),false);
1810 j=listManager.getNotebookIndex().size();
1814 notebookTreeSelection();
1815 listManager.loadNotesIndex();
1816 notebookIndexUpdated();
1817 noteIndexUpdated(false);
1818 reloadTagTree(true);
1819 // noteIndexUpdated(false);
1821 // Build a list of non-closed notebooks
1822 List<Notebook> nbooks = new ArrayList<Notebook>();
1823 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1824 boolean found=false;
1825 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1826 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1830 nbooks.add(listManager.getNotebookIndex().get(i));
1833 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1834 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1835 browserWindow.setNotebookList(filteredBooks);
1837 // Update any external windows
1838 Iterator<String> set = externalWindows.keySet().iterator();
1839 while(set.hasNext())
1840 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1844 // Change the notebook's icon
1845 @SuppressWarnings("unused")
1846 private void setNotebookIcon() {
1847 boolean stackSelected = false;
1848 boolean allNotebookSelected = false;
1850 QTreeWidgetItem currentSelection;
1851 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1852 if (selections.size() == 0)
1855 currentSelection = selections.get(0);
1856 String guid = currentSelection.text(2);
1857 if (guid.equalsIgnoreCase(""))
1858 allNotebookSelected = true;
1859 if (guid.equalsIgnoreCase("STACK"))
1860 stackSelected = true;
1862 QIcon currentIcon = currentSelection.icon(0);
1866 if (!stackSelected && !allNotebookSelected) {
1867 icon = conn.getNotebookTable().getIcon(guid);
1869 dialog = new SetIcon(currentIcon, saveLastPath);
1870 dialog.setUseDefaultIcon(true);
1872 dialog = new SetIcon(icon, saveLastPath);
1873 dialog.setUseDefaultIcon(false);
1876 if (stackSelected) {
1877 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1879 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1882 dialog = new SetIcon(currentIcon, saveLastPath);
1883 dialog.setUseDefaultIcon(true);
1885 dialog = new SetIcon(icon, saveLastPath);
1886 dialog.setUseDefaultIcon(false);
1890 if (dialog.okPressed()) {
1891 saveLastPath = dialog.getPath();
1893 QIcon newIcon = dialog.getIcon();
1894 if (stackSelected) {
1895 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1896 if (newIcon == null) {
1897 newIcon = new QIcon(iconPath+"books2.png");
1899 currentSelection.setIcon(0,newIcon);
1902 if (allNotebookSelected) {
1903 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1904 if (newIcon == null) {
1905 newIcon = new QIcon(iconPath+"notebook-green.png");
1907 currentSelection.setIcon(0,newIcon);
1910 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1911 if (newIcon == null) {
1912 boolean isPublished = false;;
1913 boolean found = false;
1914 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1915 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1916 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1920 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1922 currentSelection.setIcon(0, newIcon);
1928 //***************************************************************
1929 //***************************************************************
1930 //** These functions deal with Tag menu items
1931 //***************************************************************
1932 //***************************************************************
1933 // Add a new notebook
1934 @SuppressWarnings("unused")
1935 private void addTag() {
1936 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1937 TagEdit edit = new TagEdit();
1938 edit.setTagList(listManager.getTagIndex());
1941 if (!edit.okPressed())
1944 Calendar currentTime = new GregorianCalendar();
1945 Long l = new Long(currentTime.getTimeInMillis());
1946 String randint = new String(Long.toString(l));
1948 Tag newTag = new Tag();
1949 newTag.setUpdateSequenceNum(0);
1950 newTag.setGuid(randint);
1951 newTag.setName(edit.getTag());
1952 conn.getTagTable().addTag(newTag, true);
1953 listManager.getTagIndex().add(newTag);
1954 reloadTagTree(true);
1956 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1958 @SuppressWarnings("unused")
1959 private void reloadTagTree() {
1960 reloadTagTree(false);
1962 private void reloadTagTree(boolean reload) {
1963 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1964 tagIndexUpdated(reload);
1965 boolean filter = false;
1967 listManager.countTagResults(listManager.getNoteIndex());
1968 if (notebookTree.selectedItems().size() > 0
1969 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1971 if (tagTree.selectedItems().size() > 0)
1973 tagTree.showAllTags(!filter);
1974 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1976 // Edit an existing tag
1977 @SuppressWarnings("unused")
1978 private void editTag() {
1979 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1980 TagEdit edit = new TagEdit();
1981 edit.setTitle("Edit Tag");
1982 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1983 QTreeWidgetItem currentSelection;
1984 currentSelection = selections.get(0);
1985 edit.setTag(currentSelection.text(0));
1986 edit.setTagList(listManager.getTagIndex());
1989 if (!edit.okPressed())
1992 String guid = currentSelection.text(2);
1993 currentSelection.setText(0,edit.getTag());
1995 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1996 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1997 listManager.getTagIndex().get(i).setName(edit.getTag());
1998 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1999 updateListTagName(guid);
2000 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2001 browserWindow.setTag(getTagNamesForNote(currentNote));
2002 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2006 browserWindow.setTag(getTagNamesForNote(currentNote));
2007 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2009 // Delete an existing tag
2010 @SuppressWarnings("unused")
2011 private void deleteTag() {
2012 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2014 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2015 QMessageBox.StandardButton.Yes,
2016 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2020 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2021 for (int i=selections.size()-1; i>=0; i--) {
2022 QTreeWidgetItem currentSelection;
2023 currentSelection = selections.get(i);
2024 removeTagItem(currentSelection.text(2));
2026 tagIndexUpdated(true);
2028 listManager.countTagResults(listManager.getNoteIndex());
2029 // tagTree.updateCounts(listManager.getTagCounter());
2030 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2032 // Remove a tag tree item. Go recursively down & remove the children too
2033 private void removeTagItem(String guid) {
2034 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2035 String parent = listManager.getTagIndex().get(j).getParentGuid();
2036 if (parent != null && parent.equals(guid)) {
2037 //Remove this tag's children
2038 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2041 //Now, remove this tag
2042 removeListTagName(guid);
2043 conn.getTagTable().expungeTag(guid, true);
2044 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2045 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2046 listManager.getTagIndex().remove(a);
2051 // Setup the tree containing the user's tags
2052 private void initializeTagTree() {
2053 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2054 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2055 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2056 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2057 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2058 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2060 // Listener when a tag is selected
2061 private void tagTreeSelection() {
2062 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2065 clearAttributeFilter();
2066 clearSavedSearchFilter();
2068 menuBar.noteRestoreAction.setVisible(false);
2070 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2071 QTreeWidgetItem currentSelection;
2072 selectedTagGUIDs.clear();
2073 for (int i=0; i<selections.size(); i++) {
2074 currentSelection = selections.get(i);
2075 selectedTagGUIDs.add(currentSelection.text(2));
2077 if (selections.size() > 0) {
2078 menuBar.tagEditAction.setEnabled(true);
2079 menuBar.tagDeleteAction.setEnabled(true);
2080 menuBar.tagIconAction.setEnabled(true);
2083 menuBar.tagEditAction.setEnabled(false);
2084 menuBar.tagDeleteAction.setEnabled(false);
2085 menuBar.tagIconAction.setEnabled(true);
2087 listManager.setSelectedTags(selectedTagGUIDs);
2088 listManager.loadNotesIndex();
2089 noteIndexUpdated(false);
2090 listManager.refreshCounters = true;
2091 listManager.refreshCounters();
2092 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2094 // trigger the tag index to be refreshed
2095 @SuppressWarnings("unused")
2096 private void tagIndexUpdated() {
2097 tagIndexUpdated(true);
2099 private void tagIndexUpdated(boolean reload) {
2100 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2101 if (selectedTagGUIDs == null)
2102 selectedTagGUIDs = new ArrayList<String>();
2104 listManager.reloadTagIndex();
2106 tagTree.blockSignals(true);
2108 tagTree.setIcons(conn.getTagTable().getAllIcons());
2109 tagTree.load(listManager.getTagIndex());
2112 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2113 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2115 selectedTagGUIDs.remove(i);
2117 tagTree.blockSignals(false);
2119 browserWindow.setTag(getTagNamesForNote(currentNote));
2120 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2122 // Show/Hide note information
2123 private void toggleTagWindow() {
2124 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2125 if (tagTree.isVisible())
2129 menuBar.hideTags.setChecked(tagTree.isVisible());
2130 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2131 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2133 // A note's tags have been updated
2134 @SuppressWarnings("unused")
2135 private void updateNoteTags(String guid, List<String> tags) {
2136 // Save any new tags. We'll need them later.
2137 List<String> newTags = new ArrayList<String>();
2138 for (int i=0; i<tags.size(); i++) {
2139 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2140 newTags.add(tags.get(i));
2143 listManager.saveNoteTags(guid, tags);
2144 listManager.countTagResults(listManager.getNoteIndex());
2145 StringBuffer names = new StringBuffer("");
2146 for (int i=0; i<tags.size(); i++) {
2147 names = names.append(tags.get(i));
2148 if (i<tags.size()-1) {
2149 names.append(Global.tagDelimeter + " ");
2152 browserWindow.setTag(names.toString());
2155 // Now, we need to add any new tags to the tag tree
2156 for (int i=0; i<newTags.size(); i++)
2157 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2159 // Get a string containing all tag names for a note
2160 private String getTagNamesForNote(Note n) {
2161 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2162 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2164 StringBuffer buffer = new StringBuffer(100);
2165 Vector<String> v = new Vector<String>();
2166 List<String> guids = n.getTagGuids();
2171 for (int i=0; i<guids.size(); i++) {
2172 v.add(listManager.getTagNameByGuid(guids.get(i)));
2174 Comparator<String> comparator = Collections.reverseOrder();
2175 Collections.sort(v,comparator);
2176 Collections.reverse(v);
2178 for (int i = 0; i<v.size(); i++) {
2180 buffer.append(", ");
2181 buffer.append(v.get(i));
2184 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2185 return buffer.toString();
2187 // Tags were added via dropping notes from the note list
2188 @SuppressWarnings("unused")
2189 private void tagsAdded(String noteGuid, String tagGuid) {
2190 String tagName = null;
2191 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2192 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2193 tagName = listManager.getTagIndex().get(i).getName();
2194 i=listManager.getTagIndex().size();
2197 if (tagName == null)
2200 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2201 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2202 List<String> tagNames = new ArrayList<String>();
2203 tagNames.add(new String(tagName));
2204 Note n = listManager.getMasterNoteIndex().get(i);
2205 for (int j=0; j<n.getTagNames().size(); j++) {
2206 tagNames.add(new String(n.getTagNames().get(j)));
2208 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2209 if (n.getGuid().equals(currentNoteGuid)) {
2210 Collections.sort(tagNames);
2211 String display = "";
2212 for (int j=0; j<tagNames.size(); j++) {
2213 display = display+tagNames.get(j);
2214 if (j+2<tagNames.size())
2215 display = display+Global.tagDelimeter+" ";
2217 browserWindow.setTag(display);
2219 i=listManager.getMasterNoteIndex().size();
2224 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2226 private void clearTagFilter() {
2227 tagTree.blockSignals(true);
2228 tagTree.clearSelection();
2229 menuBar.noteRestoreAction.setVisible(false);
2230 menuBar.tagEditAction.setEnabled(false);
2231 menuBar.tagDeleteAction.setEnabled(false);
2232 menuBar.tagIconAction.setEnabled(false);
2233 selectedTagGUIDs.clear();
2234 listManager.setSelectedTags(selectedTagGUIDs);
2235 tagTree.blockSignals(false);
2237 // Change the icon for a tag
2238 @SuppressWarnings("unused")
2239 private void setTagIcon() {
2240 QTreeWidgetItem currentSelection;
2241 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2242 if (selections.size() == 0)
2245 currentSelection = selections.get(0);
2246 String guid = currentSelection.text(2);
2248 QIcon currentIcon = currentSelection.icon(0);
2249 QIcon icon = conn.getTagTable().getIcon(guid);
2252 dialog = new SetIcon(currentIcon, saveLastPath);
2253 dialog.setUseDefaultIcon(true);
2255 dialog = new SetIcon(icon, saveLastPath);
2256 dialog.setUseDefaultIcon(false);
2259 if (dialog.okPressed()) {
2260 saveLastPath = dialog.getPath();
2261 QIcon newIcon = dialog.getIcon();
2262 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2263 if (newIcon == null)
2264 newIcon = new QIcon(iconPath+"tag.png");
2265 currentSelection.setIcon(0, newIcon);
2271 //***************************************************************
2272 //***************************************************************
2273 //** These functions deal with Saved Search menu items
2274 //***************************************************************
2275 //***************************************************************
2276 // Add a new notebook
2277 @SuppressWarnings("unused")
2278 private void addSavedSearch() {
2279 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2280 SavedSearchEdit edit = new SavedSearchEdit();
2281 edit.setSearchList(listManager.getSavedSearchIndex());
2284 if (!edit.okPressed())
2287 Calendar currentTime = new GregorianCalendar();
2288 Long l = new Long(currentTime.getTimeInMillis());
2289 String randint = new String(Long.toString(l));
2291 SavedSearch search = new SavedSearch();
2292 search.setUpdateSequenceNum(0);
2293 search.setGuid(randint);
2294 search.setName(edit.getName());
2295 search.setQuery(edit.getQuery());
2296 search.setFormat(QueryFormat.USER);
2297 listManager.getSavedSearchIndex().add(search);
2298 conn.getSavedSearchTable().addSavedSearch(search, true);
2299 savedSearchIndexUpdated();
2300 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2302 // Edit an existing tag
2303 @SuppressWarnings("unused")
2304 private void editSavedSearch() {
2305 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2306 SavedSearchEdit edit = new SavedSearchEdit();
2307 edit.setTitle(tr("Edit Search"));
2308 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2309 QTreeWidgetItem currentSelection;
2310 currentSelection = selections.get(0);
2311 String guid = currentSelection.text(1);
2312 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2313 edit.setName(currentSelection.text(0));
2314 edit.setQuery(s.getQuery());
2315 edit.setSearchList(listManager.getSavedSearchIndex());
2318 if (!edit.okPressed())
2321 List<SavedSearch> list = listManager.getSavedSearchIndex();
2322 SavedSearch search = null;
2323 boolean found = false;
2324 for (int i=0; i<list.size(); i++) {
2325 search = list.get(i);
2326 if (search.getGuid().equals(guid)) {
2333 search.setName(edit.getName());
2334 search.setQuery(edit.getQuery());
2335 conn.getSavedSearchTable().updateSavedSearch(search, true);
2336 savedSearchIndexUpdated();
2337 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2339 // Delete an existing tag
2340 @SuppressWarnings("unused")
2341 private void deleteSavedSearch() {
2342 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2344 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2345 QMessageBox.StandardButton.Yes,
2346 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2350 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2351 for (int i=selections.size()-1; i>=0; i--) {
2352 QTreeWidgetItem currentSelection;
2353 currentSelection = selections.get(i);
2354 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2355 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2356 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2357 listManager.getSavedSearchIndex().remove(j);
2358 j=listManager.getSavedSearchIndex().size()+1;
2361 selections.remove(i);
2363 savedSearchIndexUpdated();
2364 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2366 // Setup the tree containing the user's tags
2367 private void initializeSavedSearchTree() {
2368 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2369 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2370 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2372 // Listener when a tag is selected
2373 @SuppressWarnings("unused")
2374 private void savedSearchTreeSelection() {
2375 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2377 clearNotebookFilter();
2380 clearAttributeFilter();
2382 String currentGuid = selectedSavedSearchGUID;
2383 menuBar.savedSearchEditAction.setEnabled(true);
2384 menuBar.savedSearchDeleteAction.setEnabled(true);
2385 menuBar.savedSearchIconAction.setEnabled(true);
2386 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2387 QTreeWidgetItem currentSelection;
2388 selectedSavedSearchGUID = "";
2389 for (int i=0; i<selections.size(); i++) {
2390 currentSelection = selections.get(i);
2391 if (currentSelection.text(1).equals(currentGuid)) {
2392 currentSelection.setSelected(false);
2394 selectedSavedSearchGUID = currentSelection.text(1);
2396 // i = selections.size() +1;
2399 // There is the potential for no notebooks to be selected if this
2400 // happens then we make it look like all notebooks were selecetd.
2401 // If that happens, just select the "all notebooks"
2402 if (selections.size()==0) {
2403 clearSavedSearchFilter();
2405 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2407 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2409 private void clearSavedSearchFilter() {
2410 menuBar.savedSearchEditAction.setEnabled(false);
2411 menuBar.savedSearchDeleteAction.setEnabled(false);
2412 menuBar.savedSearchIconAction.setEnabled(false);
2413 savedSearchTree.blockSignals(true);
2414 savedSearchTree.clearSelection();
2415 savedSearchTree.blockSignals(false);
2416 selectedSavedSearchGUID = "";
2417 searchField.setEditText("");
2418 searchPerformed = false;
2419 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2421 // trigger the tag index to be refreshed
2422 private void savedSearchIndexUpdated() {
2423 if (selectedSavedSearchGUID == null)
2424 selectedSavedSearchGUID = new String();
2425 savedSearchTree.blockSignals(true);
2426 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2427 savedSearchTree.load(listManager.getSavedSearchIndex());
2428 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2429 savedSearchTree.blockSignals(false);
2431 // trigger when the saved search selection changes
2432 @SuppressWarnings("unused")
2433 private void updateSavedSearchSelection() {
2434 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2436 menuBar.savedSearchEditAction.setEnabled(true);
2437 menuBar.savedSearchDeleteAction.setEnabled(true);
2438 menuBar.savedSearchIconAction.setEnabled(true);
2439 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2441 if (selections.size() > 0) {
2442 menuBar.savedSearchEditAction.setEnabled(true);
2443 menuBar.savedSearchDeleteAction.setEnabled(true);
2444 menuBar.savedSearchIconAction.setEnabled(true);
2445 selectedSavedSearchGUID = selections.get(0).text(1);
2446 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2447 searchField.setEditText(s.getQuery());
2449 menuBar.savedSearchEditAction.setEnabled(false);
2450 menuBar.savedSearchDeleteAction.setEnabled(false);
2451 menuBar.savedSearchIconAction.setEnabled(false);
2452 selectedSavedSearchGUID = "";
2453 searchField.setEditText("");
2455 searchFieldChanged();
2457 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2461 // Show/Hide note information
2462 private void toggleSavedSearchWindow() {
2463 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2464 if (savedSearchTree.isVisible())
2465 savedSearchTree.hide();
2467 savedSearchTree.show();
2468 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2470 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2471 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2473 // Change the icon for a saved search
2474 @SuppressWarnings("unused")
2475 private void setSavedSearchIcon() {
2476 QTreeWidgetItem currentSelection;
2477 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2478 if (selections.size() == 0)
2481 currentSelection = selections.get(0);
2482 String guid = currentSelection.text(1);
2484 QIcon currentIcon = currentSelection.icon(0);
2485 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2488 dialog = new SetIcon(currentIcon, saveLastPath);
2489 dialog.setUseDefaultIcon(true);
2491 dialog = new SetIcon(icon, saveLastPath);
2492 dialog.setUseDefaultIcon(false);
2495 if (dialog.okPressed()) {
2496 saveLastPath = dialog.getPath();
2497 QIcon newIcon = dialog.getIcon();
2498 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2499 if (newIcon == null)
2500 newIcon = new QIcon(iconPath+"search.png");
2501 currentSelection.setIcon(0, newIcon);
2509 //***************************************************************
2510 //***************************************************************
2511 //** These functions deal with Help menu & tool menu items
2512 //***************************************************************
2513 //***************************************************************
2514 // Show database status
2515 @SuppressWarnings("unused")
2516 private void databaseStatus() {
2518 indexRunner.interrupt = true;
2519 int dirty = conn.getNoteTable().getDirtyCount();
2520 int unindexed = conn.getNoteTable().getUnindexedCount();
2521 DatabaseStatus status = new DatabaseStatus();
2522 status.setUnsynchronized(dirty);
2523 status.setUnindexed(unindexed);
2524 status.setNoteCount(conn.getNoteTable().getNoteCount());
2525 status.setNotebookCount(listManager.getNotebookIndex().size());
2526 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2527 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2528 status.setTagCount(listManager.getTagIndex().size());
2529 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2530 status.setWordCount(conn.getWordsTable().getWordCount());
2534 // Compact the database
2535 @SuppressWarnings("unused")
2536 private void compactDatabase() {
2537 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2538 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2539 "but please be aware that depending upon the size of your database this can be time consuming " +
2540 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2541 QMessageBox.StandardButton.Yes,
2542 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2545 setMessage("Compacting database.");
2547 listManager.compactDatabase();
2549 setMessage("Database compact is complete.");
2550 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2552 @SuppressWarnings("unused")
2553 private void accountInformation() {
2554 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2555 AccountDialog dialog = new AccountDialog();
2557 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2559 @SuppressWarnings("unused")
2560 private void releaseNotes() {
2561 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2562 QDialog dialog = new QDialog(this);
2563 QHBoxLayout layout = new QHBoxLayout();
2564 QTextEdit textBox = new QTextEdit();
2565 layout.addWidget(textBox);
2566 textBox.setReadOnly(true);
2567 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2568 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2569 QIODevice.OpenModeFlag.Text)))
2571 textBox.setText(file.readAll().toString());
2573 dialog.setWindowTitle(tr("Release Notes"));
2574 dialog.setLayout(layout);
2576 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2578 // Called when user picks Log from the help menu
2579 @SuppressWarnings("unused")
2580 private void logger() {
2581 logger.log(logger.HIGH, "Entering NeverNote.logger");
2582 LogFileDialog dialog = new LogFileDialog(emitLog);
2584 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2586 // Menu option "help/about" was selected
2587 @SuppressWarnings("unused")
2588 private void about() {
2589 logger.log(logger.HIGH, "Entering NeverNote.about");
2590 QMessageBox.about(this,
2591 tr("About NeverNote"),
2592 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2594 +tr("<hr></center>Evernote"
2595 +"An Open Source Evernote Client.<br><br>"
2596 +"Licensed under GPL v2. <br><hr><br>"
2597 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2598 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2599 +"PDFRenderer is licened under the LGPL<br>"
2600 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2601 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2602 +"Jazzy is licened under the LGPL<br>"
2603 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
2604 logger.log(logger.HIGH, "Leaving NeverNote.about");
2606 // Hide the entire left hand side
2607 @SuppressWarnings("unused")
2608 private void toggleLeftSide() {
2611 hidden = !menuBar.hideLeftSide.isChecked();
2612 menuBar.hideLeftSide.setChecked(!hidden);
2615 leftSplitter1.setHidden(true);
2617 leftSplitter1.setHidden(false);
2619 Global.saveWindowVisible("leftPanel", hidden);
2622 public void checkForUpdates() {
2623 // Send off thread to check for a new version
2624 versionChecker = new QNetworkAccessManager(this);
2625 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2626 QNetworkRequest request = new QNetworkRequest();
2627 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2628 versionChecker.get(request);
2630 @SuppressWarnings("unused")
2631 private void upgradeFileRead(QNetworkReply reply) {
2632 if (!reply.isReadable())
2635 String winVersion = Global.version;
2636 String osxVersion = Global.version;
2637 String linuxVersion = Global.version;
2638 String linux64Version = Global.version;
2639 String version = Global.version;
2641 // Determine the versions available
2642 QByteArray data = reply.readLine();
2643 while (data != null && !reply.atEnd()) {
2644 String line = data.toString();
2646 if (line.contains(":"))
2647 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2650 if (line.toLowerCase().contains("windows"))
2651 winVersion = lineVersion;
2652 else if (line.toLowerCase().contains("os-x"))
2653 osxVersion = lineVersion;
2654 else if (line.toLowerCase().contains("linux amd64"))
2655 linux64Version = lineVersion;
2656 else if (line.toLowerCase().contains("linux i386"))
2657 linuxVersion = lineVersion;
2658 else if (line.toLowerCase().contains("default"))
2659 version = lineVersion;
2661 // Read the next line
2662 data = reply.readLine();
2665 // Now we need to determine what system we are on.
2666 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2667 version = winVersion;
2668 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2669 version = osxVersion;
2670 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2671 if (System.getProperty("os.arch").contains("amd64") ||
2672 System.getProperty("os.arch").contains("x86_64"))
2673 version = linux64Version;
2675 version = linuxVersion;
2679 for (String validVersion : Global.validVersions) {
2680 if (version.equals(validVersion))
2684 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2686 if (dialog.remindMe())
2687 Global.setCheckVersionUpgrade(true);
2689 Global.setCheckVersionUpgrade(false);
2693 //***************************************************************
2694 //***************************************************************
2695 //** These functions deal with the Toolbar
2696 //***************************************************************
2697 //***************************************************************
2698 @SuppressWarnings("unused")
2699 private void focusSearch() {
2700 searchField.setFocus();
2703 // Text in the search bar has been cleared
2704 private void searchFieldCleared() {
2707 // This is done because we want to force a reload of
2708 // images. Some images we may want to highlight the text.
2709 readOnlyCache.clear();
2710 inkNoteCache.clear();
2712 QWebSettings.setMaximumPagesInCache(0);
2713 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2715 searchField.setEditText("");
2716 saveNoteColumnPositions();
2717 saveNoteIndexWidth();
2718 noteIndexUpdated(true);
2719 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2720 currentNote = listManager.getNoteIndex().get(0);
2721 currentNoteGuid = currentNote.getGuid();
2723 if (currentNote != null)
2724 loadNoteBrowserInformation(browserWindow);
2726 // text in the search bar changed. We only use this to tell if it was cleared,
2727 // otherwise we trigger off searchFieldChanged.
2728 @SuppressWarnings("unused")
2729 private void searchFieldTextChanged(String text) {
2730 QWebSettings.setMaximumPagesInCache(0);
2731 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2733 if (text.trim().equals("")) {
2734 searchFieldCleared();
2735 if (searchPerformed) {
2737 // This is done because we want to force a reload of
2738 // images. Some images we may want to highlight the text.
2740 readOnlyCache.clear();
2741 inkNoteCache.clear();
2743 listManager.setEnSearch("");
2744 listManager.loadNotesIndex();
2745 refreshEvernoteNote(true);
2746 noteIndexUpdated(false);
2748 searchPerformed = false;
2751 // Text in the toolbar has changed
2752 private void searchFieldChanged() {
2753 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2755 readOnlyCache.clear();
2756 inkNoteCache.clear();
2757 saveNoteColumnPositions();
2758 saveNoteIndexWidth();
2759 String text = searchField.currentText();
2760 listManager.setEnSearch(text.trim());
2761 listManager.loadNotesIndex();
2762 noteIndexUpdated(false);
2763 refreshEvernoteNote(true);
2764 searchPerformed = true;
2765 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2768 // Build the window tool bar
2769 private void setupToolBar() {
2770 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2771 toolBar = addToolBar(tr("Tool Bar"));
2772 menuBar.setupToolBarVisible();
2773 if (!Global.isWindowVisible("toolBar"))
2774 toolBar.setVisible(false);
2776 toolBar.setVisible(true);
2778 // toolBar.addWidget(menuBar);
2779 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2780 // toolBar.addSeparator();
2781 prevButton = toolBar.addAction("Previous");
2782 QIcon prevIcon = new QIcon(iconPath+"back.png");
2783 prevButton.setIcon(prevIcon);
2784 prevButton.triggered.connect(this, "previousViewedAction()");
2785 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2787 nextButton = toolBar.addAction("Next");
2788 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2789 nextButton.setIcon(nextIcon);
2790 nextButton.triggered.connect(this, "nextViewedAction()");
2791 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2793 upButton = toolBar.addAction("Up");
2794 QIcon upIcon = new QIcon(iconPath+"up.png");
2795 upButton.setIcon(upIcon);
2796 upButton.triggered.connect(this, "upAction()");
2797 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2800 downButton = toolBar.addAction("Down");
2801 QIcon downIcon = new QIcon(iconPath+"down.png");
2802 downButton.setIcon(downIcon);
2803 downButton.triggered.connect(this, "downAction()");
2804 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2806 synchronizeButton = toolBar.addAction("Synchronize");
2807 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2808 synchronizeIconAngle = 0;
2809 synchronizeButton.triggered.connect(this, "evernoteSync()");
2810 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2812 printButton = toolBar.addAction("Print");
2813 QIcon printIcon = new QIcon(iconPath+"print.png");
2814 printButton.setIcon(printIcon);
2815 printButton.triggered.connect(this, "printNote()");
2816 togglePrintButton(Global.isToolbarButtonVisible("print"));
2818 tagButton = toolBar.addAction("Tag");
2819 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2820 tagButton.setIcon(tagIcon);
2821 tagButton.triggered.connect(browserWindow, "modifyTags()");
2822 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2824 attributeButton = toolBar.addAction("Attributes");
2825 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2826 attributeButton.setIcon(attributeIcon);
2827 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2828 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2830 emailButton = toolBar.addAction("Email");
2831 QIcon emailIcon = new QIcon(iconPath+"email.png");
2832 emailButton.setIcon(emailIcon);
2833 emailButton.triggered.connect(this, "emailNote()");
2834 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2836 deleteButton = toolBar.addAction("Delete");
2837 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2838 deleteButton.setIcon(deleteIcon);
2839 deleteButton.triggered.connect(this, "deleteNote()");
2840 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2842 newButton = toolBar.addAction("New");
2843 QIcon newIcon = new QIcon(iconPath+"new.png");
2844 newButton.triggered.connect(this, "addNote()");
2845 newButton.setIcon(newIcon);
2846 toggleNewButton(Global.isToolbarButtonVisible("new"));
2848 allNotesButton = toolBar.addAction("All Notes");
2849 QIcon allIcon = new QIcon(iconPath+"books.png");
2850 allNotesButton.triggered.connect(this, "allNotes()");
2851 allNotesButton.setIcon(allIcon);
2852 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2854 //toolBar.addSeparator();
2855 //toolBar.addWidget(new QLabel(tr("Quota:")));
2856 //toolBar.addWidget(quotaBar);
2857 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2859 //toolBar.addSeparator();
2861 //toolBar.addWidget(new QLabel(tr("Zoom")));
2862 //toolBar.addWidget(zoomSpinner);
2864 //toolBar.addWidget(new QLabel(" "));
2865 //toolBar.addSeparator();
2866 //toolBar.addWidget(new QLabel(tr(" Search:")));
2867 //toolBar.addWidget(searchField);
2868 QSizePolicy sizePolicy = new QSizePolicy();
2869 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2870 QLabel spacer = new QLabel("");
2871 spacer.setSizePolicy(sizePolicy);
2872 toolBar.addWidget(spacer);
2873 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2875 //searchClearButton = toolBar.addAction("Search Clear");
2876 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2877 //searchClearButton.setIcon(searchClearIcon);
2878 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
2879 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2881 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2883 // Update the sychronize button picture
2885 public QMenu createPopupMenu() {
2886 QMenu contextMenu = super.createPopupMenu();
2888 contextMenu.addSeparator();
2889 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2890 contextMenu.addAction(prevAction);
2891 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2893 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2894 contextMenu.addAction(nextAction);
2895 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2897 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2898 contextMenu.addAction(upAction);
2899 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2901 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2902 contextMenu.addAction(downAction);
2903 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2905 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2906 contextMenu.addAction(synchronizeAction);
2907 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2909 QAction printAction = addContextAction("print", tr("Print"));
2910 contextMenu.addAction(printAction);
2911 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2913 QAction tagAction = addContextAction("tag", tr("Tag"));
2914 contextMenu.addAction(tagAction);
2915 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2917 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2918 contextMenu.addAction(attributeAction);
2919 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2921 QAction emailAction = addContextAction("email", tr("Email"));
2922 contextMenu.addAction(emailAction);
2923 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2925 QAction deleteAction = addContextAction("delete", tr("Delete"));
2926 contextMenu.addAction(deleteAction);
2927 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2929 QAction newAction = addContextAction("new", tr("Add"));
2930 contextMenu.addAction(newAction);
2931 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2933 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2934 contextMenu.addAction(allNotesAction);
2935 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2937 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2938 contextMenu.addAction(searchClearAction);
2939 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2944 private QAction addContextAction(String config, String name) {
2945 QAction newAction = new QAction(this);
2946 newAction.setText(name);
2947 newAction.setCheckable(true);
2948 newAction.setChecked(Global.isToolbarButtonVisible(config));
2951 private void togglePrevArrowButton(Boolean toggle) {
2952 prevButton.setVisible(toggle);
2953 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2955 private void toggleNextArrowButton(Boolean toggle) {
2956 nextButton.setVisible(toggle);
2957 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2959 private void toggleUpArrowButton(Boolean toggle) {
2960 upButton.setVisible(toggle);
2961 Global.saveToolbarButtonsVisible("upArrow", toggle);
2963 private void toggleDownArrowButton(Boolean toggle) {
2964 downButton.setVisible(toggle);
2965 Global.saveToolbarButtonsVisible("downArrow", toggle);
2967 private void toggleSynchronizeButton(Boolean toggle) {
2968 synchronizeButton.setVisible(toggle);
2969 Global.saveToolbarButtonsVisible("synchronize", toggle);
2971 private void togglePrintButton(Boolean toggle) {
2972 printButton.setVisible(toggle);
2973 Global.saveToolbarButtonsVisible("print", toggle);
2975 private void toggleTagButton(Boolean toggle) {
2976 tagButton.setVisible(toggle);
2977 Global.saveToolbarButtonsVisible("tag", toggle);
2979 private void toggleAttributeButton(Boolean toggle) {
2980 attributeButton.setVisible(toggle);
2981 Global.saveToolbarButtonsVisible("attribute", toggle);
2983 private void toggleEmailButton(Boolean toggle) {
2984 emailButton.setVisible(toggle);
2985 Global.saveToolbarButtonsVisible("email", toggle);
2987 private void toggleDeleteButton(Boolean toggle) {
2988 deleteButton.setVisible(toggle);
2989 Global.saveToolbarButtonsVisible("delete", toggle);
2991 private void toggleNewButton(Boolean toggle) {
2992 newButton.setVisible(toggle);
2993 Global.saveToolbarButtonsVisible("new", toggle);
2995 private void toggleAllNotesButton(Boolean toggle) {
2996 allNotesButton.setVisible(toggle);
2997 Global.saveToolbarButtonsVisible("allNotes", toggle);
2999 @SuppressWarnings("unused")
3000 private void toggleSearchClearButton(Boolean toggle) {
3001 searchClearButton.setVisible(toggle);
3002 Global.saveToolbarButtonsVisible("searchClear", toggle);
3009 @SuppressWarnings("unused")
3010 private void updateSyncButton() {
3012 if (syncIcons == null) {
3013 syncIcons = new ArrayList<QPixmap>();
3015 synchronizeIconAngle = 0;
3016 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3018 for (int i=0; i<=360; i++) {
3019 QPixmap rotatedPix = new QPixmap(pix.size());
3020 QPainter p = new QPainter(rotatedPix);
3021 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3022 QSize size = pix.size();
3023 p.translate(size.width()/2, size.height()/2);
3026 p.setBackgroundMode(BGMode.OpaqueMode);
3027 p.translate(-size.width()/2, -size.height()/2);
3028 p.drawPixmap(0,0, pix);
3030 syncIcons.add(rotatedPix);
3034 synchronizeIconAngle++;
3035 if (synchronizeIconAngle > 359)
3036 synchronizeIconAngle=0;
3037 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3040 // Synchronize with Evernote
3041 @SuppressWarnings("unused")
3042 private void evernoteSync() {
3043 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3044 if (!Global.isConnected)
3046 if (Global.isConnected)
3047 synchronizeAnimationTimer.start(5);
3048 // synchronizeAnimationTimer.start(200);
3050 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3052 private void updateQuotaBar() {
3053 long limit = Global.getUploadLimit();
3054 long amount = Global.getUploadAmount();
3055 if (amount>0 && limit>0) {
3056 int percent =(int)(amount*100/limit);
3057 quotaBar.setValue(percent);
3059 quotaBar.setValue(0);
3062 @SuppressWarnings("unused")
3063 private void zoomChanged() {
3064 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3067 //****************************************************************
3068 //****************************************************************
3069 //* System Tray functions
3070 //****************************************************************
3071 //****************************************************************
3072 private void trayToggleVisible() {
3077 if (windowMaximized)
3084 @SuppressWarnings("unused")
3085 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3086 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3087 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3088 trayToggleVisible();
3093 //***************************************************************
3094 //***************************************************************
3095 //** These functions deal with the trash tree
3096 //***************************************************************
3097 //***************************************************************
3098 // Setup the tree containing the trash.
3099 @SuppressWarnings("unused")
3100 private void trashTreeSelection() {
3101 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3103 clearNotebookFilter();
3105 clearAttributeFilter();
3106 clearSavedSearchFilter();
3108 String tempGuid = currentNoteGuid;
3110 // currentNoteGuid = "";
3111 currentNote = new Note();
3112 selectedNoteGUIDs.clear();
3113 listManager.getSelectedNotebooks().clear();
3114 listManager.getSelectedTags().clear();
3115 listManager.setSelectedSavedSearch("");
3116 browserWindow.clear();
3118 // toggle the add buttons
3119 newButton.setEnabled(!newButton.isEnabled());
3120 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3121 menuBar.noteAdd.setVisible(true);
3123 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3124 if (selections.size() == 0) {
3125 currentNoteGuid = trashNoteGuid;
3126 trashNoteGuid = tempGuid;
3127 Global.showDeleted = false;
3128 menuBar.noteRestoreAction.setEnabled(false);
3129 menuBar.noteRestoreAction.setVisible(false);
3132 currentNoteGuid = trashNoteGuid;
3133 trashNoteGuid = tempGuid;
3134 menuBar.noteRestoreAction.setEnabled(true);
3135 menuBar.noteRestoreAction.setVisible(true);
3136 Global.showDeleted = true;
3138 listManager.loadNotesIndex();
3139 noteIndexUpdated(false);
3140 //// browserWindow.setEnabled(newButton.isEnabled());
3141 browserWindow.setReadOnly(!newButton.isEnabled());
3142 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3144 // Empty the trash file
3145 @SuppressWarnings("unused")
3146 private void emptyTrash() {
3147 // browserWindow.clear();
3148 listManager.emptyTrash();
3149 if (trashTree.selectedItems().size() > 0) {
3150 listManager.getSelectedNotebooks().clear();
3151 listManager.getSelectedTags().clear();
3152 listManager.setSelectedSavedSearch("");
3153 newButton.setEnabled(!newButton.isEnabled());
3154 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3155 menuBar.noteAdd.setVisible(true);
3156 browserWindow.clear();
3159 clearNotebookFilter();
3160 clearSavedSearchFilter();
3161 clearAttributeFilter();
3163 Global.showDeleted = false;
3164 menuBar.noteRestoreAction.setEnabled(false);
3165 menuBar.noteRestoreAction.setVisible(false);
3167 listManager.loadNotesIndex();
3168 noteIndexUpdated(false);
3171 // Show/Hide trash window
3172 private void toggleTrashWindow() {
3173 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3174 if (trashTree.isVisible())
3178 menuBar.hideTrash.setChecked(trashTree.isVisible());
3180 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3181 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3183 private void clearTrashFilter() {
3184 Global.showDeleted = false;
3185 newButton.setEnabled(true);
3186 menuBar.noteAdd.setEnabled(true);
3187 menuBar.noteAdd.setVisible(true);
3188 trashTree.blockSignals(true);
3189 trashTree.clearSelection();
3190 trashTree.blockSignals(false);
3195 //***************************************************************
3196 //***************************************************************
3197 //** These functions deal with connection settings
3198 //***************************************************************
3199 //***************************************************************
3200 // SyncRunner had a problem and things are disconnected
3201 @SuppressWarnings("unused")
3202 private void remoteErrorDisconnect() {
3203 menuBar.connectAction.setText(tr("Connect"));
3204 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3205 menuBar.synchronizeAction.setEnabled(false);
3206 Global.isConnected = false;
3207 synchronizeAnimationTimer.stop();
3210 // Do a manual connect/disconnect
3211 private void remoteConnect() {
3212 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3214 if (Global.isConnected) {
3215 Global.isConnected = false;
3216 syncRunner.enDisconnect();
3217 setupConnectMenuOptions();
3222 AESEncrypter aes = new AESEncrypter();
3224 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3225 } catch (FileNotFoundException e) {
3226 // File not found, so we'll just get empty strings anyway.
3229 if (Global.getProxyValue("url").equals("")) {
3230 System.setProperty("http.proxyHost","") ;
3231 System.setProperty("http.proxyPort", "") ;
3232 System.setProperty("https.proxyHost","") ;
3233 System.setProperty("https.proxyPort", "") ;
3236 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3237 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3238 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3239 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3241 if (Global.getProxyValue("userid").equals("")) {
3242 Authenticator.setDefault(new Authenticator() {
3244 protected PasswordAuthentication getPasswordAuthentication() {
3246 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3252 syncRunner.userStoreUrl = Global.userStoreUrl;
3253 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3254 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3256 String userid = aes.getUserid();
3257 String password = aes.getPassword();
3258 if (!userid.equals("") && !password.equals("")) {
3259 Global.username = userid;
3260 Global.password = password;
3261 syncRunner.username = Global.username;
3262 syncRunner.password = Global.password;
3263 syncRunner.enConnect();
3266 Global.isConnected = syncRunner.isConnected;
3268 if (!Global.isConnected) {
3269 // Show the login dialog box
3270 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3271 LoginDialog login = new LoginDialog();
3274 if (!login.okPressed()) {
3278 Global.username = login.getUserid();
3279 Global.password = login.getPassword();
3281 syncRunner.username = Global.username;
3282 syncRunner.password = Global.password;
3283 syncRunner.enConnect();
3284 Global.isConnected = syncRunner.isConnected;
3287 if (!Global.isConnected)
3290 setupConnectMenuOptions();
3291 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3293 private void setupConnectMenuOptions() {
3294 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3295 if (!Global.isConnected) {
3296 menuBar.connectAction.setText(tr("Connect"));
3297 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3298 menuBar.synchronizeAction.setEnabled(false);
3300 menuBar.connectAction.setText(tr("Disconnect"));
3301 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3302 menuBar.synchronizeAction.setEnabled(true);
3304 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3309 //***************************************************************
3310 //***************************************************************
3311 //** These functions deal with the GUI Attribute tree
3312 //***************************************************************
3313 //***************************************************************
3314 @SuppressWarnings("unused")
3315 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3317 // clearTagFilter();
3318 // clearNotebookFilter();
3320 // clearSavedSearchFilter();
3322 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3323 if (item.childCount() > 0) {
3324 item.setSelected(false);
3326 Global.createdBeforeFilter.reset();
3327 Global.createdSinceFilter.reset();
3328 Global.changedBeforeFilter.reset();
3329 Global.changedSinceFilter.reset();
3330 Global.containsFilter.reset();
3331 attributeTreeSelected = item;
3332 DateAttributeFilterTable f = null;
3333 f = findDateAttributeFilterTable(item.parent());
3335 f.select(item.parent().indexOfChild(item));
3337 Global.containsFilter.select(item.parent().indexOfChild(item));
3340 listManager.loadNotesIndex();
3341 noteIndexUpdated(false);
3344 attributeTreeSelected = null;
3345 item.setSelected(false);
3346 Global.createdBeforeFilter.reset();
3347 Global.createdSinceFilter.reset();
3348 Global.changedBeforeFilter.reset();
3349 Global.changedSinceFilter.reset();
3350 Global.containsFilter.reset();
3351 listManager.loadNotesIndex();
3352 noteIndexUpdated(false);
3354 // This determines what attribute filter we need, depending upon the selection
3355 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3356 if (w.parent() != null && w.childCount() > 0) {
3357 QTreeWidgetItem parent = w.parent();
3358 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3359 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3360 return Global.createdSinceFilter;
3361 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3362 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3363 return Global.createdBeforeFilter;
3364 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3365 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3366 return Global.changedSinceFilter;
3367 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3368 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3369 return Global.changedBeforeFilter;
3374 // Show/Hide attribute search window
3375 private void toggleAttributesWindow() {
3376 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3377 if (attributeTree.isVisible())
3378 attributeTree.hide();
3380 attributeTree.show();
3381 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3383 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3384 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3386 private void clearAttributeFilter() {
3387 Global.createdBeforeFilter.reset();
3388 Global.createdSinceFilter.reset();
3389 Global.changedBeforeFilter.reset();
3390 Global.changedSinceFilter.reset();
3391 Global.containsFilter.reset();
3392 attributeTreeSelected = null;
3393 attributeTree.blockSignals(true);
3394 attributeTree.clearSelection();
3395 attributeTree.blockSignals(false);
3399 //***************************************************************
3400 //***************************************************************
3401 //** These functions deal with the GUI Note index table
3402 //***************************************************************
3403 //***************************************************************
3404 // Initialize the note list table
3405 private void initializeNoteTable() {
3406 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3407 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3408 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3409 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3411 // Show/Hide trash window
3412 @SuppressWarnings("unused")
3413 private void toggleNoteListWindow() {
3414 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3415 if (noteTableView.isVisible())
3416 noteTableView.hide();
3418 noteTableView.show();
3419 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3421 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3422 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3424 // Handle the event that a user selects a note from the table
3425 @SuppressWarnings("unused")
3426 private void noteTableSelection() {
3427 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3429 if (historyGuids.size() == 0) {
3430 historyGuids.add(currentNoteGuid);
3431 historyPosition = 1;
3433 noteTableView.showColumn(Global.noteTableGuidPosition);
3435 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3436 if (!Global.isColumnVisible("guid"))
3437 noteTableView.hideColumn(Global.noteTableGuidPosition);
3439 if (selections.size() > 0) {
3441 menuBar.noteDuplicateAction.setEnabled(true);
3442 menuBar.noteOnlineHistoryAction.setEnabled(true);
3443 menuBar.noteMergeAction.setEnabled(true);
3444 selectedNoteGUIDs.clear();
3445 if (selections.size() != 1 || Global.showDeleted) {
3446 menuBar.noteDuplicateAction.setEnabled(false);
3448 if (selections.size() != 1 || !Global.isConnected) {
3449 menuBar.noteOnlineHistoryAction.setEnabled(false);
3451 if (selections.size() == 1) {
3452 menuBar.noteMergeAction.setEnabled(false);
3454 for (int i=0; i<selections.size(); i++) {
3455 int row = selections.get(i).row();
3457 upButton.setEnabled(false);
3459 upButton.setEnabled(true);
3460 if (row < listManager.getNoteTableModel().rowCount()-1)
3461 downButton.setEnabled(true);
3463 downButton.setEnabled(false);
3464 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3465 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3466 currentNoteGuid = (String)ix.values().toArray()[0];
3467 selectedNoteGUIDs.add(currentNoteGuid);
3471 nextButton.setEnabled(true);
3472 prevButton.setEnabled(true);
3474 int endPosition = historyGuids.size()-1;
3475 for (int j=historyPosition; j<=endPosition; j++) {
3476 historyGuids.remove(historyGuids.size()-1);
3478 historyGuids.add(currentNoteGuid);
3479 historyPosition = historyGuids.size();
3481 if (historyPosition <= 1)
3482 prevButton.setEnabled(false);
3483 if (historyPosition == historyGuids.size())
3484 nextButton.setEnabled(false);
3486 fromHistory = false;
3487 scrollToGuid(currentNoteGuid);
3488 refreshEvernoteNote(true);
3489 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3491 // Trigger a refresh when the note db has been updated
3492 private void noteIndexUpdated(boolean reload) {
3493 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3495 refreshEvernoteNoteList();
3496 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3497 noteTableView.load(reload);
3498 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3500 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3501 pos = noteTableView.proxyModel.rowCount();
3504 if (noteTableView.proxyModel.rowCount() == 0)
3507 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3509 currentNoteGuid = (String)i.data();
3513 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3515 scrollToGuid(currentNoteGuid);
3516 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3518 // Called when the list of notes is updated
3519 private void refreshEvernoteNoteList() {
3520 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3521 browserWindow.setDisabled(false);
3522 if (selectedNoteGUIDs == null)
3523 selectedNoteGUIDs = new ArrayList<String>();
3524 selectedNoteGUIDs.clear(); // clear out old entries
3526 String saveCurrentNoteGuid = new String();
3527 String tempNoteGuid = new String();
3529 historyGuids.clear();
3530 historyPosition = 0;
3531 prevButton.setEnabled(false);
3532 nextButton.setEnabled(false);
3534 if (currentNoteGuid == null)
3535 currentNoteGuid = new String();
3537 //determine current note guid
3538 for (Note note : listManager.getNoteIndex()) {
3539 tempNoteGuid = note.getGuid();
3540 if (currentNoteGuid.equals(tempNoteGuid)) {
3541 saveCurrentNoteGuid = tempNoteGuid;
3545 if (listManager.getNoteIndex().size() == 0) {
3546 currentNoteGuid = "";
3548 browserWindow.clear();
3549 browserWindow.setDisabled(true);
3552 if (!saveCurrentNoteGuid.equals("")) {
3553 refreshEvernoteNote(false);
3555 currentNoteGuid = "";
3557 reloadTagTree(false);
3559 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3561 // Called when the previous arrow button is clicked
3562 @SuppressWarnings("unused")
3563 private void previousViewedAction() {
3564 if (!prevButton.isEnabled())
3566 if (historyPosition == 0)
3569 if (historyPosition <= 0)
3571 String historyGuid = historyGuids.get(historyPosition-1);
3573 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3574 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3575 if (modelIndex != null) {
3576 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3577 String tableGuid = (String)ix.values().toArray()[0];
3578 if (tableGuid.equals(historyGuid)) {
3579 noteTableView.selectRow(i);
3585 @SuppressWarnings("unused")
3586 private void nextViewedAction() {
3587 if (!nextButton.isEnabled())
3589 String historyGuid = historyGuids.get(historyPosition);
3592 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3593 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3594 if (modelIndex != null) {
3595 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3596 String tableGuid = (String)ix.values().toArray()[0];
3597 if (tableGuid.equals(historyGuid)) {
3598 noteTableView.selectRow(i);
3604 // Called when the up arrow is clicked
3605 @SuppressWarnings("unused")
3606 private void upAction() {
3607 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3608 int row = selections.get(0).row();
3610 noteTableView.selectRow(row-1);
3613 // Called when the down arrow is clicked
3614 @SuppressWarnings("unused")
3615 private void downAction() {
3616 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3617 int row = selections.get(0).row();
3618 int max = listManager.getNoteTableModel().rowCount();
3620 noteTableView.selectRow(row+1);
3623 // Update a tag string for a specific note in the list
3624 @SuppressWarnings("unused")
3625 private void updateListTags(String guid, List<String> tags) {
3626 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3627 StringBuffer tagBuffer = new StringBuffer();
3628 for (int i=0; i<tags.size(); i++) {
3629 tagBuffer.append(tags.get(i));
3630 if (i<tags.size()-1)
3631 tagBuffer.append(", ");
3634 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3635 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3636 if (modelIndex != null) {
3637 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3638 String tableGuid = (String)ix.values().toArray()[0];
3639 if (tableGuid.equals(guid)) {
3640 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3641 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3642 noteTableView.proxyModel.invalidate();
3647 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3649 // Update a title for a specific note in the list
3650 @SuppressWarnings("unused")
3651 private void updateListAuthor(String guid, String author) {
3652 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3654 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3655 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3656 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3657 if (modelIndex != null) {
3658 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3659 String tableGuid = (String)ix.values().toArray()[0];
3660 if (tableGuid.equals(guid)) {
3661 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3662 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3663 noteTableView.proxyModel.invalidate();
3669 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3671 private void updateListNoteNotebook(String guid, String notebook) {
3672 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3673 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3674 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3676 // Update a title for a specific note in the list
3677 @SuppressWarnings("unused")
3678 private void updateListSourceUrl(String guid, String url) {
3679 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3681 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3682 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3683 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3684 if (modelIndex != null) {
3685 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3686 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3687 String tableGuid = (String)ix.values().toArray()[0];
3688 if (tableGuid.equals(guid)) {
3689 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3690 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3691 noteTableView.proxyModel.invalidate();
3696 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3698 @SuppressWarnings("unused")
3699 private void updateListGuid(String oldGuid, String newGuid) {
3700 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3702 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3703 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3704 if (modelIndex != null) {
3705 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3706 String tableGuid = (String)ix.values().toArray()[0];
3707 if (tableGuid.equals(oldGuid)) {
3708 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3709 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3714 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3716 private void updateListTagName(String guid) {
3717 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3719 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3720 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3721 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3723 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3724 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3725 if (modelIndex != null) {
3726 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3727 String noteGuid = (String)ix.values().toArray()[0];
3728 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3729 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3730 i=listManager.getNoteTableModel().rowCount();
3736 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3738 private void removeListTagName(String guid) {
3739 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3741 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3742 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3743 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3744 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3745 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3748 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3749 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3750 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3751 if (modelIndex != null) {
3752 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3753 String noteGuid = (String)ix.values().toArray()[0];
3754 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3755 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3756 i=listManager.getNoteTableModel().rowCount();
3762 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3764 private void updateListNotebookName(String oldName, String newName) {
3765 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3767 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3768 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3769 if (modelIndex != null) {
3770 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3771 String tableName = (String)ix.values().toArray()[0];
3772 if (tableName.equalsIgnoreCase(oldName)) {
3773 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3777 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3779 @SuppressWarnings("unused")
3780 private void updateListDateCreated(String guid, QDateTime date) {
3781 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3783 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3784 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3785 if (modelIndex != null) {
3786 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3787 String tableGuid = (String)ix.values().toArray()[0];
3788 if (tableGuid.equals(guid)) {
3789 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3790 noteTableView.proxyModel.invalidate();
3795 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3797 @SuppressWarnings("unused")
3798 private void updateListDateSubject(String guid, QDateTime date) {
3799 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3801 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3802 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3803 if (modelIndex != null) {
3804 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3805 String tableGuid = (String)ix.values().toArray()[0];
3806 if (tableGuid.equals(guid)) {
3807 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3808 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3809 noteTableView.proxyModel.invalidate();
3814 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3816 private void updateListDateChanged(String guid, QDateTime date) {
3817 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3819 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3820 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3821 if (modelIndex != null) {
3822 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3823 String tableGuid = (String)ix.values().toArray()[0];
3824 if (tableGuid.equals(guid)) {
3825 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3826 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3831 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3833 private void updateListDateChanged() {
3834 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3835 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3836 updateListDateChanged(currentNoteGuid, date);
3837 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3840 private void scrollToCurrentGuid() {
3841 //scrollToGuid(currentNoteGuid);
3842 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3843 if (selections.size() == 0)
3845 QModelIndex index = selections.get(0);
3846 int row = selections.get(0).row();
3847 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3850 // Scroll to the current GUID in tthe list.
3851 // Scroll to a particular index item
3852 private void scrollToGuid(String guid) {
3853 if (currentNote == null || guid == null)
3855 if (currentNote.isActive() && Global.showDeleted) {
3856 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3857 if (!listManager.getNoteIndex().get(i).isActive()) {
3858 currentNote = listManager.getNoteIndex().get(i);
3859 currentNoteGuid = currentNote.getGuid();
3860 i = listManager.getNoteIndex().size();
3864 if (!currentNote.isActive() && !Global.showDeleted) {
3865 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3866 if (listManager.getNoteIndex().get(i).isActive()) {
3867 currentNote = listManager.getNoteIndex().get(i);
3868 currentNoteGuid = currentNote.getGuid();
3869 i = listManager.getNoteIndex().size();
3874 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3875 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3876 if (currentNoteGuid.equals(index.data())) {
3877 // noteTableView.selectionModel().blockSignals(true);
3878 noteTableView.selectRow(i);
3879 // noteTableView.selectionModel().blockSignals(false);
3880 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3881 i=listManager.getNoteTableModel().rowCount();
3884 noteTableView.repaint();
3886 // Show/Hide columns
3887 private void showColumns() {
3888 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3889 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3890 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3891 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3892 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3893 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3894 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3895 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3896 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3897 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3898 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3900 // Title color has changed
3901 @SuppressWarnings("unused")
3902 private void titleColorChanged(Integer color) {
3903 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3905 QColor backgroundColor = new QColor();
3906 QColor foregroundColor = new QColor(QColor.black);
3907 backgroundColor.setRgb(color);
3909 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3910 foregroundColor.setRgb(QColor.white.rgb());
3912 if (selectedNoteGUIDs.size() == 0)
3913 selectedNoteGUIDs.add(currentNoteGuid);
3915 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3916 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3917 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3918 if (modelIndex != null) {
3919 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3920 String tableGuid = (String)ix.values().toArray()[0];
3921 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3922 for (int k=0; k<Global.noteTableColumnCount; k++) {
3923 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3924 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3925 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3927 i=listManager.getNoteTableModel().rowCount();
3932 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3934 // Wide list was chosen
3935 public void narrowListView() {
3936 saveNoteColumnPositions();
3937 saveNoteIndexWidth();
3939 int sortCol = noteTableView.proxyModel.sortColumn();
3940 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3941 Global.setSortColumn(sortCol);
3942 Global.setSortOrder(sortOrder);
3944 Global.setListView(Global.View_List_Narrow);
3946 menuBar.wideListView.blockSignals(true);
3947 menuBar.narrowListView.blockSignals(true);
3949 menuBar.wideListView.setChecked(false);
3950 menuBar.narrowListView.setChecked(true);
3952 menuBar.wideListView.blockSignals(false);
3953 menuBar.narrowListView.blockSignals(false);
3955 mainLeftRightSplitter.addWidget(noteTableView);
3956 mainLeftRightSplitter.addWidget(browserWindow);
3957 restoreWindowState(false);
3958 noteTableView.repositionColumns();
3959 noteTableView.resizeColumnWidths();
3960 noteTableView.resizeRowHeights();
3962 sortCol = Global.getSortColumn();
3963 sortOrder = Global.getSortOrder();
3964 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3967 noteTableView.load(false);
3968 scrollToCurrentGuid();
3970 public void wideListView() {
3971 int sortCol = noteTableView.proxyModel.sortColumn();
3972 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3973 Global.setSortColumn(sortCol);
3974 Global.setSortOrder(sortOrder);
3977 saveNoteColumnPositions();
3978 saveNoteIndexWidth();
3979 Global.setListView(Global.View_List_Wide);
3981 menuBar.wideListView.blockSignals(true);
3982 menuBar.narrowListView.blockSignals(true);
3984 menuBar.wideListView.setChecked(true);
3985 menuBar.narrowListView.setChecked(false);
3987 menuBar.wideListView.blockSignals(false);
3988 menuBar.narrowListView.blockSignals(false);
3989 browserIndexSplitter.setVisible(true);
3990 browserIndexSplitter.addWidget(noteTableView);
3991 browserIndexSplitter.addWidget(browserWindow);
3992 restoreWindowState(false);
3993 noteTableView.repositionColumns();
3994 noteTableView.resizeColumnWidths();
3995 noteTableView.resizeRowHeights();
3997 sortCol = Global.getSortColumn();
3998 sortOrder = Global.getSortOrder();
3999 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4002 noteTableView.load(false);
4003 scrollToCurrentGuid();
4007 //***************************************************************
4008 //***************************************************************
4009 //** External editor window functions
4010 //***************************************************************
4011 //***************************************************************
4012 private void listDoubleClick() {
4014 if (externalWindows.containsKey(currentNoteGuid)) {
4015 externalWindows.get(currentNoteGuid).raise();
4018 // We have a new external editor to create
4019 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4020 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4021 newBrowser.setWindowIcon(appIcon);
4022 externalWindows.put(currentNoteGuid, newBrowser);
4023 showEditorButtons(newBrowser.getBrowserWindow());
4024 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
4025 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4026 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4027 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4028 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4029 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4031 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4032 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4033 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4037 @SuppressWarnings("unused")
4038 private void externalWindowTitleEdited(String guid, String text) {
4039 if (guid.equals(currentNoteGuid)) {
4040 browserWindow.setTitle(text);
4043 @SuppressWarnings({ "rawtypes", "unused" })
4044 private void externalWindowTagsEdited(String guid, List values) {
4045 StringBuffer line = new StringBuffer(100);
4046 for (int i=0; i<values.size(); i++) {
4048 line.append(Global.tagDelimeter+" ");
4049 line.append(values.get(i));
4051 if (guid.equals(currentNoteGuid)) {
4052 browserWindow.setTag(line.toString());
4055 @SuppressWarnings("unused")
4056 private void externalWindowClosing(String guid) {
4057 externalWindows.remove(guid);
4062 //***************************************************************
4063 //***************************************************************
4064 //** These functions deal with Note specific things
4065 //***************************************************************
4066 //***************************************************************
4067 @SuppressWarnings("unused")
4068 private void setNoteDirty() {
4069 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4071 // Find if the note is being edited externally. If it is, update it.
4072 if (externalWindows.containsKey(currentNoteGuid)) {
4073 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4074 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4075 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4076 window.getBrowserWindow().getBrowser().setContent(unicode);
4079 // If the note is dirty, then it is unsynchronized by default.
4083 // Set the note as dirty and check if its status is synchronized in the display table
4085 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
4086 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
4090 // If this wasn't already marked as unsynchronized, then we need to update the table
4091 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4092 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4093 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4094 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4095 if (modelIndex != null) {
4096 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4097 String tableGuid = (String)ix.values().toArray()[0];
4098 if (tableGuid.equals(currentNoteGuid)) {
4099 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4105 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4107 @SuppressWarnings("unused")
4108 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4109 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4110 QByteArray unicode = codec.fromUnicode(content);
4111 noteCache.remove(guid);
4112 noteCache.put(guid, unicode.toString());
4113 if (guid.equals(currentNoteGuid)) {
4115 browserWindow.getBrowser().setContent(unicode);
4118 thumbnailRunner.addWork("GENERATE "+ guid);
4119 saveNote(guid, browser);
4123 private void saveNote() {
4125 saveNote(currentNoteGuid, browserWindow);
4126 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4130 private void saveNote(String guid, BrowserWindow window) {
4131 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4132 logger.log(logger.EXTREME, "Note is dirty.");
4135 logger.log(logger.EXTREME, "Saving to cache");
4136 QTextCodec codec = QTextCodec.codecForLocale();
4137 // QTextDecoder decoder = codec.makeDecoder();
4138 codec = QTextCodec.codecForName("UTF-8");
4139 QByteArray unicode = codec.fromUnicode(window.getContent());
4140 noteCache.put(guid, unicode.toString());
4142 logger.log(logger.EXTREME, "updating list manager");
4143 listManager.updateNoteContent(guid, window.getContent());
4144 logger.log(logger.EXTREME, "Updating title");
4145 listManager.updateNoteTitle(guid, window.getTitle());
4146 updateListDateChanged();
4148 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4149 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4150 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4151 currentNote = listManager.getNoteIndex().get(i);
4152 i = listManager.getNoteIndex().size();
4157 // Get a note from Evernote (and put it in the browser)
4158 private void refreshEvernoteNote(boolean reload) {
4159 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4161 if (Global.disableViewing) {
4162 browserWindow.setEnabled(false);
4167 if (Global.showDeleted)
4169 Global.cryptCounter =0;
4170 if (currentNoteGuid.equals("")) {
4171 browserWindow.setReadOnly(true);
4179 browserWindow.loadingData(true);
4181 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4182 if (currentNote == null)
4184 loadNoteBrowserInformation(browserWindow);
4187 private void loadNoteBrowserInformation(BrowserWindow browser) {
4188 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4189 formatter.setNote(currentNote, Global.pdfPreview());
4190 formatter.setHighlight(listManager.getEnSearch());
4192 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4193 js = new QByteArray();
4194 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4195 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4196 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>");
4197 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4198 js.append("<style> img { max-width:100%; }</style>");
4199 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4200 js.append("</head>");
4201 formatter.setNote(currentNote, Global.pdfPreview());
4202 js.append(formatter.rebuildNoteHTML());
4203 js.append("</HTML>");
4204 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4205 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4206 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4207 browser.getBrowser().setContent(js);
4208 noteCache.put(currentNoteGuid, js.toString());
4210 if (formatter.resourceError)
4211 resourceErrorMessage();
4212 readOnly = formatter.readOnly;
4213 inkNote = formatter.inkNote;
4215 readOnlyCache.put(currentNoteGuid, true);
4217 inkNoteCache.put(currentNoteGuid, true);
4219 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4220 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4221 js = new QByteArray(cachedContent);
4222 browser.getBrowser().setContent(js);
4223 if (readOnlyCache.containsKey(currentNoteGuid))
4225 if (inkNoteCache.containsKey(currentNoteGuid))
4228 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4229 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4231 if (readOnly || inkNote)
4232 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4234 browser.getBrowser().page().setContentEditable(true);
4235 browser.setReadOnly(readOnly);
4236 deleteButton.setEnabled(!readOnly);
4237 tagButton.setEnabled(!readOnly);
4238 menuBar.noteDelete.setEnabled(!readOnly);
4239 menuBar.noteTags.setEnabled(!readOnly);
4240 browser.setNote(currentNote);
4242 if (currentNote != null && currentNote.getNotebookGuid() != null &&
4243 conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4244 deleteButton.setEnabled(false);
4245 menuBar.notebookDeleteAction.setEnabled(false);
4247 deleteButton.setEnabled(true);
4248 menuBar.notebookDeleteAction.setEnabled(true);
4251 // Build a list of non-closed notebooks
4252 List<Notebook> nbooks = new ArrayList<Notebook>();
4253 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4254 boolean found=false;
4255 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4256 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4260 nbooks.add(listManager.getNotebookIndex().get(i));
4263 browser.setTitle(currentNote.getTitle());
4264 browser.setTag(getTagNamesForNote(currentNote));
4265 browser.setAuthor(currentNote.getAttributes().getAuthor());
4267 browser.setAltered(currentNote.getUpdated());
4268 browser.setCreation(currentNote.getCreated());
4269 if (currentNote.getAttributes().getSubjectDate() > 0)
4270 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4272 browser.setSubjectDate(currentNote.getCreated());
4273 browser.setUrl(currentNote.getAttributes().getSourceURL());
4275 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4276 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4277 browser.setAllTags(tagList);
4279 browser.setCurrentTags(currentNote.getTagNames());
4281 scrollToGuid(currentNoteGuid);
4283 browser.loadingData(false);
4284 if (thumbnailViewer.isActiveWindow())
4287 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4288 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4291 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4293 // Save a generated thumbnail
4294 private void toggleNoteInformation() {
4295 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4296 browserWindow.toggleInformation();
4297 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4298 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4299 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4301 // Listener triggered when a print button is pressed
4302 @SuppressWarnings("unused")
4303 private void printNote() {
4304 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4306 QPrintDialog dialog = new QPrintDialog();
4307 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4308 QPrinter printer = dialog.printer();
4309 browserWindow.getBrowser().print(printer);
4311 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4314 // Listener triggered when the email button is pressed
4315 @SuppressWarnings("unused")
4316 private void emailNote() {
4317 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4319 if (Desktop.isDesktopSupported()) {
4320 Desktop desktop = Desktop.getDesktop();
4322 String text2 = browserWindow.getContentsToEmail();
4323 QUrl url = new QUrl("mailto:");
4324 url.addQueryItem("subject", currentNote.getTitle());
4325 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4326 url.addQueryItem("body", text2);
4327 QDesktopServices.openUrl(url);
4331 if (desktop.isSupported(Desktop.Action.MAIL)) {
4332 URI uriMailTo = null;
4334 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4335 String text = browserWindow.getContentsToEmail();
4336 //text = "<b>" +text +"</b>";
4337 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4338 +"&BODY=" +text, null);
4339 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4340 +"&ATTACHMENT=d:/test.pdf", null);
4341 desktop.mail(uriMailTo);
4342 } catch (URISyntaxException e) {
4343 e.printStackTrace();
4344 } catch (IOException e) {
4345 e.printStackTrace();
4352 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4354 // Reindex all notes
4355 @SuppressWarnings("unused")
4356 private void fullReindex() {
4357 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4358 indexRunner.addWork("REINDEXALL");
4359 setMessage(tr("Database will be reindexed."));
4360 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4362 // Listener when a user wants to reindex a specific note
4363 @SuppressWarnings("unused")
4364 private void reindexNote() {
4365 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4366 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4367 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4369 if (selectedNotebookGUIDs.size() > 1)
4370 setMessage(tr("Notes will be reindexed."));
4372 setMessage(tr("Note will be reindexed."));
4373 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4376 @SuppressWarnings("unused")
4377 private void deleteNote() {
4378 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4379 if (currentNote == null)
4381 if (currentNoteGuid.equals(""))
4383 String title = null;
4384 if (selectedNoteGUIDs.size() == 1)
4385 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4387 // If we are deleting non-trash notes
4388 if (currentNote.isActive()) {
4389 if (Global.verifyDelete()) {
4391 if (selectedNoteGUIDs.size() > 1) {
4392 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4395 msg = new String(tr("Delete note \"") +title +"\"?");
4397 msg = new String(tr("Delete note selected note?"));
4399 if (QMessageBox.question(this, tr("Confirmation"), msg,
4400 QMessageBox.StandardButton.Yes,
4401 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4405 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4406 selectedNoteGUIDs.add(currentNoteGuid);
4407 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4408 listManager.deleteNote(selectedNoteGUIDs.get(i));
4411 // If we are deleting from the trash.
4412 if (Global.verifyDelete()) {
4414 if (selectedNoteGUIDs.size() > 1) {
4415 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4418 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4420 msg = new String(tr("Permanently delete note selected note?"));
4422 if (QMessageBox.question(this, "Confirmation", msg,
4423 QMessageBox.StandardButton.Yes,
4424 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4428 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4429 selectedNoteGUIDs.add(currentNoteGuid);
4430 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4431 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4432 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4433 if (modelIndex != null) {
4434 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4435 String tableGuid = (String)ix.values().toArray()[0];
4436 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4437 listManager.getNoteTableModel().removeRow(j);
4442 listManager.expungeNote(selectedNoteGUIDs.get(i));
4445 currentNoteGuid = "";
4446 listManager.loadNotesIndex();
4447 noteIndexUpdated(false);
4448 refreshEvernoteNote(true);
4449 scrollToGuid(currentNoteGuid);
4450 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4453 @SuppressWarnings("unused")
4454 private void addNote() {
4455 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4456 // browserWindow.setEnabled(true);
4457 browserWindow.setReadOnly(false);
4459 Calendar currentTime = new GregorianCalendar();
4460 StringBuffer noteString = new StringBuffer(100);
4461 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4462 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4465 if (Global.overrideDefaultFont()) {
4466 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4467 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4468 noteString.append("<br clear=\"none\" />\n");
4469 noteString.append("</span>\n</font>\n");
4471 noteString.append("<br clear=\"none\" />\n");
4472 noteString.append("</en-note>");
4474 Long l = new Long(currentTime.getTimeInMillis());
4475 String randint = new String(Long.toString(l));
4477 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4479 // for the first non-archived notebook. Finally, if nothing else we
4480 // pick the first notebook in the list.
4481 String notebook = null;
4482 listManager.getNotebookIndex().get(0).getGuid();
4483 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4484 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4485 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4486 notebook = currentSelectedNotebook.text(2);
4488 boolean found = false;
4489 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4490 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4491 boolean match = false;
4492 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4493 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4495 j = listManager.getArchiveNotebookIndex().size();
4499 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4500 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4502 // Now we have a list of good notebooks, so we can look for the default
4504 for (int i=0; i<goodNotebooks.size(); i++) {
4505 if (goodNotebooks.get(i).isDefaultNotebook()) {
4506 notebook = goodNotebooks.get(i).getGuid();
4508 i = goodNotebooks.size();
4512 if (goodNotebooks.size() > 0 && !found)
4513 notebook = goodNotebooks.get(0).getGuid();
4516 notebook = listManager.getNotebookIndex().get(0).getGuid();
4519 Note newNote = new Note();
4520 newNote.setUpdateSequenceNum(0);
4521 newNote.setGuid(randint);
4522 newNote.setNotebookGuid(notebook);
4523 newNote.setTitle("");
4524 newNote.setContent(noteString.toString());
4525 newNote.setDeleted(0);
4526 newNote.setCreated(System.currentTimeMillis());
4527 newNote.setUpdated(System.currentTimeMillis());
4528 newNote.setActive(true);
4529 NoteAttributes na = new NoteAttributes();
4530 na.setLatitude(0.0);
4531 na.setLongitude(0.0);
4532 na.setAltitude(0.0);
4533 newNote.setAttributes(new NoteAttributes());
4534 newNote.setTagGuids(new ArrayList<String>());
4535 newNote.setTagNames(new ArrayList<String>());
4537 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4538 if (Global.newNoteWithSelectedTags()) {
4539 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4540 QTreeWidgetItem currentSelection;
4541 for (int i=0; i<selections.size(); i++) {
4542 currentSelection = selections.get(i);
4543 newNote.getTagGuids().add(currentSelection.text(2));
4544 newNote.getTagNames().add(currentSelection.text(0));
4548 conn.getNoteTable().addNote(newNote, true);
4549 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4550 listManager.addNote(newNote);
4551 // noteTableView.insertRow(newNote, true, -1);
4553 currentNote = newNote;
4554 currentNoteGuid = currentNote.getGuid();
4555 noteTableView.clearSelection();
4556 refreshEvernoteNote(true);
4557 listManager.countNotebookResults(listManager.getNoteIndex());
4558 browserWindow.titleLabel.setFocus();
4559 browserWindow.titleLabel.selectAll();
4560 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4562 // If the window is hidden, then we want to popup this in an external window &
4565 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4567 // Restore a note from the trash;
4568 @SuppressWarnings("unused")
4569 private void restoreNote() {
4571 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4572 selectedNoteGUIDs.add(currentNoteGuid);
4573 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4574 listManager.restoreNote(selectedNoteGUIDs.get(i));
4576 currentNoteGuid = "";
4577 listManager.loadNotesIndex();
4578 noteIndexUpdated(false);
4581 // Search a note for specific txt
4582 @SuppressWarnings("unused")
4583 private void findText() {
4585 find.setFocusOnTextField();
4587 @SuppressWarnings("unused")
4588 private void doFindText() {
4589 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4592 @SuppressWarnings("unused")
4593 private void updateNoteTitle(String guid, String title) {
4594 listManager.setNoteSynchronized(guid, false);
4596 // Signal received that note content has changed. Normally we just need the guid to remove
4597 // it from the cache.
4598 @SuppressWarnings("unused")
4599 private void invalidateNoteCache(String guid, String content) {
4600 String v = noteCache.remove(guid);
4601 // if (guid.equals(currentNoteGuid) && !noteDirty)
4602 refreshEvernoteNote(true);
4604 // Signal received that a note guid has changed
4605 @SuppressWarnings("unused")
4606 private void noteGuidChanged(String oldGuid, String newGuid) {
4607 if (noteCache.containsKey(oldGuid)) {
4608 if (!oldGuid.equals(currentNoteGuid)) {
4609 String cache = noteCache.get(oldGuid);
4610 noteCache.put(newGuid, cache);
4611 noteCache.remove(oldGuid);
4613 noteCache.remove(oldGuid);
4614 noteCache.put(newGuid, browserWindow.getContent());
4618 listManager.updateNoteGuid(oldGuid, newGuid, false);
4619 if (currentNoteGuid.equals(oldGuid)) {
4620 if (currentNote != null)
4621 currentNote.setGuid(newGuid);
4622 currentNoteGuid = newGuid;
4625 if (externalWindows.containsKey(oldGuid)) {
4626 ExternalBrowse b = externalWindows.get(oldGuid);
4627 externalWindows.remove(oldGuid);
4628 b.getBrowserWindow().getNote().setGuid(newGuid);
4629 externalWindows.put(newGuid, b);
4632 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4633 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4634 noteTableView.proxyModel.addGuid(newGuid);
4635 i=listManager.getNoteIndex().size();
4639 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4640 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4641 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4642 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4646 // Toggle the note editor button bar
4647 private void toggleEditorButtonBar() {
4648 if (browserWindow.buttonsVisible) {
4649 browserWindow.hideButtons();
4650 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4651 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4653 browserWindow.buttonsVisible = true;
4654 showEditorButtons(browserWindow);
4656 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4658 // Show editor buttons
4659 private void showEditorButtons(BrowserWindow browser) {
4660 browser.buttonLayout.setVisible(true);
4661 browser.undoAction.setVisible(false);
4663 browser.undoButton.setVisible(false);
4665 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4666 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4667 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4668 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4669 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4670 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4671 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4672 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4673 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4674 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4675 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4676 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4677 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4678 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4679 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4680 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4681 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4682 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4683 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4684 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4685 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4686 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4687 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4689 private void duplicateNote(String guid) {
4691 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4692 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4693 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4694 oldNote.setResources(resList);
4695 duplicateNote(oldNote);
4697 private void duplicateNote(Note oldNote) {
4699 // Now that we have a good notebook guid, we need to move the conflicting note
4700 // to the local notebook
4701 Calendar currentTime = new GregorianCalendar();
4702 Long l = new Long(currentTime.getTimeInMillis());
4703 String newGuid = new String(Long.toString(l));
4705 // Note newNote = oldNote.deepCopy();
4706 Note newNote = (Note)Global.deepCopy(oldNote);
4707 newNote.setUpdateSequenceNum(0);
4708 newNote.setGuid(newGuid);
4709 newNote.setDeleted(0);
4710 newNote.setActive(true);
4713 List<String> tagNames = new ArrayList<String>();
4714 List<String> tagGuids = new ArrayList<String>();;
4715 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4716 tagNames.add(oldNote.getTagNames().get(i));
4717 tagGuids.add(oldNote.getTagGuids().get(i));
4720 // Sort note Tags to make them look nice
4721 for (int i=0; i<tagNames.size()-1; i++) {
4722 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4723 String n1 = tagNames.get(i);
4724 String n2 = tagNames.get(i+1);
4725 tagNames.set(i, n2);
4726 tagNames.set(i+1, n1);
4729 newNote.setTagGuids(tagGuids);
4730 newNote.setTagNames(tagNames);
4732 // Add tag guids to note
4735 // Duplicate resources
4736 List<Resource> resList = oldNote.getResources();
4737 if (resList == null)
4738 resList = new ArrayList<Resource>();
4740 for (int i=0; i<resList.size(); i++) {
4742 while (l == prevGuid) {
4743 currentTime = new GregorianCalendar();
4744 l = new Long(currentTime.getTimeInMillis());
4747 String newResGuid = new String(Long.toString(l));
4748 resList.get(i).setNoteGuid(newGuid);
4749 resList.get(i).setGuid(newResGuid);
4750 resList.get(i).setUpdateSequenceNum(0);
4751 resList.get(i).setActive(true);
4752 conn.getNoteTable().noteResourceTable.saveNoteResource(
4753 (Resource)Global.deepCopy(resList.get(i)), true);
4755 newNote.setResources(resList);
4757 // Add note to the database
4758 listManager.addNote(newNote);
4759 conn.getNoteTable().addNote(newNote, true);
4760 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4761 noteTableView.insertRow(newNote, true, -1);
4762 currentNoteGuid = newNote.getGuid();
4763 currentNote = newNote;
4764 refreshEvernoteNote(true);
4765 listManager.countNotebookResults(listManager.getNoteIndex());
4769 @SuppressWarnings("unused")
4770 private void allNotes() {
4771 clearAttributeFilter();
4772 clearNotebookFilter();
4773 clearSavedSearchFilter();
4776 searchField.clear();
4777 if (Global.mimicEvernoteInterface) {
4778 notebookTree.selectGuid("");
4780 notebookTreeSelection();
4783 @SuppressWarnings("unused")
4784 private void mergeNotes() {
4785 logger.log(logger.HIGH, "Merging notes");
4788 String masterGuid = null;
4789 List<String> sources = new ArrayList<String>();
4791 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4792 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4793 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4794 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4796 masterGuid = (String)ix.values().toArray()[0];
4798 sources.add((String)ix.values().toArray()[0]);
4801 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4802 logger.log(logger.EXTREME, "Children count: "+sources.size());
4803 mergeNoteContents(masterGuid, sources);
4804 currentNoteGuid = masterGuid;
4805 noteIndexUpdated(false);
4806 refreshEvernoteNote(true);
4809 private void mergeNoteContents(String targetGuid, List<String> sources) {
4810 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4811 String newContent = target.getContent();
4812 newContent = newContent.replace("</en-note>", "<br></br>");
4814 for (int i=0; i<sources.size(); i++) {
4815 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4816 if (source.isSetTitle()) {
4817 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4819 String sourceContent = source.getContent();
4820 logger.log(logger.EXTREME, "Merging contents into note");
4821 logger.log(logger.EXTREME, sourceContent);
4822 logger.log(logger.EXTREME, "End of content");
4823 int startOfNote = sourceContent.indexOf("<en-note>");
4824 sourceContent = sourceContent.substring(startOfNote+9);
4825 int endOfNote = sourceContent.indexOf("</en-note>");
4826 sourceContent = sourceContent.substring(0,endOfNote);
4827 newContent = newContent + sourceContent;
4828 logger.log(logger.EXTREME, "New note content");
4829 logger.log(logger.EXTREME, newContent);
4830 logger.log(logger.EXTREME, "End of content");
4831 for (int j=0; j<source.getResourcesSize(); j++) {
4832 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4833 Resource r = source.getResources().get(j);
4834 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4836 Calendar currentTime = new GregorianCalendar();
4837 Long l = new Long(currentTime.getTimeInMillis());
4841 while (l == prevGuid) {
4842 currentTime = new GregorianCalendar();
4843 l = new Long(currentTime.getTimeInMillis());
4845 String newResGuid = new String(Long.toString(l));
4846 newRes.setNoteGuid(targetGuid);
4847 newRes.setGuid(newResGuid);
4848 newRes.setUpdateSequenceNum(0);
4849 newRes.setActive(true);
4850 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4853 logger.log(logger.EXTREME, "Updating note");
4854 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4855 for (int i=0; i<sources.size(); i++) {
4856 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4857 listManager.deleteNote(sources.get(i));
4859 logger.log(logger.EXTREME, "Exiting merge note");
4861 // A resource within a note has had a guid change
4862 @SuppressWarnings("unused")
4863 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4864 if (!oldGuid.equals(newGuid))
4865 Global.resourceMap.put(oldGuid, newGuid);
4867 // View a thumbnail of the note
4868 public void thumbnailView() {
4870 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4871 QFile thumbnail = new QFile(thumbnailName);
4872 if (!thumbnail.exists()) {
4874 QImage img = new QImage();
4875 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4876 thumbnailViewer.setThumbnail(img);
4878 thumbnailViewer.setThumbnail(thumbnailName);
4879 if (!thumbnailViewer.isVisible())
4880 thumbnailViewer.showFullScreen();
4882 // An error happened while saving a note. Inform the user
4883 @SuppressWarnings("unused")
4884 private void saveRunnerError(String guid, String msg) {
4886 String title = "*Unknown*";
4887 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4888 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4889 title = listManager.getMasterNoteIndex().get(i).getTitle();
4890 i=listManager.getMasterNoteIndex().size();
4893 msg = "An error has happened while saving the note \"" +title+
4894 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4895 "As a result, changes to the note may not be saved properly in the database."+
4896 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4897 "\nbe lost. Please review the note to recover any critical data before restarting.";
4899 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4902 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4903 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4904 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4905 // Find an idle preview object
4906 for (int i=0; i<thumbGenerators.size(); i++) {
4907 if (thumbGenerators.get(i).mutex.tryLock()) {
4908 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4909 thumbGenerators.get(i).loadContent(guid, html, zoom);
4913 if (thumbGenerators.size() >= 1) {
4914 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4918 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4919 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4920 thumbGenerators.add(preview);
4922 if (preview.mutex.tryLock()) {
4923 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4924 preview.loadContent(guid, html, zoom);
4926 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4931 //**********************************************************
4932 //**********************************************************
4933 //* Online user actions
4934 //**********************************************************
4935 //**********************************************************
4936 private void setupOnlineMenu() {
4937 if (!Global.isConnected) {
4938 menuBar.noteOnlineHistoryAction.setEnabled(false);
4939 menuBar.selectiveSyncAction.setEnabled(false);
4942 menuBar.noteOnlineHistoryAction.setEnabled(true);
4943 menuBar.selectiveSyncAction.setEnabled(true);
4946 @SuppressWarnings("unused")
4947 private void viewNoteHistory() {
4948 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4950 if (currentNote.getUpdateSequenceNum() == 0) {
4951 setMessage(tr("Note has never been synchronized."));
4952 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4956 setMessage(tr("Getting Note History"));
4958 Note currentOnlineNote = null;
4961 if (Global.isPremium())
4962 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4964 versions = new ArrayList<NoteVersionId>();
4965 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4966 } catch (EDAMUserException e) {
4967 setMessage("EDAMUserException: " +e.getMessage());
4969 } catch (EDAMSystemException e) {
4970 setMessage("EDAMSystemException: " +e.getMessage());
4972 } catch (EDAMNotFoundException e) {
4973 setMessage(tr("Note not found on server."));
4974 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
4976 } catch (TException e) {
4977 setMessage("EDAMTransactionException: " +e.getMessage());
4981 // If we've gotten this far, we have a good note.
4982 if (historyWindow == null) {
4983 historyWindow = new OnlineNoteHistory(logger, conn);
4984 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
4985 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
4986 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
4988 historyWindow.historyCombo.clear();
4990 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
4991 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
4993 historyWindow.setCurrent(isDirty);
4995 loadHistoryWindowContent(currentOnlineNote);
4996 historyWindow.load(versions);
4997 setMessage(tr("History retrieved"));
4999 historyWindow.exec();
5001 private Note reloadHistoryWindow(String selection) {
5003 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5004 String dateTimeFormat = new String(fmt);
5005 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5009 for (int i=0; i<versions.size(); i++) {
5010 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5011 if (versionDate.toString().equals(selection))
5015 if (index > -1 || selection.indexOf("Current") > -1) {
5016 Note historyNote = null;
5019 usn = versions.get(index).getUpdateSequenceNum();
5020 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5022 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5023 } catch (EDAMUserException e) {
5024 setMessage("EDAMUserException: " +e.getMessage());
5027 } catch (EDAMSystemException e) {
5028 setMessage("EDAMSystemException: " +e.getMessage());
5031 } catch (EDAMNotFoundException e) {
5032 setMessage("EDAMNotFoundException: " +e.getMessage());
5035 } catch (TException e) {
5036 setMessage("EDAMTransactionException: " +e.getMessage());
5042 if (historyNote != null)
5043 historyWindow.setContent(historyNote);
5049 private void loadHistoryWindowContent(Note note) {
5050 note.setUpdateSequenceNum(0);
5051 historyWindow.setContent(note);
5053 @SuppressWarnings("unused")
5054 private void restoreHistoryNoteAsNew() {
5055 setMessage(tr("Restoring as new note."));
5056 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5057 setMessage(tr("Note has been restored as a new note."));
5059 @SuppressWarnings("unused")
5060 private void restoreHistoryNote() {
5061 setMessage(tr("Restoring note."));
5062 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5063 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5066 for (int i=0; i<n.getResourcesSize(); i++) {
5067 n.getResources().get(i).setActive(true);
5068 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5070 listManager.addNote(n);
5071 conn.getNoteTable().addNote(n, true);
5072 refreshEvernoteNote(true);
5073 setMessage(tr("Note has been restored."));
5075 @SuppressWarnings("unused")
5076 private void setupSelectiveSync() {
5078 // Get a list of valid notebooks
5079 List<Notebook> notebooks = null;
5080 List<Tag> tags = null;
5081 List<LinkedNotebook> linkedNotebooks = null;
5083 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5084 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5085 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5086 } catch (EDAMUserException e) {
5087 setMessage("EDAMUserException: " +e.getMessage());
5089 } catch (EDAMSystemException e) {
5090 setMessage("EDAMSystemException: " +e.getMessage());
5092 } catch (TException e) {
5093 setMessage("EDAMTransactionException: " +e.getMessage());
5095 } catch (EDAMNotFoundException e) {
5096 setMessage("EDAMNotFoundException: " +e.getMessage());
5100 // Split up notebooks into synchronized & non-synchronized
5101 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5102 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5104 for (int i=notebooks.size()-1; i>=0; i--) {
5105 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5106 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5107 ignoredBooks.add(notebooks.get(i));
5108 j=dbIgnoredNotebooks.size();
5113 // split up tags into synchronized & non-synchronized
5114 List<Tag> ignoredTags = new ArrayList<Tag>();
5115 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5117 for (int i=tags.size()-1; i>=0; i--) {
5118 for (int j=0; j<dbIgnoredTags.size(); j++) {
5119 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5120 ignoredTags.add(tags.get(i));
5121 j=dbIgnoredTags.size();
5126 // split up linked notebooks into synchronized & non-synchronized
5127 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5128 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5129 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5130 String notebookGuid = linkedNotebooks.get(i).getGuid();
5131 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5132 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5133 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5134 j=dbIgnoredLinkedNotebooks.size();
5139 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5141 if (!ignore.okClicked())
5146 // Clear out old notebooks & add the new ones
5147 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5148 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5149 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5152 List<String> newNotebooks = new ArrayList<String>();
5153 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5154 String text = ignore.getIgnoredBookList().takeItem(i).text();
5155 for (int j=0; j<notebooks.size(); j++) {
5156 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5157 Notebook n = notebooks.get(j);
5158 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5160 newNotebooks.add(n.getGuid());
5165 // Clear out old tags & add new ones
5166 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5167 for (int i=0; i<oldIgnoreTags.size(); i++) {
5168 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5171 List<String> newTags = new ArrayList<String>();
5172 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5173 String text = ignore.getIgnoredTagList().takeItem(i).text();
5174 for (int j=0; j<tags.size(); j++) {
5175 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5176 Tag t = tags.get(j);
5177 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5178 newTags.add(t.getGuid());
5184 // Clear out old tags & add new ones
5185 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5186 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5187 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5190 List<String> newLinked = new ArrayList<String>();
5191 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5192 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5193 for (int j=0; j<linkedNotebooks.size(); j++) {
5194 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5195 LinkedNotebook t = linkedNotebooks.get(j);
5196 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5197 newLinked.add(t.getGuid());
5198 j=linkedNotebooks.size();
5203 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5209 //**********************************************************
5210 //**********************************************************
5211 //* XML Modifying methods
5212 //**********************************************************
5213 //**********************************************************
5214 // An error has happended fetching a resource. let the user know
5215 private void resourceErrorMessage() {
5218 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5219 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5220 "In a perfect world this wouldn't happen, but it has.\n" +
5221 "It is embarasing when a program like me, designed to save all your\n"+
5222 "precious data, has a problem finding data.\n\n" +
5223 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5224 "In the mean time, I'm not going to let you make changes to this note.\n" +
5225 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5226 "this note on the Evernote servers. Sorry."+
5227 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5229 browserWindow.setReadOnly(true);
5235 //**********************************************************
5236 //**********************************************************
5238 //**********************************************************
5239 //**********************************************************
5240 // We should now do a sync with Evernote
5241 private void syncTimer() {
5242 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5243 syncRunner.syncNeeded = true;
5244 syncRunner.disableUploads = Global.disableUploads;
5246 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5248 private void syncStart() {
5249 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5251 if (!syncRunning && Global.isConnected) {
5252 syncRunner.setConnected(true);
5253 syncRunner.setKeepRunning(Global.keepRunning);
5254 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5256 if (syncThreadsReady > 0) {
5257 thumbnailRunner.interrupt = true;
5258 saveNoteIndexWidth();
5259 saveNoteColumnPositions();
5260 if (syncRunner.addWork("SYNC")) {
5262 syncRunner.syncNeeded = true;
5267 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5269 @SuppressWarnings("unused")
5270 private void syncThreadComplete(Boolean refreshNeeded) {
5271 setMessage(tr("Finalizing Synchronization"));
5273 syncRunning = false;
5274 syncRunner.syncNeeded = false;
5275 synchronizeAnimationTimer.stop();
5276 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5278 if (currentNote == null) {
5279 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5281 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5282 noteIndexUpdated(false);
5283 noteTableView.selectionModel().blockSignals(true);
5284 scrollToGuid(currentNoteGuid);
5285 noteTableView.selectionModel().blockSignals(false);
5286 refreshEvernoteNote(false);
5287 scrollToGuid(currentNoteGuid);
5289 if (!syncRunner.error)
5290 setMessage(tr("Synchronization Complete"));
5292 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5293 logger.log(logger.MEDIUM, "Sync complete.");
5295 public void saveUploadAmount(long t) {
5296 Global.saveUploadAmount(t);
5298 public void saveUserInformation(User user) {
5299 Global.saveUserInformation(user);
5301 public void saveEvernoteUpdateCount(int i) {
5302 Global.saveEvernoteUpdateCount(i);
5304 public void refreshLists() {
5305 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5306 System.out.println("<><><><><><><><><><><><><><><><><><><><>");
5308 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5309 tagIndexUpdated(true);
5310 notebookIndexUpdated();
5311 savedSearchIndexUpdated();
5312 listManager.loadNotesIndex();
5314 noteTableView.selectionModel().blockSignals(true);
5315 noteIndexUpdated(true);
5316 noteTableView.selectionModel().blockSignals(false);
5317 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5321 @SuppressWarnings("unused")
5322 private void authTimer() {
5323 Calendar cal = Calendar.getInstance();
5325 // If we are not connected let's get out of here
5326 if (!Global.isConnected)
5329 // If this is the first time through, then we need to set this
5330 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5331 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5333 // long now = new Date().getTime();
5334 // if (now > Global.authRefreshTime && Global.isConnected) {
5335 syncRunner.authRefreshNeeded = true;
5339 @SuppressWarnings("unused")
5340 private void authRefreshComplete(boolean goodSync) {
5341 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5342 Global.isConnected = syncRunner.isConnected;
5344 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5345 authTimer.start(1000*60*15);
5346 logger.log(logger.LOW, "Authentication token has been renewed");
5347 // setMessage("Authentication token has been renewed.");
5349 authTimer.start(1000*60*5);
5350 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5351 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5353 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5357 @SuppressWarnings("unused")
5358 private synchronized void indexTimer() {
5359 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5362 if (!indexDisabled && indexRunner.idle) {
5363 thumbnailRunner.interrupt = true;
5364 indexRunner.addWork("SCAN");
5366 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5369 @SuppressWarnings("unused")
5370 private void indexStarted() {
5371 setMessage(tr("Indexing notes"));
5373 @SuppressWarnings("unused")
5374 private void indexComplete() {
5375 setMessage(tr("Index complete"));
5377 @SuppressWarnings("unused")
5378 private synchronized void toggleNoteIndexing() {
5379 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5380 indexDisabled = !indexDisabled;
5382 setMessage(tr("Indexing is now enabled."));
5384 setMessage(tr("Indexing is now disabled."));
5385 menuBar.disableIndexing.setChecked(indexDisabled);
5386 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5389 @SuppressWarnings("unused")
5390 private void threadMonitorCheck() {
5395 alive = listManager.threadCheck(Global.tagCounterThreadId);
5398 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5399 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5400 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5401 disableTagThreadCheck = true;
5406 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5408 notebookThreadDeadCount++;
5409 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5410 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5411 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5412 disableNotebookThreadCheck=true;
5415 notebookThreadDeadCount=0;
5417 alive = listManager.threadCheck(Global.trashCounterThreadId);
5420 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5421 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5422 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5423 disableTrashThreadCheck = true;
5428 alive = listManager.threadCheck(Global.saveThreadId);
5430 saveThreadDeadCount++;
5431 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5432 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5433 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5434 disableSaveThreadCheck = true;
5437 saveThreadDeadCount=0;
5439 if (!syncThread.isAlive()) {
5440 syncThreadDeadCount++;
5441 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5442 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5443 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5444 disableSyncThreadCheck = true;
5447 syncThreadDeadCount=0;
5449 if (!indexThread.isAlive()) {
5450 indexThreadDeadCount++;
5451 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5452 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5453 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5454 disableIndexThreadCheck = true;
5457 indexThreadDeadCount=0;
5462 private void thumbnailTimer() {
5463 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5464 thumbnailRunner.addWork("SCAN");
5468 //**************************************************
5469 //* Backup & Restore
5470 //**************************************************
5471 @SuppressWarnings("unused")
5472 private void databaseBackup() {
5473 QFileDialog fd = new QFileDialog(this);
5474 fd.setFileMode(FileMode.AnyFile);
5475 fd.setConfirmOverwrite(true);
5476 fd.setWindowTitle(tr("Backup Database"));
5477 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5478 fd.setAcceptMode(AcceptMode.AcceptSave);
5479 if (saveLastPath == null || saveLastPath.equals(""))
5480 fd.setDirectory(System.getProperty("user.home"));
5482 fd.setDirectory(saveLastPath);
5483 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5489 saveLastPath = fd.selectedFiles().get(0);
5490 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5491 setMessage(tr("Backing up database"));
5493 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5495 ExportData noteWriter = new ExportData(conn, true);
5496 String fileName = fd.selectedFiles().get(0);
5498 if (!fileName.endsWith(".nnex"))
5499 fileName = fileName +".nnex";
5500 noteWriter.exportData(fileName);
5501 setMessage(tr("Database backup completed."));
5506 @SuppressWarnings("unused")
5507 private void databaseRestore() {
5508 if (QMessageBox.question(this, tr("Confirmation"),
5509 tr("This is used to restore a database from backups.\n" +
5510 "It is HIGHLY recommened that this only be used to populate\n" +
5511 "an empty database. Restoring into a database that\n already has data" +
5512 " can cause problems.\n\nAre you sure you want to continue?"),
5513 QMessageBox.StandardButton.Yes,
5514 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5519 QFileDialog fd = new QFileDialog(this);
5520 fd.setFileMode(FileMode.ExistingFile);
5521 fd.setConfirmOverwrite(true);
5522 fd.setWindowTitle(tr("Restore Database"));
5523 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5524 fd.setAcceptMode(AcceptMode.AcceptOpen);
5525 if (saveLastPath == null || saveLastPath.equals(""))
5526 fd.setDirectory(System.getProperty("user.home"));
5528 fd.setDirectory(saveLastPath);
5529 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5535 saveLastPath = fd.selectedFiles().get(0);
5536 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5538 setMessage(tr("Restoring database"));
5539 ImportData noteReader = new ImportData(conn, true);
5540 noteReader.importData(fd.selectedFiles().get(0));
5542 if (noteReader.lastError != 0) {
5543 setMessage(noteReader.getErrorMessage());
5544 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5549 listManager.loadNoteTitleColors();
5551 refreshEvernoteNote(true);
5552 setMessage(tr("Database has been restored."));
5555 @SuppressWarnings("unused")
5556 private void exportNotes() {
5557 QFileDialog fd = new QFileDialog(this);
5558 fd.setFileMode(FileMode.AnyFile);
5559 fd.setConfirmOverwrite(true);
5560 fd.setWindowTitle(tr("Backup Database"));
5561 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5562 fd.setAcceptMode(AcceptMode.AcceptSave);
5563 fd.setDirectory(System.getProperty("user.home"));
5564 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5570 setMessage(tr("Exporting Notes"));
5573 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5574 selectedNoteGUIDs.add(currentNoteGuid);
5576 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5577 String fileName = fd.selectedFiles().get(0);
5579 if (!fileName.endsWith(".nnex"))
5580 fileName = fileName +".nnex";
5581 noteWriter.exportData(fileName);
5582 setMessage(tr("Export completed."));
5588 @SuppressWarnings("unused")
5589 private void importNotes() {
5590 QFileDialog fd = new QFileDialog(this);
5591 fd.setFileMode(FileMode.ExistingFile);
5592 fd.setConfirmOverwrite(true);
5593 fd.setWindowTitle(tr("Import Notes"));
5594 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5595 fd.setAcceptMode(AcceptMode.AcceptOpen);
5596 if (saveLastPath == null || saveLastPath.equals(""))
5597 fd.setDirectory(System.getProperty("user.home"));
5599 fd.setDirectory(saveLastPath);
5600 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5606 setMessage("Importing Notes");
5609 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5610 selectedNoteGUIDs.add(currentNoteGuid);
5612 ImportData noteReader = new ImportData(conn, false);
5613 String fileName = fd.selectedFiles().get(0);
5614 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5616 if (!fileName.endsWith(".nnex"))
5617 fileName = fileName +".nnex";
5618 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5619 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5621 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5623 noteReader.importData(fileName);
5625 if (noteReader.lastError != 0) {
5626 setMessage(noteReader.getErrorMessage());
5627 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5632 listManager.loadNoteTitleColors();
5634 refreshEvernoteNote(false);
5635 setMessage(tr("Notes have been imported."));
5638 setMessage("Import completed.");
5645 //**************************************************
5646 //* Duplicate a note
5647 //**************************************************
5648 @SuppressWarnings("unused")
5649 private void duplicateNote() {
5651 duplicateNote(currentNoteGuid);
5656 //**************************************************
5658 //**************************************************
5659 public void setupFolderImports() {
5660 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5662 if (importKeepWatcher == null)
5663 importKeepWatcher = new QFileSystemWatcher();
5664 if (importDeleteWatcher == null) {
5665 importDeleteWatcher = new QFileSystemWatcher();
5666 for (int i=0; i<records.size(); i++) {
5667 if (!records.get(i).keep)
5668 folderImportDelete(records.get(i).folder);
5674 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5675 for (int i=0; i<records.size(); i++) {
5676 if (records.get(i).keep)
5677 importKeepWatcher.addPath(records.get(i).folder);
5679 importDeleteWatcher.addPath(records.get(i).folder);
5682 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5683 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5685 // Look at the files already there so we don't import them again if a new file is created
5686 if (importedFiles == null) {
5687 importedFiles = new ArrayList<String>();
5688 for (int j=0; j<records.size(); j++) {
5689 QDir dir = new QDir(records.get(j).folder);
5690 List<QFileInfo> list = dir.entryInfoList();
5691 for (int k=0; k<list.size(); k++) {
5692 if (list.get(k).isFile())
5693 importedFiles.add(list.get(k).absoluteFilePath());
5698 public void folderImport() {
5699 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5700 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5702 if (!dialog.okClicked())
5705 // We have some sort of update.
5706 if (importKeepWatcher.directories().size() > 0)
5707 importKeepWatcher.removePaths(importKeepWatcher.directories());
5708 if (importDeleteWatcher.directories().size() > 0)
5709 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5711 conn.getWatchFolderTable().expungeAll();
5712 // Start building from the table
5713 for (int i=0; i<dialog.table.rowCount(); i++) {
5714 QTableWidgetItem item = dialog.table.item(i, 0);
5715 String dir = item.text();
5716 item = dialog.table.item(i, 1);
5717 String notebook = item.text();
5718 item = dialog.table.item(i, 2);
5720 if (item.text().equalsIgnoreCase("Keep"))
5725 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5726 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5728 setupFolderImports();
5731 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5733 String whichOS = System.getProperty("os.name");
5734 if (whichOS.contains("Windows"))
5735 dirName = dirName.replace('/','\\');
5737 FileImporter importer = new FileImporter(logger, conn);
5739 QDir dir = new QDir(dirName);
5740 List<QFileInfo> list = dir.entryInfoList();
5741 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5743 for (int i=0; i<list.size(); i++){
5745 boolean redundant = false;
5746 // Check if we've already imported this one or if it existed before
5747 for (int j=0; j<importedFiles.size(); j++) {
5748 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5753 importer.setFileInfo(list.get(i));
5754 importer.setFileName(list.get(i).absoluteFilePath());
5757 if (list.get(i).isFile() && importer.isValidType()) {
5759 if (!importer.importFile()) {
5760 // If we can't get to the file, it is probably locked. We'll try again later.
5761 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5762 importFilesKeep.add(list.get(i).absoluteFilePath());
5766 Note newNote = importer.getNote();
5767 newNote.setNotebookGuid(notebook);
5768 newNote.setTitle(dir.at(i));
5769 listManager.addNote(newNote);
5770 conn.getNoteTable().addNote(newNote, true);
5771 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5772 noteTableView.insertRow(newNote, true, -1);
5773 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5774 listManager.countNotebookResults(listManager.getNoteIndex());
5775 importedFiles.add(list.get(i).absoluteFilePath());
5783 public void folderImportDelete(String dirName) {
5785 String whichOS = System.getProperty("os.name");
5786 if (whichOS.contains("Windows"))
5787 dirName = dirName.replace('/','\\');
5789 FileImporter importer = new FileImporter(logger, conn);
5790 QDir dir = new QDir(dirName);
5791 List<QFileInfo> list = dir.entryInfoList();
5792 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5794 for (int i=0; i<list.size(); i++){
5795 importer.setFileInfo(list.get(i));
5796 importer.setFileName(list.get(i).absoluteFilePath());
5798 if (list.get(i).isFile() && importer.isValidType()) {
5800 if (!importer.importFile()) {
5801 // If we can't get to the file, it is probably locked. We'll try again later.
5802 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5803 importFilesKeep.add(list.get(i).absoluteFilePath());
5807 Note newNote = importer.getNote();
5808 newNote.setNotebookGuid(notebook);
5809 newNote.setTitle(dir.at(i));
5810 listManager.addNote(newNote);
5811 conn.getNoteTable().addNote(newNote, true);
5812 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5813 noteTableView.insertRow(newNote, true, -1);
5814 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5815 listManager.countNotebookResults(listManager.getNoteIndex());
5816 dir.remove(dir.at(i));
5822 //**************************************************
5824 //**************************************************
5825 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5826 logger.log(logger.HIGH, "Entering exernalFileEdited");
5828 // Strip URL prefix and base dir path
5829 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5830 String name = fileName.replace(dPath, "");
5831 int pos = name.lastIndexOf('.');
5834 guid = guid.substring(0,pos);
5836 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5838 guid = name.substring(0, pos);
5841 QFile file = new QFile(fileName);
5842 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5843 // If we can't get to the file, it is probably locked. We'll try again later.
5844 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5845 externalFiles.add(fileName);
5848 QByteArray binData = file.readAll();
5850 if (binData.size() == 0) {
5851 // If we can't get to the file, it is probably locked. We'll try again later.
5852 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5853 externalFiles.add(fileName);
5857 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5859 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5860 if (r == null || r.getData() == null || r.getData().getBody() == null)
5862 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5863 MessageDigest md = MessageDigest.getInstance("MD5");
5864 md.update(binData.toByteArray());
5865 byte[] hash = md.digest();
5866 String newHash = Global.byteArrayToHexString(hash);
5867 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5868 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5870 if (externalWindows.containsKey(r.getNoteGuid())) {
5871 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5872 r.getGuid(), oldHash, newHash);
5874 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5875 Data data = r.getData();
5876 data.setBody(binData.toByteArray());
5877 data.setBodyHash(hash);
5878 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5880 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5882 if (r.getNoteGuid().equals(currentNoteGuid)) {
5883 QWebSettings.setMaximumPagesInCache(0);
5884 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5885 refreshEvernoteNote(true);
5886 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5889 if (externalWindows.containsKey(r.getNoteGuid())) {
5890 QWebSettings.setMaximumPagesInCache(0);
5891 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5892 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5896 logger.log(logger.HIGH, "Exiting externalFielEdited");
5898 // This is a timer event that tries to save any external files that were edited. This
5899 // is only needed if we couldn't save a file earlier.
5900 public void externalFileEditedSaver() {
5901 for (int i=externalFiles.size()-1; i>=0; i--) {
5903 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5904 externalFileEdited(externalFiles.get(i));
5905 externalFiles.remove(i);
5906 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5908 for (int i=0; i<importFilesKeep.size(); i++) {
5910 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5911 folderImportKeep(importFilesKeep.get(i));
5912 importFilesKeep.remove(i);
5913 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5915 for (int i=0; i<importFilesDelete.size(); i++) {
5916 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5917 folderImportDelete(importFilesDelete.get(i));
5918 importFilesDelete.remove(i);
5925 // If an attachment on the current note was edited, we need to update the current notes's hash
5926 // Update a note content's hash. This happens if a resource is edited outside of NN
5927 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5928 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5930 for (;position>-1;) {
5931 endPos = browser.getContent().indexOf(">", position+1);
5932 String oldSegment = browser.getContent().substring(position,endPos);
5933 int hashPos = oldSegment.indexOf("hash=\"");
5934 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5935 String hash = oldSegment.substring(hashPos+6, hashEnd);
5936 if (hash.equalsIgnoreCase(oldHash)) {
5937 String newSegment = oldSegment.replace(oldHash, newHash);
5938 String content = browser.getContent().substring(0,position) +
5940 browser.getContent().substring(endPos);
5941 browser.getBrowser().setContent(new QByteArray(content));;
5944 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5949 //*************************************************
5950 //* Minimize to tray
5951 //*************************************************
5953 public void changeEvent(QEvent e) {
5954 if (e.type() == QEvent.Type.WindowStateChange) {
5955 if (isMinimized() && Global.showTrayIcon()) {
5957 QTimer.singleShot(10, this, "hide()");
5961 windowMaximized = true;
5963 windowMaximized = false;
5967 //*************************************************
5968 //* Check database userid & passwords
5969 //*************************************************
5970 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
5971 Connection connection;
5974 Class.forName("org.h2.Driver");
5975 } catch (ClassNotFoundException e1) {
5976 e1.printStackTrace();
5981 String passwordString = null;
5982 if (cypherPassword==null || cypherPassword.trim().equals(""))
5983 passwordString = userPassword;
5985 passwordString = cypherPassword+" "+userPassword;
5986 connection = DriverManager.getConnection(url,userid,passwordString);
5987 } catch (SQLException e) {
5992 } catch (SQLException e) {
5993 e.printStackTrace();