2 * This file is part of NixNote
3 * Copyright 2009 Randy Baumgarte
5 * This file may be licensed under the terms of of the
6 * GNU General Public License Version 2 (the ``GPL'').
8 * Software distributed under the License is distributed
9 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10 * express or implied. See the GPL for the specific language
11 * governing rights and limitations.
13 * You should have received a copy of the GPL along with this
14 * program. If not, go to http://www.gnu.org/licenses/gpl.html
15 * or write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 package cx.fbn.nevernote;
20 import java.awt.Desktop;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.net.Authenticator;
25 import java.net.PasswordAuthentication;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.SQLException;
31 import java.sql.Statement;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.SortedMap;
44 import java.util.Vector;
46 import org.apache.log4j.Level;
47 import org.apache.log4j.Logger;
48 import org.apache.thrift.TException;
49 import org.h2.tools.ChangeFileEncryption;
51 import com.evernote.edam.error.EDAMNotFoundException;
52 import com.evernote.edam.error.EDAMSystemException;
53 import com.evernote.edam.error.EDAMUserException;
54 import com.evernote.edam.notestore.NoteFilter;
55 import com.evernote.edam.notestore.NoteVersionId;
56 import com.evernote.edam.type.Data;
57 import com.evernote.edam.type.LinkedNotebook;
58 import com.evernote.edam.type.Note;
59 import com.evernote.edam.type.NoteAttributes;
60 import com.evernote.edam.type.Notebook;
61 import com.evernote.edam.type.Publishing;
62 import com.evernote.edam.type.QueryFormat;
63 import com.evernote.edam.type.Resource;
64 import com.evernote.edam.type.SavedSearch;
65 import com.evernote.edam.type.Tag;
66 import com.evernote.edam.type.User;
67 import com.trolltech.qt.QThread;
68 import com.trolltech.qt.core.QByteArray;
69 import com.trolltech.qt.core.QDateTime;
70 import com.trolltech.qt.core.QDir;
71 import com.trolltech.qt.core.QEvent;
72 import com.trolltech.qt.core.QFile;
73 import com.trolltech.qt.core.QFileInfo;
74 import com.trolltech.qt.core.QFileSystemWatcher;
75 import com.trolltech.qt.core.QIODevice;
76 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
77 import com.trolltech.qt.core.QLocale;
78 import com.trolltech.qt.core.QMimeData;
79 import com.trolltech.qt.core.QModelIndex;
80 import com.trolltech.qt.core.QSize;
81 import com.trolltech.qt.core.QTemporaryFile;
82 import com.trolltech.qt.core.QTextCodec;
83 import com.trolltech.qt.core.QThreadPool;
84 import com.trolltech.qt.core.QTimer;
85 import com.trolltech.qt.core.QTranslator;
86 import com.trolltech.qt.core.QUrl;
87 import com.trolltech.qt.core.Qt;
88 import com.trolltech.qt.core.Qt.BGMode;
89 import com.trolltech.qt.core.Qt.ItemDataRole;
90 import com.trolltech.qt.core.Qt.KeyboardModifier;
91 import com.trolltech.qt.core.Qt.MouseButton;
92 import com.trolltech.qt.core.Qt.SortOrder;
93 import com.trolltech.qt.core.Qt.WidgetAttribute;
94 import com.trolltech.qt.gui.QAbstractItemView;
95 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
96 import com.trolltech.qt.gui.QAction;
97 import com.trolltech.qt.gui.QApplication;
98 import com.trolltech.qt.gui.QClipboard;
99 import com.trolltech.qt.gui.QCloseEvent;
100 import com.trolltech.qt.gui.QColor;
101 import com.trolltech.qt.gui.QComboBox;
102 import com.trolltech.qt.gui.QCursor;
103 import com.trolltech.qt.gui.QDesktopServices;
104 import com.trolltech.qt.gui.QDialog;
105 import com.trolltech.qt.gui.QFileDialog;
106 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
107 import com.trolltech.qt.gui.QFileDialog.FileMode;
108 import com.trolltech.qt.gui.QGridLayout;
109 import com.trolltech.qt.gui.QHBoxLayout;
110 import com.trolltech.qt.gui.QIcon;
111 import com.trolltech.qt.gui.QImage;
112 import com.trolltech.qt.gui.QKeySequence;
113 import com.trolltech.qt.gui.QLabel;
114 import com.trolltech.qt.gui.QMainWindow;
115 import com.trolltech.qt.gui.QMenu;
116 import com.trolltech.qt.gui.QMessageBox;
117 import com.trolltech.qt.gui.QMessageBox.StandardButton;
118 import com.trolltech.qt.gui.QPainter;
119 import com.trolltech.qt.gui.QPalette.ColorRole;
120 import com.trolltech.qt.gui.QPixmap;
121 import com.trolltech.qt.gui.QPrintDialog;
122 import com.trolltech.qt.gui.QPrinter;
123 import com.trolltech.qt.gui.QShortcut;
124 import com.trolltech.qt.gui.QSizePolicy;
125 import com.trolltech.qt.gui.QSizePolicy.Policy;
126 import com.trolltech.qt.gui.QSpinBox;
127 import com.trolltech.qt.gui.QSplashScreen;
128 import com.trolltech.qt.gui.QSplitter;
129 import com.trolltech.qt.gui.QStatusBar;
130 import com.trolltech.qt.gui.QSystemTrayIcon;
131 import com.trolltech.qt.gui.QTableWidgetItem;
132 import com.trolltech.qt.gui.QTextEdit;
133 import com.trolltech.qt.gui.QToolBar;
134 import com.trolltech.qt.gui.QTreeWidgetItem;
135 import com.trolltech.qt.network.QNetworkAccessManager;
136 import com.trolltech.qt.network.QNetworkReply;
137 import com.trolltech.qt.network.QNetworkRequest;
138 import com.trolltech.qt.webkit.QWebPage.WebAction;
139 import com.trolltech.qt.webkit.QWebSettings;
141 import cx.fbn.nevernote.config.InitializationException;
142 import cx.fbn.nevernote.config.StartupConfig;
143 import cx.fbn.nevernote.dialog.AccountDialog;
144 import cx.fbn.nevernote.dialog.ConfigDialog;
145 import cx.fbn.nevernote.dialog.DBEncryptDialog;
146 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
147 import cx.fbn.nevernote.dialog.DatabaseStatus;
148 import cx.fbn.nevernote.dialog.FindDialog;
149 import cx.fbn.nevernote.dialog.IgnoreSync;
150 import cx.fbn.nevernote.dialog.LogFileDialog;
151 import cx.fbn.nevernote.dialog.LoginDialog;
152 import cx.fbn.nevernote.dialog.NotebookArchive;
153 import cx.fbn.nevernote.dialog.NotebookEdit;
154 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
155 import cx.fbn.nevernote.dialog.PublishNotebook;
156 import cx.fbn.nevernote.dialog.SavedSearchEdit;
157 import cx.fbn.nevernote.dialog.SetIcon;
158 import cx.fbn.nevernote.dialog.ShareNotebook;
159 import cx.fbn.nevernote.dialog.SharedNotebookSyncError;
160 import cx.fbn.nevernote.dialog.StackNotebook;
161 import cx.fbn.nevernote.dialog.SynchronizationRequiredWarning;
162 import cx.fbn.nevernote.dialog.TagEdit;
163 import cx.fbn.nevernote.dialog.TagMerge;
164 import cx.fbn.nevernote.dialog.ThumbnailViewer;
165 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
166 import cx.fbn.nevernote.dialog.WatchFolder;
167 import cx.fbn.nevernote.evernote.NoteMetadata;
168 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
169 import cx.fbn.nevernote.filters.FilterEditorTags;
170 import cx.fbn.nevernote.gui.AttributeTreeWidget;
171 import cx.fbn.nevernote.gui.BrowserWindow;
172 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
173 import cx.fbn.nevernote.gui.ExternalBrowse;
174 import cx.fbn.nevernote.gui.MainMenuBar;
175 import cx.fbn.nevernote.gui.NotebookTreeWidget;
176 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
177 import cx.fbn.nevernote.gui.SearchPanel;
178 import cx.fbn.nevernote.gui.TableView;
179 import cx.fbn.nevernote.gui.TagTreeWidget;
180 import cx.fbn.nevernote.gui.Thumbnailer;
181 import cx.fbn.nevernote.gui.TrashTreeWidget;
182 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
183 import cx.fbn.nevernote.sql.DatabaseConnection;
184 import cx.fbn.nevernote.sql.WatchFolderRecord;
185 import cx.fbn.nevernote.threads.IndexRunner;
186 import cx.fbn.nevernote.threads.SyncRunner;
187 import cx.fbn.nevernote.threads.ThumbnailRunner;
188 import cx.fbn.nevernote.utilities.AESEncrypter;
189 import cx.fbn.nevernote.utilities.ApplicationLogger;
190 import cx.fbn.nevernote.utilities.FileImporter;
191 import cx.fbn.nevernote.utilities.FileUtils;
192 import cx.fbn.nevernote.utilities.ListManager;
193 import cx.fbn.nevernote.utilities.SyncTimes;
194 import cx.fbn.nevernote.xml.ExportData;
195 import cx.fbn.nevernote.xml.ImportData;
196 import cx.fbn.nevernote.xml.NoteFormatter;
199 public class NeverNote extends QMainWindow{
201 QStatusBar statusBar; // Application status bar
203 DatabaseConnection conn;
205 MainMenuBar menuBar; // Main menu bar
206 FindDialog find; // Text search in note dialog
207 List<String> emitLog; // Messages displayed in the status bar;
208 QSystemTrayIcon trayIcon; // little tray icon
209 QMenu trayMenu; // System tray menu
210 QAction trayExitAction; // Exit the application
211 QAction trayShowAction; // toggle the show/hide action
212 QAction trayAddNoteAction; // Add a note from the system tray
213 QNetworkAccessManager versionChecker; // Used when checking for new versions
215 NotebookTreeWidget notebookTree; // List of notebooks
216 AttributeTreeWidget attributeTree; // List of note attributes
217 TagTreeWidget tagTree; // list of user created tags
218 SavedSearchTreeWidget savedSearchTree; // list of saved searches
219 TrashTreeWidget trashTree; // Trashcan
220 TableView noteTableView; // List of notes (the widget).
222 public BrowserWindow browserWindow; // Window containing browser & labels
223 public QToolBar toolBar; // The tool bar under the menu
224 QComboBox searchField; // search filter bar on the toolbar;
225 QShortcut searchShortcut; // Shortcut to search bar
226 boolean searchPerformed = false; // Search was done?
227 QuotaProgressBar quotaBar; // The current quota usage
229 ApplicationLogger logger;
230 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
231 List<String> selectedTagGUIDs; // List of selected tag GUIDs
232 List<String> selectedNoteGUIDs; // List of selected notes
233 String selectedSavedSearchGUID; // Currently selected saved searches
234 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
236 NoteFilter filter; // Note filter
237 String currentNoteGuid; // GUID of the current note
238 Note currentNote; // The currently viewed note
239 boolean noteDirty; // Has the note been changed?
240 boolean inkNote; // if this is an ink note, it is read only
241 boolean readOnly; // Is this note read-only?
244 ListManager listManager; // DB runnable task
246 List<QTemporaryFile> tempFiles; // Array of temporary files;
248 QTimer indexTimer; // timer to start the index thread
249 IndexRunner indexRunner; // thread to index notes
252 QTimer syncTimer; // Sync on an interval
253 QTimer syncDelayTimer; // Sync delay to free up database
254 SyncRunner syncRunner; // thread to do a sync.
255 QThread syncThread; // Thread which talks to evernote
256 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
257 QThread thumbnailThread; // Thread that generates pretty pictures
258 QTimer saveTimer; // Timer to save note contents
260 QTimer authTimer; // Refresh authentication
261 QTimer externalFileSaveTimer; // Save files altered externally
262 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
263 List<String> externalFiles; // External files to save later
264 List<String> importFilesKeep; // Auto-import files to save later
265 List<String> importFilesDelete; // Auto-import files to save later
267 int indexTime; // how often to try and index
268 boolean indexRunning; // Is indexing running?
269 boolean indexDisabled; // Is indexing disabled?
271 int syncThreadsReady; // number of sync threads that are free
272 int syncTime; // Sync interval
273 boolean syncRunning; // Is sync running?
274 boolean automaticSync; // do sync automatically?
275 QTreeWidgetItem attributeTreeSelected;
277 QAction prevButton; // Go to the previous item viewed
278 QAction nextButton; // Go to the next item in the history
279 QAction downButton; // Go to the next item in the list
280 QAction upButton; // Go to the prev. item in the list;
281 QAction synchronizeButton; // Synchronize with Evernote
282 QAction allNotesButton; // Reset & view all notes
283 QTimer synchronizeAnimationTimer; // Timer to change animation button
284 int synchronizeIconAngle; // Used to rotate sync icon
285 QAction printButton; // Print Button
286 QAction tagButton; // Tag edit button
287 QAction attributeButton; // Attribute information button
288 QAction emailButton; // Email button
289 QAction deleteButton; // Delete button
290 QAction newButton; // new Note Button;
291 QSpinBox zoomSpinner; // Zoom zoom
292 QAction searchClearButton; // Clear the search field
294 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
296 QSplitter mainLeftRightSplitter; // main splitter for left/right side
297 QSplitter leftSplitter1; // first left hand splitter
298 QSplitter browserIndexSplitter; // splitter between note index & note text
300 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
301 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
302 List<String> importedFiles; // History of imported files (so we don't import twice)
304 OnlineNoteHistory historyWindow; // online history window
305 List<NoteVersionId> versions; // history versions
307 QTimer threadMonitorTimer; // Timer to watch threads.
308 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
309 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
310 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
311 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
312 int tagDeadCount=0; // number of consecutive dead times for the tag thread
313 int trashDeadCount=0; // number of consecutive dead times for the trash thread
314 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
315 boolean disableTagThreadCheck=false;
316 boolean disableNotebookThreadCheck=false;
317 boolean disableTrashThreadCheck=false;
318 boolean disableSaveThreadCheck=false;
319 boolean disableSyncThreadCheck=false;
320 boolean disableIndexThreadCheck=false;
322 HashMap<String, String> noteCache; // Cash of note content
323 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
324 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
325 List<String> historyGuids; // GUIDs of previously viewed items
326 int historyPosition; // Position within the viewed items
327 boolean fromHistory; // Is this from the history queue?
328 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
329 List<Thumbnailer> thumbGenerators; // generate preview image
330 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
331 boolean encryptOnShutdown; // should I encrypt when I close?
332 boolean decryptOnShutdown; // should I decrypt on shutdown;
333 String encryptCipher; // What cipher should I use?
334 Signal0 minimizeToTray;
335 boolean windowMaximized = false; // Keep track of the window state for restores
336 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
337 List<QPixmap> syncIcons; // Array of icons used in sync animation
338 private boolean closeAction = false; // Used to say when to close or when to minimize
339 private static Logger log = Logger.getLogger(NeverNote.class);
340 private String saveLastPath; // last path we used
341 private final QTimer messageTimer; // Timer to clear the status message.
342 private QTimer blockTimer;
343 BrowserWindow blockingWindow;
345 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
348 //***************************************************************
349 //***************************************************************
350 //** Constructor & main entry point
351 //***************************************************************
352 //***************************************************************
353 // Application Constructor
354 @SuppressWarnings("static-access")
355 public NeverNote(DatabaseConnection dbConn) {
357 if (conn.getConnection() == null) {
358 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
359 "is accessing the database or NixNote is already running.\n\n" +
360 "Please end any other process or shutdown the other NixNote before starting.\n\nExiting program."));
362 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
365 setObjectName("mainWindow");
366 // thread().setPriority(Thread.MAX_PRIORITY);
368 logger = new ApplicationLogger("nevernote.log");
369 logger.log(logger.HIGH, "Starting Application");
371 decryptOnShutdown = false;
372 encryptOnShutdown = false;
373 conn.checkDatabaseVersion();
377 // Start building the invalid XML tables
378 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
379 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
381 for (int i=0; i<elements.size(); i++) {
382 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
385 logger.log(logger.EXTREME, "Starting GUI build");
387 QTranslator nevernoteTranslator = new QTranslator();
388 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
389 QApplication.instance().installTranslator(nevernoteTranslator);
391 Global.originalPalette = QApplication.palette();
392 QApplication.setStyle(Global.getStyle());
393 if (Global.useStandardPalette())
394 QApplication.setPalette(QApplication.style().standardPalette());
395 setWindowTitle(tr("NixNote"));
397 mainLeftRightSplitter = new QSplitter();
398 setCentralWidget(mainLeftRightSplitter);
399 leftSplitter1 = new QSplitter();
400 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
402 browserIndexSplitter = new QSplitter();
403 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
405 //* Setup threads & thread timers
406 // int indexRunnerCount = Global.getIndexThreads();
407 // indexRunnerCount = 1;
408 QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount); // increase max thread count
410 logger.log(logger.EXTREME, "Building list manager");
411 listManager = new ListManager(conn, logger);
413 logger.log(logger.EXTREME, "Building index runners & timers");
414 indexRunner = new IndexRunner("indexRunner.log",
415 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
416 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
417 indexThread = new QThread(indexRunner, "Index Thread");
418 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
419 indexRunner.indexImageRecognition = Global.indexImageRecognition();
420 indexRunner.indexNoteBody = Global.indexNoteBody();
421 indexRunner.indexNoteTitle = Global.indexNoteTitle();
422 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
425 synchronizeAnimationTimer = new QTimer();
426 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
428 indexTimer = new QTimer();
429 indexTime = 1000*Global.getIndexThreadSleepInterval();
430 indexTimer.start(indexTime); // Start indexing timer
431 indexTimer.timeout.connect(this, "indexTimer()");
432 indexDisabled = false;
433 indexRunning = false;
435 logger.log(logger.EXTREME, "Setting sync thread & timers");
437 syncRunner = new SyncRunner("syncRunner.log",
438 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
439 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
440 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
441 syncTimer = new QTimer();
442 syncTimer.timeout.connect(this, "syncTimer()");
443 syncRunner.status.message.connect(this, "setMessage(String)");
444 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
445 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
448 automaticSync = true;
449 syncTimer.start(syncTime*60*1000);
451 automaticSync = false;
454 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
455 syncThread = new QThread(syncRunner, "Synchronization Thread");
459 logger.log(logger.EXTREME, "Starting thumnail thread");
460 pdfReadyQueue = new ArrayList<String>();
461 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
462 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
463 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
464 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
465 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
466 thumbnailThread.start();
467 thumbGenerators = new ArrayList<Thumbnailer>();
468 thumbnailTimer = new QTimer();
469 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
471 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
472 thumbnailTimer.start();
474 logger.log(logger.EXTREME, "Starting authentication timer");
475 authTimer = new QTimer();
476 authTimer.timeout.connect(this, "authTimer()");
477 authTimer.start(1000*60*15);
478 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
480 logger.log(logger.EXTREME, "Setting save note timer");
481 saveTimer = new QTimer();
482 saveTimer.timeout.connect(this, "saveNote()");
483 if (Global.getAutoSaveInterval() > 0) {
484 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
487 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
489 logger.log(logger.EXTREME, "Starting external file monitor timer");
490 externalFileSaveTimer = new QTimer();
491 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
492 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
493 externalFiles = new ArrayList<String>();
494 importFilesDelete = new ArrayList<String>();
495 importFilesKeep = new ArrayList<String>();
496 externalFileSaveTimer.start();
498 notebookTree = new NotebookTreeWidget(conn);
499 attributeTree = new AttributeTreeWidget();
500 tagTree = new TagTreeWidget(conn);
501 savedSearchTree = new SavedSearchTreeWidget();
502 trashTree = new TrashTreeWidget();
503 noteTableView = new TableView(logger, listManager);
505 searchField = new QComboBox();
506 searchField.setObjectName("searchField");
507 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
508 searchField.setEditable(true);
509 searchField.activatedIndex.connect(this, "searchFieldChanged()");
510 searchField.setDuplicatesEnabled(false);
511 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
512 searchShortcut = new QShortcut(this);
513 setupShortcut(searchShortcut, "Focus_Search");
514 searchShortcut.activated.connect(this, "focusSearch()");
516 quotaBar = new QuotaProgressBar();
518 zoomSpinner = new QSpinBox();
519 zoomSpinner.setMinimum(10);
520 zoomSpinner.setMaximum(1000);
521 zoomSpinner.setAccelerated(true);
522 zoomSpinner.setSingleStep(10);
523 zoomSpinner.setValue(100);
524 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
526 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
529 QGridLayout leftGrid = new QGridLayout();
530 leftSplitter1.setContentsMargins(5, 0, 0, 7);
531 leftSplitter1.setLayout(leftGrid);
532 leftGrid.addWidget(searchLayout,1,1);
533 leftGrid.addWidget(tagTree,2,1);
534 leftGrid.addWidget(attributeTree,3,1);
535 leftGrid.addWidget(savedSearchTree,4,1);
536 leftGrid.addWidget(trashTree,5, 1);
538 // Setup the browser window
539 noteCache = new HashMap<String,String>();
540 readOnlyCache = new HashMap<String, Boolean>();
541 inkNoteCache = new HashMap<String, Boolean>();
542 browserWindow = new BrowserWindow(conn);
544 mainLeftRightSplitter.addWidget(leftSplitter1);
545 mainLeftRightSplitter.addWidget(browserIndexSplitter);
547 if (Global.getListView() == Global.View_List_Wide) {
548 browserIndexSplitter.addWidget(noteTableView);
549 browserIndexSplitter.addWidget(browserWindow);
551 mainLeftRightSplitter.addWidget(noteTableView);
552 mainLeftRightSplitter.addWidget(browserWindow);
555 // Setup the thumbnail viewer
556 thumbnailViewer = new ThumbnailViewer();
557 thumbnailViewer.upArrow.connect(this, "upAction()");
558 thumbnailViewer.downArrow.connect(this, "downAction()");
559 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
560 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
562 //Setup external browser manager
563 externalWindows = new HashMap<String, ExternalBrowse>();
565 listManager.loadNotesIndex();
566 initializeNotebookTree();
568 initializeSavedSearchTree();
569 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
570 attributeTreeSelected = null;
571 initializeNoteTable();
573 selectedNoteGUIDs = new ArrayList<String>();
574 statusBar = new QStatusBar();
575 setStatusBar(statusBar);
576 menuBar = new MainMenuBar(this);
577 emitLog = new ArrayList<String>();
579 tagTree.setDeleteAction(menuBar.tagDeleteAction);
580 tagTree.setMergeAction(menuBar.tagMergeAction);
581 tagTree.setEditAction(menuBar.tagEditAction);
582 tagTree.setAddAction(menuBar.tagAddAction);
583 tagTree.setIconAction(menuBar.tagIconAction);
584 tagTree.setVisible(Global.isWindowVisible("tagTree"));
585 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
586 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
587 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
588 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
590 if (!Global.isWindowVisible("zoom")) {
591 searchLayout.hideZoom();
592 menuBar.hideZoom.setChecked(false);
595 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
596 notebookTree.setEditAction(menuBar.notebookEditAction);
597 notebookTree.setAddAction(menuBar.notebookAddAction);
598 notebookTree.setIconAction(menuBar.notebookIconAction);
599 notebookTree.setStackAction(menuBar.notebookStackAction);
600 notebookTree.setPublishAction(menuBar.notebookPublishAction);
601 notebookTree.setShareAction(menuBar.notebookShareAction);
602 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
603 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
604 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
605 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
606 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
608 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
609 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
610 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
611 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
612 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
613 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
614 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
616 noteTableView.setAddAction(menuBar.noteAdd);
617 noteTableView.setDeleteAction(menuBar.noteDelete);
618 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
619 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
620 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
621 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
622 noteTableView.noteSignal.notePinned.connect(this, "notePinned()");
623 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
624 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
625 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
626 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
628 quotaBar.setMouseClickAction(menuBar.accountAction);
631 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
632 trashTree.setEmptyAction(menuBar.emptyTrashAction);
633 trashTree.setVisible(Global.isWindowVisible("trashTree"));
634 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
635 trashTree.updateCounts(listManager.getTrashCount());
636 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
637 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
639 noteTableView.setVisible(Global.isWindowVisible("noteList"));
640 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
642 if (!Global.isWindowVisible("editorButtonBar"))
643 toggleEditorButtonBar();
644 if (!Global.isWindowVisible("leftPanel"))
645 menuBar.hideLeftSide.setChecked(true);
646 if (Global.isWindowVisible("noteInformation"))
647 toggleNoteInformation();
648 quotaBar.setVisible(Global.isWindowVisible("quota"));
649 if (!quotaBar.isVisible())
650 menuBar.hideQuota.setChecked(false);
651 searchField.setVisible(Global.isWindowVisible("searchField"));
652 if (!searchField.isVisible())
653 menuBar.hideSearch.setChecked(false);
655 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
660 find = new FindDialog();
661 find.getOkButton().clicked.connect(this, "doFindText()");
663 // Setup the tray icon menu bar
664 trayShowAction = new QAction(tr("Show/Hide"), this);
665 trayExitAction = new QAction(tr("Exit"), this);
666 trayAddNoteAction = new QAction(tr("Add Note"), this);
668 trayExitAction.triggered.connect(this, "closeNeverNote()");
669 trayAddNoteAction.triggered.connect(this, "addNote()");
670 trayShowAction.triggered.connect(this, "trayToggleVisible()");
672 trayMenu = new QMenu(this);
673 trayMenu.addAction(trayAddNoteAction);
674 trayMenu.addAction(trayShowAction);
675 trayMenu.addAction(trayExitAction);
678 trayIcon = new QSystemTrayIcon(this);
679 trayIcon.setToolTip(tr("NixNote"));
680 trayIcon.setContextMenu(trayMenu);
681 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
684 currentNoteGuid = Global.getLastViewedNoteGuid();
685 historyGuids = new ArrayList<String>();
689 if (!currentNoteGuid.trim().equals("")) {
690 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
693 noteIndexUpdated(true);
695 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
696 if (menuBar.showEditorBar.isChecked())
697 showEditorButtons(browserWindow);
698 tagIndexUpdated(true);
699 savedSearchIndexUpdated();
700 notebookIndexUpdated();
702 setupSyncSignalListeners();
703 setupBrowserSignalListeners();
704 setupIndexListeners();
707 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
708 tagTree.showAllTags(true);
710 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
711 setWindowIcon(appIcon);
712 trayIcon.setIcon(appIcon);
713 if (Global.showTrayIcon())
718 scrollToGuid(currentNoteGuid);
719 if (Global.automaticLogin()) {
721 if (Global.isConnected)
724 setupFolderImports();
727 restoreWindowState(true);
729 if (Global.mimicEvernoteInterface) {
730 notebookTree.selectGuid("");
733 threadMonitorTimer = new QTimer();
734 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
735 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
737 historyGuids.add(currentNoteGuid);
740 menuBar.blockSignals(true);
741 menuBar.narrowListView.blockSignals(true);
742 menuBar.wideListView.blockSignals(true);
743 if (Global.getListView() == Global.View_List_Narrow) {
744 menuBar.narrowListView.setChecked(true);
747 menuBar.wideListView.setChecked(true);
749 menuBar.blockSignals(false);
750 menuBar.narrowListView.blockSignals(false);
751 menuBar.wideListView.blockSignals(false);
753 if (Global.getListView() == Global.View_List_Wide) {
754 browserIndexSplitter.addWidget(noteTableView);
755 browserIndexSplitter.addWidget(browserWindow);
757 mainLeftRightSplitter.addWidget(noteTableView);
758 mainLeftRightSplitter.addWidget(browserWindow);
761 messageTimer = new QTimer();
762 messageTimer.timeout.connect(this, "clearMessage()");
763 messageTimer.setInterval(1000*15);
766 int sortCol = Global.getSortColumn();
767 int sortOrder = Global.getSortOrder();
768 noteTableView.proxyModel.blocked = true;
769 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
770 noteTableView.proxyModel.blocked = false;
771 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
773 if (Global.checkVersionUpgrade())
778 public static void main(String[] args) {
779 log.setLevel(Level.FATAL);
780 QApplication.initialize(args);
781 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
782 QSplashScreen splash = new QSplashScreen(pixmap);
785 DatabaseConnection dbConn;
788 initializeGlobalSettings(args);
790 showSplash = Global.isWindowVisible("SplashScreen");
794 dbConn = setupDatabaseConnection();
796 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
797 Global.getFileManager().purgeResDirectory(true);
799 } catch (InitializationException e) {
802 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
806 NeverNote application = new NeverNote(dbConn);
808 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
809 if (Global.startMinimized())
810 application.showMinimized();
812 if (Global.wasWindowMaximized())
813 application.showMaximized();
819 splash.finish(application);
821 System.out.println("Goodbye.");
826 * Open the internal database, or create if not present
828 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
830 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
831 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
833 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
834 File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
835 File fi = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
837 Global.setDatabaseUrl("");
839 Global.setResourceDatabaseUrl("");
841 Global.setIndexDatabaseUrl("");
843 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
844 boolean goodCheck = false;
846 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
848 if (!dialog.okPressed())
850 Global.cipherPassword = dialog.getPassword();
851 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
852 Global.getDatabaseUserPassword(), Global.cipherPassword);
855 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
856 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
857 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
861 // Encrypt the database upon shutdown
862 private void encryptOnShutdown() {
863 String dbPath= Global.getFileManager().getDbDirPath("");
866 Statement st = conn.getConnection().createStatement();
867 st.execute("shutdown");
868 st = conn.getResourceConnection().createStatement();
869 st.execute("shutdown");
870 st = conn.getIndexConnection().createStatement();
871 st.execute("shutdown");
872 if (QMessageBox.question(this, tr("Are you sure"),
873 tr("Are you sure you wish to encrypt the database?"),
874 QMessageBox.StandardButton.Yes,
875 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
876 ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
877 ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
878 ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
879 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
880 Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
881 Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
883 QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
885 } catch (SQLException e) {
890 // Decrypt the database upon shutdown
891 private void decryptOnShutdown() {
892 String dbPath= Global.getFileManager().getDbDirPath("");
893 String dbName = "NeverNote";
895 Statement st = conn.getConnection().createStatement();
896 st.execute("shutdown");
897 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
898 encryptCipher = "AES";
900 encryptCipher = "XTEA";
901 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
902 "Are you sure you wish to decrypt the database?"),
903 QMessageBox.StandardButton.Yes,
904 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
906 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
907 Global.setDatabaseUrl("");
908 Global.setResourceDatabaseUrl("");
909 Global.setIndexDatabaseUrl("");
910 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
912 } catch (SQLException e) {
917 * Encrypt/Decrypt the local database
919 public void doDatabaseEncrypt() {
920 // The database is not currently encrypted
921 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
922 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
923 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
924 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
925 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
926 "Do you wish to proceed?"),
927 QMessageBox.StandardButton.Yes,
928 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
931 DBEncryptDialog dialog = new DBEncryptDialog();
933 if (dialog.okPressed()) {
934 Global.cipherPassword = dialog.getPassword();
935 encryptOnShutdown = true;
936 encryptCipher = dialog.getEncryptionMethod();
939 DBEncryptDialog dialog = new DBEncryptDialog();
940 dialog.setWindowTitle(tr("Database Decryption"));
941 dialog.hideEncryption();
943 if (dialog.okPressed()) {
944 if (!dialog.getPassword().equals(Global.cipherPassword)) {
945 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
948 decryptOnShutdown = true;
955 private static void initializeGlobalSettings(String[] args) throws InitializationException {
956 StartupConfig startupConfig = new StartupConfig();
958 for (String arg : args) {
959 String lower = arg.toLowerCase();
960 if (lower.startsWith("--name="))
961 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
962 if (lower.startsWith("--home="))
963 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
964 if (lower.startsWith("--disable-viewing"))
965 startupConfig.setDisableViewing(true);
967 Global.setup(startupConfig);
972 public void closeEvent(QCloseEvent event) {
973 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
978 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
981 if (currentNote!= null & browserWindow!=null) {
982 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
983 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
986 setMessage(tr("Beginning shutdown."));
988 // Close down external windows
989 Collection<ExternalBrowse> windows = externalWindows.values();
990 Iterator<ExternalBrowse> iterator = windows.iterator();
991 while (iterator.hasNext()) {
992 ExternalBrowse browser = iterator.next();
993 browser.windowClosing.disconnect();
998 externalFileEditedSaver();
999 if (Global.isConnected && Global.synchronizeOnClose()) {
1000 setMessage(tr("Performing synchronization before closing."));
1001 syncRunner.syncNeeded = true;
1002 syncRunner.addWork("SYNC");
1004 syncRunner.keepRunning = false;
1006 syncRunner.addWork("STOP");
1007 setMessage("Closing Program.");
1008 threadMonitorTimer.stop();
1010 thumbnailRunner.addWork("STOP");
1011 indexRunner.addWork("STOP");
1016 if (tempFiles != null)
1019 browserWindow.noteSignal.tagsChanged.disconnect();
1020 browserWindow.noteSignal.titleChanged.disconnect();
1021 browserWindow.noteSignal.noteChanged.disconnect();
1022 browserWindow.noteSignal.notebookChanged.disconnect();
1023 browserWindow.noteSignal.createdDateChanged.disconnect();
1024 browserWindow.noteSignal.alteredDateChanged.disconnect();
1025 syncRunner.searchSignal.listChanged.disconnect();
1026 syncRunner.tagSignal.listChanged.disconnect();
1027 syncRunner.notebookSignal.listChanged.disconnect();
1028 syncRunner.noteIndexSignal.listChanged.disconnect();
1031 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1032 saveNoteColumnPositions();
1033 saveNoteIndexWidth();
1035 int width = notebookTree.columnWidth(0);
1036 Global.setColumnWidth("notebookTreeName", width);
1037 width = tagTree.columnWidth(0);
1038 Global.setColumnWidth("tagTreeName", width);
1040 Global.saveWindowMaximized(isMaximized());
1041 Global.saveCurrentNoteGuid(currentNoteGuid);
1043 int sortCol = noteTableView.proxyModel.sortColumn();
1044 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1045 Global.setSortColumn(sortCol);
1046 Global.setSortOrder(sortOrder);
1050 Global.keepRunning = false;
1052 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1053 if (indexRunner.thread().isAlive())
1054 indexRunner.thread().join(50);
1055 if (!indexRunner.thread().isAlive())
1056 logger.log(logger.MEDIUM, "Index thread has stopped");
1058 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1059 indexRunner.thread().interrupt();
1061 } catch (InterruptedException e1) {
1062 e1.printStackTrace();
1065 if (!syncRunner.thread().isAlive()) {
1066 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1067 if (syncRunner.thread().isAlive()) {
1068 System.out.println(tr("Synchronizing. Please be patient."));
1069 for(;syncRunner.thread().isAlive();) {
1072 } catch (InterruptedException e) {
1073 e.printStackTrace();
1077 logger.log(logger.MEDIUM, "Sync thread has stopped");
1080 if (encryptOnShutdown) {
1081 encryptOnShutdown();
1083 if (decryptOnShutdown) {
1084 decryptOnShutdown();
1087 Global.getFileManager().purgeResDirectory(false);
1088 } catch (InitializationException e) {
1089 System.out.println(tr("Empty res directory purge failed"));
1090 e.printStackTrace();
1092 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1095 @SuppressWarnings("unused")
1096 private void closeNeverNote() {
1100 public void setMessage(String s) {
1101 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1104 logger.log(logger.HIGH, "Message: " +s);
1105 statusBar.showMessage(s);
1109 messageTimer.stop();
1110 messageTimer.setSingleShot(true);
1111 messageTimer.start();
1114 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1117 private void clearMessage() {
1118 statusBar.clearMessage();
1122 private void waitCursor(boolean wait) {
1124 if (QApplication.overrideCursor() == null)
1125 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1128 while (QApplication.overrideCursor() != null)
1129 QApplication.restoreOverrideCursor();
1131 listManager.refreshCounters();
1134 private void setupIndexListeners() {
1135 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1136 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1137 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1138 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1140 private void setupSyncSignalListeners() {
1141 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1142 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1143 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1144 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1145 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1147 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1148 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1149 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1151 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1152 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1153 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1154 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1155 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1157 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1160 private void setupBrowserSignalListeners() {
1161 setupBrowserWindowListeners(browserWindow, true);
1164 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1165 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1166 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1167 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1168 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1169 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1170 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1171 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1172 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1173 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1174 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1175 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1176 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1177 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1178 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1179 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1180 browser.unblockApplication.connect(this, "unblockApplication()");
1181 if (master) browser.focusLost.connect(this, "saveNote()");
1182 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1183 browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1186 //**************************************************
1188 //**************************************************
1189 private void setupShortcut(QShortcut action, String text) {
1190 if (!Global.shortcutKeys.containsAction(text))
1192 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1195 //***************************************************************
1196 //***************************************************************
1197 //* Settings and look & feel
1198 //***************************************************************
1199 //***************************************************************
1200 @SuppressWarnings("unused")
1201 private void settings() {
1202 logger.log(logger.HIGH, "Entering NeverNote.settings");
1203 saveNoteColumnPositions();
1204 saveNoteIndexWidth();
1206 ConfigDialog settings = new ConfigDialog(this);
1207 String dateFormat = Global.getDateFormat();
1208 String timeFormat = Global.getTimeFormat();
1210 indexTime = 1000*Global.getIndexThreadSleepInterval();
1211 indexTimer.start(indexTime); // reset indexing timer
1214 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1215 indexRunner.indexNoteBody = Global.indexNoteBody();
1216 indexRunner.indexNoteTitle = Global.indexNoteTitle();
1217 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1218 indexRunner.indexImageRecognition = Global.indexImageRecognition();
1219 if (Global.showTrayIcon())
1224 if (menuBar.showEditorBar.isChecked())
1225 showEditorButtons(browserWindow);
1227 // Reset the save timer
1228 if (Global.getAutoSaveInterval() > 0)
1229 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1234 // Set special reloads
1235 if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1236 conn.executeSql("Delete from LinkedNotebook");
1237 conn.executeSql("delete from SharedNotebook");
1238 conn.executeSql("Delete from Notebook where linked=true");
1239 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1240 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1245 readOnlyCache.clear();
1246 inkNoteCache.clear();
1247 noteIndexUpdated(true);
1249 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1251 // Restore things to the way they were
1252 private void restoreWindowState(boolean mainWindow) {
1253 // We need to name things or this doesn't work.
1254 setObjectName("NeverNote");
1255 restoreState(Global.restoreState(objectName()));
1256 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1257 browserIndexSplitter.setObjectName("browserIndexSplitter");
1258 leftSplitter1.setObjectName("leftSplitter1");
1260 // Restore the actual positions.
1262 restoreGeometry(Global.restoreGeometry(objectName()));
1263 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1264 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1265 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1268 // Save window positions for the next start
1269 private void saveWindowState() {
1270 Global.saveGeometry(objectName(), saveGeometry());
1271 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1272 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1273 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1274 Global.saveState(objectName(), saveState());
1276 // Load the style sheet
1277 private void loadStyleSheet() {
1278 String styleSheetName = "default.qss";
1279 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1280 styleSheetName = "default-cleanlooks.qss";
1281 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1282 QFile file = new QFile(fileName);
1284 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1285 if (!file.exists()) {
1286 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1287 file = new QFile(fileName);
1289 file.open(OpenModeFlag.ReadOnly);
1290 String styleSheet = file.readAll().toString();
1292 setStyleSheet(styleSheet);
1294 // Save column positions for the next time
1295 private void saveNoteColumnPositions() {
1296 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1297 Global.setColumnPosition("noteTableCreationPosition", position);
1298 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1299 Global.setColumnPosition("noteTableTagPosition", position);
1300 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1301 Global.setColumnPosition("noteTableNotebookPosition", position);
1302 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1303 Global.setColumnPosition("noteTableChangedPosition", position);
1304 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1305 Global.setColumnPosition("noteTableAuthorPosition", position);
1306 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1307 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1308 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1309 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1310 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1311 Global.setColumnPosition("noteTableTitlePosition", position);
1312 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1313 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1314 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1315 Global.setColumnPosition("noteTableGuidPosition", position);
1316 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1317 Global.setColumnPosition("noteTableThumbnailPosition", position);
1318 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1319 Global.setColumnPosition("noteTablePinnedPosition", position);
1322 // Save column widths for the next time
1323 private void saveNoteIndexWidth() {
1325 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1326 Global.setColumnWidth("noteTableCreationPosition", width);
1327 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1328 Global.setColumnWidth("noteTableChangedPosition", width);
1329 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1330 Global.setColumnWidth("noteTableGuidPosition", width);
1331 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1332 Global.setColumnWidth("noteTableNotebookPosition", width);
1333 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1334 Global.setColumnWidth("noteTableTagPosition", width);
1335 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1336 Global.setColumnWidth("noteTableTitlePosition", width);
1337 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1338 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1339 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1340 Global.setColumnWidth("noteTableAuthorPosition", width);
1341 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1342 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1343 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1344 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1345 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1346 Global.setColumnWidth("noteTableThumbnailPosition", width);
1347 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1348 Global.setColumnWidth("noteTableGuidPosition", width);
1351 @SuppressWarnings("unused")
1352 private void toggleSearchWindow() {
1353 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1354 searchLayout.toggleSearchField();
1355 menuBar.hideSearch.setChecked(searchField.isVisible());
1356 Global.saveWindowVisible("searchField", searchField.isVisible());
1357 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1359 @SuppressWarnings("unused")
1360 private void toggleQuotaWindow() {
1361 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1362 searchLayout.toggleQuotaBar();
1363 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1364 Global.saveWindowVisible("quota", quotaBar.isVisible());
1365 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1367 @SuppressWarnings("unused")
1368 private void toggleZoomWindow() {
1369 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1370 searchLayout.toggleZoom();
1371 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1372 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1373 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1378 //***************************************************************
1379 //***************************************************************
1380 //** These functions deal with Notebook menu items
1381 //***************************************************************
1382 //***************************************************************
1383 // Setup the tree containing the user's notebooks.
1384 private void initializeNotebookTree() {
1385 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1386 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1387 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1388 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1389 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1391 // Listener when a notebook is selected
1392 private void notebookTreeSelection() {
1393 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1394 noteTableView.proxyModel.blocked = true;
1397 clearAttributeFilter();
1398 clearSavedSearchFilter();
1399 if (Global.mimicEvernoteInterface) {
1401 searchField.clear();
1403 menuBar.noteRestoreAction.setVisible(false);
1404 menuBar.notebookEditAction.setEnabled(true);
1405 menuBar.notebookDeleteAction.setEnabled(true);
1406 menuBar.notebookPublishAction.setEnabled(true);
1407 menuBar.notebookShareAction.setEnabled(true);
1408 menuBar.notebookIconAction.setEnabled(true);
1409 menuBar.notebookStackAction.setEnabled(true);
1410 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1411 selectedNotebookGUIDs.clear();
1413 String stackName = "";
1414 if (selections.size() > 0) {
1415 guid = (selections.get(0).text(2));
1416 stackName = selections.get(0).text(0);
1418 if (!Global.mimicEvernoteInterface) {
1419 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1420 if (selections.size()==0) {
1421 selectedNotebookGUIDs.clear();
1422 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1423 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1425 menuBar.notebookEditAction.setEnabled(false);
1426 menuBar.notebookDeleteAction.setEnabled(false);
1427 menuBar.notebookStackAction.setEnabled(false);
1428 menuBar.notebookIconAction.setEnabled(false);
1431 if (!guid.equals("") && !guid.equals("STACK")) {
1432 selectedNotebookGUIDs.add(guid);
1433 menuBar.notebookIconAction.setEnabled(true);
1435 menuBar.notebookIconAction.setEnabled(true);
1436 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1437 Notebook book = listManager.getNotebookIndex().get(j);
1438 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1439 selectedNotebookGUIDs.add(book.getGuid());
1442 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1443 listManager.loadNotesIndex();
1444 noteIndexUpdated(false);
1445 refreshEvernoteNote(true);
1446 listManager.refreshCounters = true;
1447 listManager.refreshCounters();
1448 if (selectedNotebookGUIDs.size() == 1) {
1449 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1450 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1452 noteTableView.proxyModel.blocked = true;
1454 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1456 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1459 noteTableView.proxyModel.blocked = false;
1460 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1463 private void clearNotebookFilter() {
1464 notebookTree.blockSignals(true);
1465 notebookTree.clearSelection();
1466 menuBar.noteRestoreAction.setVisible(false);
1467 menuBar.notebookEditAction.setEnabled(false);
1468 menuBar.notebookDeleteAction.setEnabled(false);
1469 selectedNotebookGUIDs.clear();
1470 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1471 notebookTree.blockSignals(false);
1473 // Triggered when the notebook DB has been updated
1474 private void notebookIndexUpdated() {
1475 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1477 // Get the possible icons
1478 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1479 notebookTree.setIcons(icons);
1481 if (selectedNotebookGUIDs == null)
1482 selectedNotebookGUIDs = new ArrayList<String>();
1483 List<Notebook> books = conn.getNotebookTable().getAll();
1484 for (int i=books.size()-1; i>=0; i--) {
1485 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1486 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1488 j=listManager.getArchiveNotebookIndex().size();
1494 listManager.countNotebookResults(listManager.getNoteIndex());
1495 notebookTree.blockSignals(true);
1496 notebookTree.load(books, listManager.getLocalNotebooks());
1497 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1498 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1500 selectedNotebookGUIDs.remove(i);
1502 listManager.refreshCounters = true;
1503 listManager.refreshCounters();
1504 notebookTree.blockSignals(false);
1506 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1508 // Show/Hide note information
1509 @SuppressWarnings("unused")
1510 private void toggleNotebookWindow() {
1511 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1512 searchLayout.toggleNotebook();
1513 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1514 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1515 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1517 // Add a new notebook
1518 @SuppressWarnings("unused")
1519 private void addNotebook() {
1520 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1521 NotebookEdit edit = new NotebookEdit();
1522 edit.setNotebooks(listManager.getNotebookIndex());
1525 if (!edit.okPressed())
1528 Calendar currentTime = new GregorianCalendar();
1529 Long l = new Long(currentTime.getTimeInMillis());
1530 String randint = new String(Long.toString(l));
1532 Notebook newBook = new Notebook();
1533 newBook.setUpdateSequenceNum(0);
1534 newBook.setGuid(randint);
1535 newBook.setName(edit.getNotebook());
1536 newBook.setServiceCreated(new Date().getTime());
1537 newBook.setServiceUpdated(new Date().getTime());
1538 newBook.setDefaultNotebook(false);
1539 newBook.setPublished(false);
1541 listManager.getNotebookIndex().add(newBook);
1543 listManager.getLocalNotebooks().add(newBook.getGuid());
1544 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1545 notebookIndexUpdated();
1546 listManager.countNotebookResults(listManager.getNoteIndex());
1547 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1548 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1550 // Edit an existing notebook
1551 @SuppressWarnings("unused")
1552 private void stackNotebook() {
1553 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1554 StackNotebook edit = new StackNotebook();
1556 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1557 QTreeWidgetItem currentSelection;
1558 for (int i=0; i<selections.size(); i++) {
1559 currentSelection = selections.get(0);
1560 String guid = currentSelection.text(2);
1561 if (guid.equalsIgnoreCase("")) {
1562 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1565 if (guid.equalsIgnoreCase("STACK")) {
1566 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1571 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1576 if (!edit.okPressed())
1579 String stack = edit.getStackName();
1581 for (int i=0; i<selections.size(); i++) {
1582 currentSelection = selections.get(i);
1583 String guid = currentSelection.text(2);
1584 listManager.updateNotebookStack(guid, stack);
1586 notebookIndexUpdated();
1587 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1589 // Edit an existing notebook
1590 @SuppressWarnings("unused")
1591 private void editNotebook() {
1592 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1593 NotebookEdit edit = new NotebookEdit();
1595 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1596 QTreeWidgetItem currentSelection;
1597 currentSelection = selections.get(0);
1598 edit.setNotebook(currentSelection.text(0));
1600 String guid = currentSelection.text(2);
1601 if (!guid.equalsIgnoreCase("STACK")) {
1602 edit.setTitle(tr("Edit Notebook"));
1603 edit.setNotebooks(listManager.getNotebookIndex());
1604 edit.setLocalCheckboxEnabled(false);
1605 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1606 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1607 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1608 i=listManager.getNotebookIndex().size();
1612 edit.setTitle(tr("Edit Stack"));
1613 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1614 edit.hideLocalCheckbox();
1615 edit.hideDefaultCheckbox();
1620 if (!edit.okPressed())
1624 if (guid.equalsIgnoreCase("STACK")) {
1625 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1626 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1627 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1628 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1629 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1631 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1632 currentSelection.setText(0, edit.getNotebook());
1636 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1637 currentSelection.setText(0, edit.getNotebook());
1639 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1640 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1641 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1642 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1643 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1644 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1645 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1646 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1648 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1649 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1650 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1651 linkedNotebook.setShareName(edit.getNotebook());
1652 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1654 i=listManager.getNotebookIndex().size();
1658 // Build a list of non-closed notebooks
1659 List<Notebook> nbooks = new ArrayList<Notebook>();
1660 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1661 boolean found=false;
1662 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1663 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1667 nbooks.add(listManager.getNotebookIndex().get(i));
1671 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1672 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1673 browserWindow.setNotebookList(filteredBooks);
1674 Iterator<String> set = externalWindows.keySet().iterator();
1675 while(set.hasNext())
1676 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1677 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1679 // Publish a notebook
1680 @SuppressWarnings("unused")
1681 private void publishNotebook() {
1682 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1683 QTreeWidgetItem currentSelection;
1684 currentSelection = selections.get(0);
1685 String guid = currentSelection.text(2);
1687 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1692 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1693 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1694 n = listManager.getNotebookIndex().get(i);
1696 i = listManager.getNotebookIndex().size();
1702 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1705 if (!publish.okClicked())
1708 Publishing p = publish.getPublishing();
1709 boolean isPublished = !publish.isStopPressed();
1710 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1711 n.setPublished(isPublished);
1713 listManager.getNotebookIndex().set(position, n);
1714 notebookIndexUpdated();
1716 // Publish a notebook
1717 @SuppressWarnings("unused")
1718 private void shareNotebook() {
1719 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1720 QTreeWidgetItem currentSelection;
1721 currentSelection = selections.get(0);
1722 String guid = currentSelection.text(2);
1724 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1728 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1729 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1730 n = listManager.getNotebookIndex().get(i);
1731 i = listManager.getNotebookIndex().size();
1735 String authToken = null;
1736 if (syncRunner.isConnected)
1737 authToken = syncRunner.authToken;
1738 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1743 // Delete an existing notebook
1744 @SuppressWarnings("unused")
1745 private void deleteNotebook() {
1746 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1747 boolean stacksFound = false;
1748 boolean notebooksFound = false;
1749 boolean assigned = false;
1750 // Check if any notes have this notebook
1751 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1752 for (int i=0; i<selections.size(); i++) {
1753 QTreeWidgetItem currentSelection;
1754 currentSelection = selections.get(i);
1755 String guid = currentSelection.text(2);
1756 if (!guid.equalsIgnoreCase("STACK")) {
1757 notebooksFound = true;
1758 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1759 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1760 if (noteGuid.equals(guid)) {
1762 j=listManager.getNoteIndex().size();
1763 i=selections.size();
1771 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1772 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1776 if (conn.getNotebookTable().getAll().size() == 1) {
1777 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1781 // If all notebooks are clear, verify the delete
1782 String msg1 = new String(tr("Delete selected notebooks?"));
1783 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1784 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1785 " not deleted unless selected?"));
1787 if (stacksFound && notebooksFound)
1789 if (!stacksFound && notebooksFound)
1791 if (stacksFound && !notebooksFound)
1793 if (QMessageBox.question(this, tr("Confirmation"), msg,
1794 QMessageBox.StandardButton.Yes,
1795 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1799 // If confirmed, delete the notebook
1800 for (int i=selections.size()-1; i>=0; i--) {
1801 QTreeWidgetItem currentSelection;
1802 currentSelection = selections.get(i);
1803 String guid = currentSelection.text(2);
1804 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1805 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1806 listManager.renameStack(currentSelection.text(0), "");
1808 conn.getNotebookTable().expungeNotebook(guid, true);
1809 listManager.deleteNotebook(guid);
1813 notebookIndexUpdated();
1814 // notebookTreeSelection();
1815 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1816 // listManager.countNotebookResults(listManager.getNoteIndex());
1817 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1819 // A note's notebook has been updated
1820 @SuppressWarnings("unused")
1821 private void updateNoteNotebook(String guid, String notebookGuid) {
1823 // Update the list manager
1824 listManager.updateNoteNotebook(guid, notebookGuid);
1825 listManager.countNotebookResults(listManager.getNoteIndex());
1826 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1828 // Find the name of the notebook
1829 String notebookName = null;
1830 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1831 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1832 notebookName = listManager.getNotebookIndex().get(i).getName();
1837 // If we found the name, update the browser window
1838 if (notebookName != null) {
1839 updateListNoteNotebook(guid, notebookName);
1840 if (guid.equals(currentNoteGuid)) {
1841 int pos = browserWindow.notebookBox.findText(notebookName);
1843 browserWindow.notebookBox.setCurrentIndex(pos);
1847 // If we're dealing with the current note, then we need to be sure and update the notebook there
1848 if (guid.equals(currentNoteGuid)) {
1849 if (currentNote != null) {
1850 currentNote.setNotebookGuid(notebookGuid);
1854 // Open/close notebooks
1855 @SuppressWarnings("unused")
1856 private void closeNotebooks() {
1857 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1859 if (!na.okClicked())
1863 listManager.getArchiveNotebookIndex().clear();
1865 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1866 String text = na.getClosedBookList().takeItem(i).text();
1867 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1868 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1869 Notebook n = listManager.getNotebookIndex().get(j);
1870 conn.getNotebookTable().setArchived(n.getGuid(),true);
1871 listManager.getArchiveNotebookIndex().add(n);
1872 j=listManager.getNotebookIndex().size();
1877 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1878 String text = na.getOpenBookList().takeItem(i).text();
1879 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1880 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1881 Notebook n = listManager.getNotebookIndex().get(j);
1882 conn.getNotebookTable().setArchived(n.getGuid(),false);
1883 j=listManager.getNotebookIndex().size();
1887 notebookTreeSelection();
1888 listManager.loadNotesIndex();
1889 notebookIndexUpdated();
1890 noteIndexUpdated(false);
1891 reloadTagTree(true);
1892 // noteIndexUpdated(false);
1894 // Build a list of non-closed notebooks
1895 List<Notebook> nbooks = new ArrayList<Notebook>();
1896 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1897 boolean found=false;
1898 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1899 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1903 nbooks.add(listManager.getNotebookIndex().get(i));
1906 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1907 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1908 browserWindow.setNotebookList(filteredBooks);
1910 // Update any external windows
1911 Iterator<String> set = externalWindows.keySet().iterator();
1912 while(set.hasNext())
1913 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1917 // Change the notebook's icon
1918 @SuppressWarnings("unused")
1919 private void setNotebookIcon() {
1920 boolean stackSelected = false;
1921 boolean allNotebookSelected = false;
1923 QTreeWidgetItem currentSelection;
1924 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1925 if (selections.size() == 0)
1928 currentSelection = selections.get(0);
1929 String guid = currentSelection.text(2);
1930 if (guid.equalsIgnoreCase(""))
1931 allNotebookSelected = true;
1932 if (guid.equalsIgnoreCase("STACK"))
1933 stackSelected = true;
1935 QIcon currentIcon = currentSelection.icon(0);
1939 if (!stackSelected && !allNotebookSelected) {
1940 icon = conn.getNotebookTable().getIcon(guid);
1942 dialog = new SetIcon(currentIcon, saveLastPath);
1943 dialog.setUseDefaultIcon(true);
1945 dialog = new SetIcon(icon, saveLastPath);
1946 dialog.setUseDefaultIcon(false);
1949 if (stackSelected) {
1950 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1952 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1955 dialog = new SetIcon(currentIcon, saveLastPath);
1956 dialog.setUseDefaultIcon(true);
1958 dialog = new SetIcon(icon, saveLastPath);
1959 dialog.setUseDefaultIcon(false);
1963 if (dialog.okPressed()) {
1964 saveLastPath = dialog.getPath();
1966 QIcon newIcon = dialog.getIcon();
1967 if (stackSelected) {
1968 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1969 if (newIcon == null) {
1970 newIcon = new QIcon(iconPath+"books2.png");
1972 currentSelection.setIcon(0,newIcon);
1975 if (allNotebookSelected) {
1976 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1977 if (newIcon == null) {
1978 newIcon = new QIcon(iconPath+"notebook-green.png");
1980 currentSelection.setIcon(0,newIcon);
1983 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1984 if (newIcon == null) {
1985 boolean isPublished = false;;
1986 boolean found = false;
1987 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1988 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1989 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1993 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1995 currentSelection.setIcon(0, newIcon);
2001 //***************************************************************
2002 //***************************************************************
2003 //** These functions deal with Tag menu items
2004 //***************************************************************
2005 //***************************************************************
2006 // Add a new notebook
2007 @SuppressWarnings("unused")
2008 private void addTag() {
2009 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2010 TagEdit edit = new TagEdit();
2011 edit.setTagList(listManager.getTagIndex());
2013 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2014 QTreeWidgetItem currentSelection = null;
2015 if (selections.size() > 0) {
2016 currentSelection = selections.get(0);
2017 edit.setParentTag(currentSelection.text(0));
2022 if (!edit.okPressed())
2025 Calendar currentTime = new GregorianCalendar();
2026 Long l = new Long(currentTime.getTimeInMillis());
2027 String randint = new String(Long.toString(l));
2029 Tag newTag = new Tag();
2030 newTag.setUpdateSequenceNum(0);
2031 newTag.setGuid(randint);
2032 newTag.setName(edit.getTag());
2033 if (edit.getParentTag().isChecked()) {
2034 newTag.setParentGuid(currentSelection.text(2));
2035 newTag.setParentGuidIsSet(true);
2036 currentSelection.setExpanded(true);
2038 conn.getTagTable().addTag(newTag, true);
2039 listManager.getTagIndex().add(newTag);
2040 reloadTagTree(true);
2042 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2044 @SuppressWarnings("unused")
2045 private void reloadTagTree() {
2046 reloadTagTree(false);
2048 private void reloadTagTree(boolean reload) {
2049 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2050 tagIndexUpdated(reload);
2051 boolean filter = false;
2053 listManager.countTagResults(listManager.getNoteIndex());
2054 if (notebookTree.selectedItems().size() > 0
2055 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2057 if (tagTree.selectedItems().size() > 0)
2059 tagTree.showAllTags(!filter);
2060 tagIndexUpdated(false);
2061 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2063 // Edit an existing tag
2064 @SuppressWarnings("unused")
2065 private void editTag() {
2066 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2067 TagEdit edit = new TagEdit();
2068 edit.setTitle("Edit Tag");
2069 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2070 QTreeWidgetItem currentSelection;
2071 currentSelection = selections.get(0);
2072 edit.setTag(currentSelection.text(0));
2073 edit.setTagList(listManager.getTagIndex());
2076 if (!edit.okPressed())
2079 String guid = currentSelection.text(2);
2080 currentSelection.setText(0,edit.getTag());
2082 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2083 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2084 listManager.getTagIndex().get(i).setName(edit.getTag());
2085 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2086 updateListTagName(guid);
2087 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2088 browserWindow.setTag(getTagNamesForNote(currentNote));
2089 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2093 browserWindow.setTag(getTagNamesForNote(currentNote));
2094 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2096 // Delete an existing tag
2097 @SuppressWarnings("unused")
2098 private void deleteTag() {
2099 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2101 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2102 QMessageBox.StandardButton.Yes,
2103 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2107 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2108 for (int i=selections.size()-1; i>=0; i--) {
2109 QTreeWidgetItem currentSelection;
2110 currentSelection = selections.get(i);
2111 removeTagItem(currentSelection.text(2));
2113 tagIndexUpdated(true);
2115 listManager.countTagResults(listManager.getNoteIndex());
2116 // tagTree.updateCounts(listManager.getTagCounter());
2117 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2119 // Remove a tag tree item. Go recursively down & remove the children too
2120 private void removeTagItem(String guid) {
2121 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2122 String parent = listManager.getTagIndex().get(j).getParentGuid();
2123 if (parent != null && parent.equals(guid)) {
2124 //Remove this tag's children
2125 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2128 //Now, remove this tag
2129 removeListTagName(guid);
2130 conn.getTagTable().expungeTag(guid, true);
2131 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2132 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2133 listManager.getTagIndex().remove(a);
2138 // Setup the tree containing the user's tags
2139 private void initializeTagTree() {
2140 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2141 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2142 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2143 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2144 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2145 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2147 // Listener when a tag is selected
2148 private void tagTreeSelection() {
2149 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2152 clearAttributeFilter();
2153 clearSavedSearchFilter();
2155 menuBar.noteRestoreAction.setVisible(false);
2157 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2158 QTreeWidgetItem currentSelection;
2159 selectedTagGUIDs.clear();
2160 for (int i=0; i<selections.size(); i++) {
2161 currentSelection = selections.get(i);
2162 selectedTagGUIDs.add(currentSelection.text(2));
2164 if (selections.size() > 0) {
2165 menuBar.tagEditAction.setEnabled(true);
2166 menuBar.tagDeleteAction.setEnabled(true);
2167 menuBar.tagIconAction.setEnabled(true);
2170 menuBar.tagEditAction.setEnabled(false);
2171 menuBar.tagDeleteAction.setEnabled(false);
2172 menuBar.tagIconAction.setEnabled(true);
2174 if (selections.size() > 1)
2175 menuBar.tagMergeAction.setEnabled(true);
2177 menuBar.tagMergeAction.setEnabled(false);
2178 listManager.setSelectedTags(selectedTagGUIDs);
2179 listManager.loadNotesIndex();
2180 noteIndexUpdated(false);
2181 refreshEvernoteNote(true);
2182 listManager.refreshCounters = true;
2183 listManager.refreshCounters();
2184 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2186 // trigger the tag index to be refreshed
2187 @SuppressWarnings("unused")
2188 private void tagIndexUpdated() {
2189 tagIndexUpdated(true);
2191 private void tagIndexUpdated(boolean reload) {
2192 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2193 if (selectedTagGUIDs == null)
2194 selectedTagGUIDs = new ArrayList<String>();
2196 listManager.reloadTagIndex();
2198 tagTree.blockSignals(true);
2200 tagTree.setIcons(conn.getTagTable().getAllIcons());
2201 tagTree.load(listManager.getTagIndex());
2204 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2205 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2207 selectedTagGUIDs.remove(i);
2209 tagTree.blockSignals(false);
2211 browserWindow.setTag(getTagNamesForNote(currentNote));
2212 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2214 // Show/Hide note information
2215 @SuppressWarnings("unused")
2216 private void toggleTagWindow() {
2217 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2218 if (tagTree.isVisible())
2222 menuBar.hideTags.setChecked(tagTree.isVisible());
2223 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2224 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2226 // A note's tags have been updated
2227 @SuppressWarnings("unused")
2228 private void updateNoteTags(String guid, List<String> tags) {
2229 // Save any new tags. We'll need them later.
2230 List<String> newTags = new ArrayList<String>();
2231 for (int i=0; i<tags.size(); i++) {
2232 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2233 newTags.add(tags.get(i));
2236 listManager.saveNoteTags(guid, tags);
2237 listManager.countTagResults(listManager.getNoteIndex());
2238 StringBuffer names = new StringBuffer("");
2239 for (int i=0; i<tags.size(); i++) {
2240 names = names.append(tags.get(i));
2241 if (i<tags.size()-1) {
2242 names.append(Global.tagDelimeter + " ");
2245 browserWindow.setTag(names.toString());
2248 // Now, we need to add any new tags to the tag tree
2249 for (int i=0; i<newTags.size(); i++)
2250 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2252 // Get a string containing all tag names for a note
2253 private String getTagNamesForNote(Note n) {
2254 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2255 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2257 StringBuffer buffer = new StringBuffer(100);
2258 Vector<String> v = new Vector<String>();
2259 List<String> guids = n.getTagGuids();
2264 for (int i=0; i<guids.size(); i++) {
2265 v.add(listManager.getTagNameByGuid(guids.get(i)));
2267 Comparator<String> comparator = Collections.reverseOrder();
2268 Collections.sort(v,comparator);
2269 Collections.reverse(v);
2271 for (int i = 0; i<v.size(); i++) {
2273 buffer.append(", ");
2274 buffer.append(v.get(i));
2277 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2278 return buffer.toString();
2280 // Tags were added via dropping notes from the note list
2281 @SuppressWarnings("unused")
2282 private void tagsAdded(String noteGuid, String tagGuid) {
2283 String tagName = null;
2284 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2285 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2286 tagName = listManager.getTagIndex().get(i).getName();
2287 i=listManager.getTagIndex().size();
2290 if (tagName == null)
2293 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2294 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2295 List<String> tagNames = new ArrayList<String>();
2296 tagNames.add(new String(tagName));
2297 Note n = listManager.getMasterNoteIndex().get(i);
2298 for (int j=0; j<n.getTagNames().size(); j++) {
2299 tagNames.add(new String(n.getTagNames().get(j)));
2301 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2302 if (n.getGuid().equals(currentNoteGuid)) {
2303 Collections.sort(tagNames);
2304 String display = "";
2305 for (int j=0; j<tagNames.size(); j++) {
2306 display = display+tagNames.get(j);
2307 if (j+2<tagNames.size())
2308 display = display+Global.tagDelimeter+" ";
2310 browserWindow.setTag(display);
2312 i=listManager.getMasterNoteIndex().size();
2317 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2319 private void clearTagFilter() {
2320 tagTree.blockSignals(true);
2321 tagTree.clearSelection();
2322 menuBar.noteRestoreAction.setVisible(false);
2323 menuBar.tagEditAction.setEnabled(false);
2324 menuBar.tagMergeAction.setEnabled(false);
2325 menuBar.tagDeleteAction.setEnabled(false);
2326 menuBar.tagIconAction.setEnabled(false);
2327 selectedTagGUIDs.clear();
2328 listManager.setSelectedTags(selectedTagGUIDs);
2329 tagTree.blockSignals(false);
2331 // Change the icon for a tag
2332 @SuppressWarnings("unused")
2333 private void setTagIcon() {
2334 QTreeWidgetItem currentSelection;
2335 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2336 if (selections.size() == 0)
2339 currentSelection = selections.get(0);
2340 String guid = currentSelection.text(2);
2342 QIcon currentIcon = currentSelection.icon(0);
2343 QIcon icon = conn.getTagTable().getIcon(guid);
2346 dialog = new SetIcon(currentIcon, saveLastPath);
2347 dialog.setUseDefaultIcon(true);
2349 dialog = new SetIcon(icon, saveLastPath);
2350 dialog.setUseDefaultIcon(false);
2353 if (dialog.okPressed()) {
2354 saveLastPath = dialog.getPath();
2355 QIcon newIcon = dialog.getIcon();
2356 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2357 if (newIcon == null)
2358 newIcon = new QIcon(iconPath+"tag.png");
2359 currentSelection.setIcon(0, newIcon);
2364 @SuppressWarnings("unused")
2365 private void mergeTags() {
2366 List<Tag> tags = new ArrayList<Tag>();
2367 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2368 for (int i=0; i<selections.size(); i++) {
2369 Tag record = new Tag();
2370 record.setGuid(selections.get(i).text(2));
2371 record.setName(selections.get(i).text(0));
2375 TagMerge mergeDialog = new TagMerge(tags);
2377 if (!mergeDialog.okClicked())
2379 String newGuid = mergeDialog.getNewTagGuid();
2381 for (int i=0; i<tags.size(); i++) {
2382 if (!tags.get(i).getGuid().equals(newGuid)) {
2383 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2384 for (int j=0; j<noteGuids.size(); j++) {
2385 String noteGuid = noteGuids.get(j);
2386 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2387 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2388 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2392 listManager.reloadIndexes();
2395 //***************************************************************
2396 //***************************************************************
2397 //** These functions deal with Saved Search menu items
2398 //***************************************************************
2399 //***************************************************************
2400 // Add a new notebook
2401 @SuppressWarnings("unused")
2402 private void addSavedSearch() {
2403 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2404 SavedSearchEdit edit = new SavedSearchEdit();
2405 edit.setSearchList(listManager.getSavedSearchIndex());
2408 if (!edit.okPressed())
2411 Calendar currentTime = new GregorianCalendar();
2412 Long l = new Long(currentTime.getTimeInMillis());
2413 String randint = new String(Long.toString(l));
2415 SavedSearch search = new SavedSearch();
2416 search.setUpdateSequenceNum(0);
2417 search.setGuid(randint);
2418 search.setName(edit.getName());
2419 search.setQuery(edit.getQuery());
2420 search.setFormat(QueryFormat.USER);
2421 listManager.getSavedSearchIndex().add(search);
2422 conn.getSavedSearchTable().addSavedSearch(search, true);
2423 savedSearchIndexUpdated();
2424 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2426 // Edit an existing tag
2427 @SuppressWarnings("unused")
2428 private void editSavedSearch() {
2429 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2430 SavedSearchEdit edit = new SavedSearchEdit();
2431 edit.setTitle(tr("Edit Search"));
2432 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2433 QTreeWidgetItem currentSelection;
2434 currentSelection = selections.get(0);
2435 String guid = currentSelection.text(1);
2436 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2437 edit.setName(currentSelection.text(0));
2438 edit.setQuery(s.getQuery());
2439 edit.setSearchList(listManager.getSavedSearchIndex());
2442 if (!edit.okPressed())
2445 List<SavedSearch> list = listManager.getSavedSearchIndex();
2446 SavedSearch search = null;
2447 boolean found = false;
2448 for (int i=0; i<list.size(); i++) {
2449 search = list.get(i);
2450 if (search.getGuid().equals(guid)) {
2457 search.setName(edit.getName());
2458 search.setQuery(edit.getQuery());
2459 conn.getSavedSearchTable().updateSavedSearch(search, true);
2460 savedSearchIndexUpdated();
2461 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2463 // Delete an existing tag
2464 @SuppressWarnings("unused")
2465 private void deleteSavedSearch() {
2466 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2468 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2469 QMessageBox.StandardButton.Yes,
2470 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2474 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2475 for (int i=selections.size()-1; i>=0; i--) {
2476 QTreeWidgetItem currentSelection;
2477 currentSelection = selections.get(i);
2478 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2479 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2480 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2481 listManager.getSavedSearchIndex().remove(j);
2482 j=listManager.getSavedSearchIndex().size()+1;
2485 selections.remove(i);
2487 savedSearchIndexUpdated();
2488 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2490 // Setup the tree containing the user's tags
2491 private void initializeSavedSearchTree() {
2492 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2493 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2494 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2496 // Listener when a tag is selected
2497 @SuppressWarnings("unused")
2498 private void savedSearchTreeSelection() {
2499 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2501 clearNotebookFilter();
2504 clearAttributeFilter();
2506 String currentGuid = selectedSavedSearchGUID;
2507 menuBar.savedSearchEditAction.setEnabled(true);
2508 menuBar.savedSearchDeleteAction.setEnabled(true);
2509 menuBar.savedSearchIconAction.setEnabled(true);
2510 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2511 QTreeWidgetItem currentSelection;
2512 selectedSavedSearchGUID = "";
2513 for (int i=0; i<selections.size(); i++) {
2514 currentSelection = selections.get(i);
2515 if (currentSelection.text(1).equals(currentGuid)) {
2516 currentSelection.setSelected(false);
2518 selectedSavedSearchGUID = currentSelection.text(1);
2520 // i = selections.size() +1;
2523 // There is the potential for no notebooks to be selected if this
2524 // happens then we make it look like all notebooks were selecetd.
2525 // If that happens, just select the "all notebooks"
2526 if (selections.size()==0) {
2527 clearSavedSearchFilter();
2529 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2531 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2533 private void clearSavedSearchFilter() {
2534 menuBar.savedSearchEditAction.setEnabled(false);
2535 menuBar.savedSearchDeleteAction.setEnabled(false);
2536 menuBar.savedSearchIconAction.setEnabled(false);
2537 savedSearchTree.blockSignals(true);
2538 savedSearchTree.clearSelection();
2539 savedSearchTree.blockSignals(false);
2540 selectedSavedSearchGUID = "";
2541 searchField.setEditText("");
2542 searchPerformed = false;
2543 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2545 // trigger the tag index to be refreshed
2546 private void savedSearchIndexUpdated() {
2547 if (selectedSavedSearchGUID == null)
2548 selectedSavedSearchGUID = new String();
2549 savedSearchTree.blockSignals(true);
2550 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2551 savedSearchTree.load(listManager.getSavedSearchIndex());
2552 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2553 savedSearchTree.blockSignals(false);
2555 // trigger when the saved search selection changes
2556 @SuppressWarnings("unused")
2557 private void updateSavedSearchSelection() {
2558 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2560 menuBar.savedSearchEditAction.setEnabled(true);
2561 menuBar.savedSearchDeleteAction.setEnabled(true);
2562 menuBar.savedSearchIconAction.setEnabled(true);
2563 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2565 if (selections.size() > 0) {
2566 menuBar.savedSearchEditAction.setEnabled(true);
2567 menuBar.savedSearchDeleteAction.setEnabled(true);
2568 menuBar.savedSearchIconAction.setEnabled(true);
2569 selectedSavedSearchGUID = selections.get(0).text(1);
2570 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2571 searchField.setEditText(s.getQuery());
2573 menuBar.savedSearchEditAction.setEnabled(false);
2574 menuBar.savedSearchDeleteAction.setEnabled(false);
2575 menuBar.savedSearchIconAction.setEnabled(false);
2576 selectedSavedSearchGUID = "";
2577 searchField.setEditText("");
2579 searchFieldChanged();
2581 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2585 // Show/Hide note information
2586 @SuppressWarnings("unused")
2587 private void toggleSavedSearchWindow() {
2588 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2589 if (savedSearchTree.isVisible())
2590 savedSearchTree.hide();
2592 savedSearchTree.show();
2593 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2595 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2596 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2598 // Change the icon for a saved search
2599 @SuppressWarnings("unused")
2600 private void setSavedSearchIcon() {
2601 QTreeWidgetItem currentSelection;
2602 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2603 if (selections.size() == 0)
2606 currentSelection = selections.get(0);
2607 String guid = currentSelection.text(1);
2609 QIcon currentIcon = currentSelection.icon(0);
2610 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2613 dialog = new SetIcon(currentIcon, saveLastPath);
2614 dialog.setUseDefaultIcon(true);
2616 dialog = new SetIcon(icon, saveLastPath);
2617 dialog.setUseDefaultIcon(false);
2620 if (dialog.okPressed()) {
2621 saveLastPath = dialog.getPath();
2622 QIcon newIcon = dialog.getIcon();
2623 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2624 if (newIcon == null)
2625 newIcon = new QIcon(iconPath+"search.png");
2626 currentSelection.setIcon(0, newIcon);
2634 //***************************************************************
2635 //***************************************************************
2636 //** These functions deal with Help menu & tool menu items
2637 //***************************************************************
2638 //***************************************************************
2639 // Show database status
2640 @SuppressWarnings("unused")
2641 private void databaseStatus() {
2643 indexRunner.interrupt = true;
2644 int dirty = conn.getNoteTable().getDirtyCount();
2645 int unindexed = conn.getNoteTable().getUnindexedCount();
2646 DatabaseStatus status = new DatabaseStatus();
2647 status.setUnsynchronized(dirty);
2648 status.setUnindexed(unindexed);
2649 status.setNoteCount(conn.getNoteTable().getNoteCount());
2650 status.setNotebookCount(listManager.getNotebookIndex().size());
2651 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2652 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2653 status.setTagCount(listManager.getTagIndex().size());
2654 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2655 status.setWordCount(conn.getWordsTable().getWordCount());
2659 // Compact the database
2660 @SuppressWarnings("unused")
2661 private void compactDatabase() {
2662 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2663 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2664 "but please be aware that depending upon the size of your database this can be time consuming " +
2665 "and NixNote will be unresponsive until it is complete. Do you wish to continue?"),
2666 QMessageBox.StandardButton.Yes,
2667 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2670 setMessage("Compacting database.");
2672 listManager.compactDatabase();
2674 setMessage("Database compact is complete.");
2675 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2677 @SuppressWarnings("unused")
2678 private void accountInformation() {
2679 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2680 AccountDialog dialog = new AccountDialog();
2682 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2684 @SuppressWarnings("unused")
2685 private void releaseNotes() {
2686 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2687 QDialog dialog = new QDialog(this);
2688 QHBoxLayout layout = new QHBoxLayout();
2689 QTextEdit textBox = new QTextEdit();
2690 layout.addWidget(textBox);
2691 textBox.setReadOnly(true);
2692 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2693 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2694 QIODevice.OpenModeFlag.Text)))
2696 textBox.setText(file.readAll().toString());
2698 dialog.setWindowTitle(tr("Release Notes"));
2699 dialog.setLayout(layout);
2701 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2703 // Called when user picks Log from the help menu
2704 @SuppressWarnings("unused")
2705 private void logger() {
2706 logger.log(logger.HIGH, "Entering NeverNote.logger");
2707 LogFileDialog dialog = new LogFileDialog(emitLog);
2709 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2711 // Menu option "help/about" was selected
2712 @SuppressWarnings("unused")
2713 private void about() {
2714 logger.log(logger.HIGH, "Entering NeverNote.about");
2715 QMessageBox.about(this,
2716 tr("About NixNote"),
2717 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2719 +tr("<hr></center>Evernote"
2720 +"An Open Source Evernote Client.<br><br>"
2721 +"Licensed under GPL v2. <br><hr><br>"
2722 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2723 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2724 +"PDFRenderer is licened under the LGPL<br>"
2725 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2726 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2727 +"Jazzy is licened under the LGPL<br>"
2728 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2729 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2730 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2731 logger.log(logger.HIGH, "Leaving NeverNote.about");
2733 // Hide the entire left hand side
2734 @SuppressWarnings("unused")
2735 private void toggleLeftSide() {
2738 hidden = !menuBar.hideLeftSide.isChecked();
2739 menuBar.hideLeftSide.setChecked(!hidden);
2742 leftSplitter1.setHidden(true);
2744 leftSplitter1.setHidden(false);
2746 Global.saveWindowVisible("leftPanel", hidden);
2749 public void checkForUpdates() {
2750 // Send off thread to check for a new version
2751 versionChecker = new QNetworkAccessManager(this);
2752 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2753 QNetworkRequest request = new QNetworkRequest();
2754 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2755 versionChecker.get(request);
2757 @SuppressWarnings("unused")
2758 private void upgradeFileRead(QNetworkReply reply) {
2759 if (!reply.isReadable())
2762 String winVersion = Global.version;
2763 String osxVersion = Global.version;
2764 String linuxVersion = Global.version;
2765 String linux64Version = Global.version;
2766 String version = Global.version;
2768 // Determine the versions available
2769 QByteArray data = reply.readLine();
2770 while (data != null && !reply.atEnd()) {
2771 String line = data.toString();
2773 if (line.contains(":"))
2774 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2777 if (line.toLowerCase().contains("windows"))
2778 winVersion = lineVersion;
2779 else if (line.toLowerCase().contains("os-x"))
2780 osxVersion = lineVersion;
2781 else if (line.toLowerCase().contains("linux amd64"))
2782 linux64Version = lineVersion;
2783 else if (line.toLowerCase().contains("linux i386"))
2784 linuxVersion = lineVersion;
2785 else if (line.toLowerCase().contains("default"))
2786 version = lineVersion;
2788 // Read the next line
2789 data = reply.readLine();
2792 // Now we need to determine what system we are on.
2793 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2794 version = winVersion;
2795 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2796 version = osxVersion;
2797 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2798 if (System.getProperty("os.arch").contains("amd64") ||
2799 System.getProperty("os.arch").contains("x86_64"))
2800 version = linux64Version;
2802 version = linuxVersion;
2806 for (String validVersion : Global.validVersions) {
2807 if (version.equals(validVersion))
2811 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2813 if (dialog.remindMe())
2814 Global.setCheckVersionUpgrade(true);
2816 Global.setCheckVersionUpgrade(false);
2820 //***************************************************************
2821 //***************************************************************
2822 //** These functions deal with the Toolbar
2823 //***************************************************************
2824 //***************************************************************
2825 @SuppressWarnings("unused")
2826 private void focusSearch() {
2827 searchField.setFocus();
2830 // Text in the search bar has been cleared
2831 private void searchFieldCleared() {
2834 // This is done because we want to force a reload of
2835 // images. Some images we may want to highlight the text.
2836 readOnlyCache.clear();
2837 inkNoteCache.clear();
2839 QWebSettings.setMaximumPagesInCache(0);
2840 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2842 searchField.setEditText("");
2843 saveNoteColumnPositions();
2844 saveNoteIndexWidth();
2845 noteIndexUpdated(true);
2846 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2847 currentNote = listManager.getNoteIndex().get(0);
2848 currentNoteGuid = currentNote.getGuid();
2850 refreshEvernoteNote(true);
2851 if (currentNote != null)
2852 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2854 // text in the search bar changed. We only use this to tell if it was cleared,
2855 // otherwise we trigger off searchFieldChanged.
2856 @SuppressWarnings("unused")
2857 private void searchFieldTextChanged(String text) {
2858 QWebSettings.setMaximumPagesInCache(0);
2859 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2861 if (text.trim().equals("")) {
2862 searchFieldCleared();
2863 if (searchPerformed) {
2865 // This is done because we want to force a reload of
2866 // images. Some images we may want to highlight the text.
2868 readOnlyCache.clear();
2869 inkNoteCache.clear();
2871 listManager.setEnSearch("");
2872 listManager.loadNotesIndex();
2873 refreshEvernoteNote(true);
2874 noteIndexUpdated(false);
2875 refreshEvernoteNote(true);
2877 searchPerformed = false;
2880 // Text in the toolbar has changed
2881 private void searchFieldChanged() {
2882 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2884 readOnlyCache.clear();
2885 inkNoteCache.clear();
2886 saveNoteColumnPositions();
2887 saveNoteIndexWidth();
2888 String text = searchField.currentText();
2889 listManager.setEnSearch(text.trim());
2890 listManager.loadNotesIndex();
2891 noteIndexUpdated(false);
2892 refreshEvernoteNote(true);
2893 searchPerformed = true;
2894 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2897 // Build the window tool bar
2898 private void setupToolBar() {
2899 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2900 toolBar = addToolBar(tr("Tool Bar"));
2901 toolBar.setObjectName("toolBar");
2902 menuBar.setupToolBarVisible();
2903 if (!Global.isWindowVisible("toolBar"))
2904 toolBar.setVisible(false);
2906 toolBar.setVisible(true);
2908 // toolBar.addWidget(menuBar);
2909 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2910 // toolBar.addSeparator();
2911 prevButton = toolBar.addAction(tr("Previous"));
2912 QIcon prevIcon = new QIcon(iconPath+"back.png");
2913 prevButton.setIcon(prevIcon);
2914 prevButton.triggered.connect(this, "previousViewedAction()");
2915 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2917 nextButton = toolBar.addAction(tr("Next"));
2918 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2919 nextButton.setIcon(nextIcon);
2920 nextButton.triggered.connect(this, "nextViewedAction()");
2921 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2923 upButton = toolBar.addAction(tr("Up"));
2924 QIcon upIcon = new QIcon(iconPath+"up.png");
2925 upButton.setIcon(upIcon);
2926 upButton.triggered.connect(this, "upAction()");
2927 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2930 downButton = toolBar.addAction(tr("Down"));
2931 QIcon downIcon = new QIcon(iconPath+"down.png");
2932 downButton.setIcon(downIcon);
2933 downButton.triggered.connect(this, "downAction()");
2934 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2936 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2937 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2938 synchronizeIconAngle = 0;
2939 synchronizeButton.triggered.connect(this, "evernoteSync()");
2940 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2942 printButton = toolBar.addAction(tr("Print"));
2943 QIcon printIcon = new QIcon(iconPath+"print.png");
2944 printButton.setIcon(printIcon);
2945 printButton.triggered.connect(this, "printNote()");
2946 togglePrintButton(Global.isToolbarButtonVisible("print"));
2948 tagButton = toolBar.addAction(tr("Tag"));
2949 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2950 tagButton.setIcon(tagIcon);
2951 tagButton.triggered.connect(browserWindow, "modifyTags()");
2952 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2954 attributeButton = toolBar.addAction(tr("Attributes"));
2955 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2956 attributeButton.setIcon(attributeIcon);
2957 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2958 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2960 emailButton = toolBar.addAction(tr("Email"));
2961 QIcon emailIcon = new QIcon(iconPath+"email.png");
2962 emailButton.setIcon(emailIcon);
2963 emailButton.triggered.connect(this, "emailNote()");
2964 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2966 deleteButton = toolBar.addAction(tr("Delete"));
2967 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2968 deleteButton.setIcon(deleteIcon);
2969 deleteButton.triggered.connect(this, "deleteNote()");
2970 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2972 newButton = toolBar.addAction(tr("New"));
2973 QIcon newIcon = new QIcon(iconPath+"new.png");
2974 newButton.triggered.connect(this, "addNote()");
2975 newButton.setIcon(newIcon);
2976 toggleNewButton(Global.isToolbarButtonVisible("new"));
2978 allNotesButton = toolBar.addAction(tr("All Notes"));
2979 QIcon allIcon = new QIcon(iconPath+"books.png");
2980 allNotesButton.triggered.connect(this, "allNotes()");
2981 allNotesButton.setIcon(allIcon);
2982 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2984 //toolBar.addSeparator();
2985 //toolBar.addWidget(new QLabel(tr("Quota:")));
2986 //toolBar.addWidget(quotaBar);
2987 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2989 //toolBar.addSeparator();
2991 //toolBar.addWidget(new QLabel(tr("Zoom")));
2992 //toolBar.addWidget(zoomSpinner);
2994 //toolBar.addWidget(new QLabel(" "));
2995 //toolBar.addSeparator();
2996 //toolBar.addWidget(new QLabel(tr(" Search:")));
2997 //toolBar.addWidget(searchField);
2998 QSizePolicy sizePolicy = new QSizePolicy();
2999 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
3000 QLabel spacer = new QLabel("");
3001 spacer.setSizePolicy(sizePolicy);
3002 toolBar.addWidget(spacer);
3003 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3005 //searchClearButton = toolBar.addAction("Search Clear");
3006 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3007 //searchClearButton.setIcon(searchClearIcon);
3008 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3009 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3011 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3013 // Update the sychronize button picture
3015 public QMenu createPopupMenu() {
3016 QMenu contextMenu = super.createPopupMenu();
3018 contextMenu.addSeparator();
3019 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3020 contextMenu.addAction(prevAction);
3021 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3023 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3024 contextMenu.addAction(nextAction);
3025 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3027 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3028 contextMenu.addAction(upAction);
3029 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3031 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3032 contextMenu.addAction(downAction);
3033 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3035 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3036 contextMenu.addAction(synchronizeAction);
3037 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3039 QAction printAction = addContextAction("print", tr("Print"));
3040 contextMenu.addAction(printAction);
3041 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3043 QAction tagAction = addContextAction("tag", tr("Tag"));
3044 contextMenu.addAction(tagAction);
3045 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3047 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3048 contextMenu.addAction(attributeAction);
3049 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3051 QAction emailAction = addContextAction("email", tr("Email"));
3052 contextMenu.addAction(emailAction);
3053 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3055 QAction deleteAction = addContextAction("delete", tr("Delete"));
3056 contextMenu.addAction(deleteAction);
3057 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3059 QAction newAction = addContextAction("new", tr("Add"));
3060 contextMenu.addAction(newAction);
3061 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3063 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3064 contextMenu.addAction(allNotesAction);
3065 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3067 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3068 contextMenu.addAction(searchClearAction);
3069 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3074 private QAction addContextAction(String config, String name) {
3075 QAction newAction = new QAction(this);
3076 newAction.setText(name);
3077 newAction.setCheckable(true);
3078 newAction.setChecked(Global.isToolbarButtonVisible(config));
3081 private void togglePrevArrowButton(Boolean toggle) {
3082 prevButton.setVisible(toggle);
3083 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3085 private void toggleNextArrowButton(Boolean toggle) {
3086 nextButton.setVisible(toggle);
3087 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3089 private void toggleUpArrowButton(Boolean toggle) {
3090 upButton.setVisible(toggle);
3091 Global.saveToolbarButtonsVisible("upArrow", toggle);
3093 private void toggleDownArrowButton(Boolean toggle) {
3094 downButton.setVisible(toggle);
3095 Global.saveToolbarButtonsVisible("downArrow", toggle);
3097 private void toggleSynchronizeButton(Boolean toggle) {
3098 synchronizeButton.setVisible(toggle);
3099 Global.saveToolbarButtonsVisible("synchronize", toggle);
3101 private void togglePrintButton(Boolean toggle) {
3102 printButton.setVisible(toggle);
3103 Global.saveToolbarButtonsVisible("print", toggle);
3105 private void toggleTagButton(Boolean toggle) {
3106 tagButton.setVisible(toggle);
3107 Global.saveToolbarButtonsVisible("tag", toggle);
3109 private void toggleAttributeButton(Boolean toggle) {
3110 attributeButton.setVisible(toggle);
3111 Global.saveToolbarButtonsVisible("attribute", toggle);
3113 private void toggleEmailButton(Boolean toggle) {
3114 emailButton.setVisible(toggle);
3115 Global.saveToolbarButtonsVisible("email", toggle);
3117 private void toggleDeleteButton(Boolean toggle) {
3118 deleteButton.setVisible(toggle);
3119 Global.saveToolbarButtonsVisible("delete", toggle);
3121 private void toggleNewButton(Boolean toggle) {
3122 newButton.setVisible(toggle);
3123 Global.saveToolbarButtonsVisible("new", toggle);
3125 private void toggleAllNotesButton(Boolean toggle) {
3126 allNotesButton.setVisible(toggle);
3127 Global.saveToolbarButtonsVisible("allNotes", toggle);
3129 @SuppressWarnings("unused")
3130 private void toggleSearchClearButton(Boolean toggle) {
3131 searchClearButton.setVisible(toggle);
3132 Global.saveToolbarButtonsVisible("searchClear", toggle);
3139 @SuppressWarnings("unused")
3140 private void updateSyncButton() {
3142 if (syncIcons == null) {
3143 syncIcons = new ArrayList<QPixmap>();
3145 synchronizeIconAngle = 0;
3146 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3148 for (int i=0; i<=360; i++) {
3149 QPixmap rotatedPix = new QPixmap(pix.size());
3150 QPainter p = new QPainter(rotatedPix);
3151 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3152 QSize size = pix.size();
3153 p.translate(size.width()/2, size.height()/2);
3156 p.setBackgroundMode(BGMode.OpaqueMode);
3157 p.translate(-size.width()/2, -size.height()/2);
3158 p.drawPixmap(0,0, pix);
3160 syncIcons.add(rotatedPix);
3164 synchronizeIconAngle++;
3165 if (synchronizeIconAngle > 359)
3166 synchronizeIconAngle=0;
3167 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3170 // Synchronize with Evernote
3172 private void evernoteSync() {
3173 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3174 if (!Global.isConnected)
3176 if (Global.isConnected)
3177 synchronizeAnimationTimer.start(5);
3178 // synchronizeAnimationTimer.start(200);
3180 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3182 private void updateQuotaBar() {
3183 long limit = Global.getUploadLimit();
3184 long amount = Global.getUploadAmount();
3185 if (amount>0 && limit>0) {
3186 int percent =(int)(amount*100/limit);
3187 quotaBar.setValue(percent);
3189 quotaBar.setValue(0);
3192 @SuppressWarnings("unused")
3193 private void zoomChanged() {
3194 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3197 //****************************************************************
3198 //****************************************************************
3199 //* System Tray functions
3200 //****************************************************************
3201 //****************************************************************
3202 private void trayToggleVisible() {
3207 if (windowMaximized)
3214 @SuppressWarnings("unused")
3215 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3216 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3217 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3218 trayToggleVisible();
3223 //***************************************************************
3224 //***************************************************************
3225 //** These functions deal with the trash tree
3226 //***************************************************************
3227 //***************************************************************
3228 // Setup the tree containing the trash.
3229 @SuppressWarnings("unused")
3230 private void trashTreeSelection() {
3231 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3233 clearNotebookFilter();
3235 clearAttributeFilter();
3236 clearSavedSearchFilter();
3238 String tempGuid = currentNoteGuid;
3240 // currentNoteGuid = "";
3241 currentNote = new Note();
3242 selectedNoteGUIDs.clear();
3243 listManager.getSelectedNotebooks().clear();
3244 listManager.getSelectedTags().clear();
3245 listManager.setSelectedSavedSearch("");
3246 browserWindow.clear();
3248 // toggle the add buttons
3249 newButton.setEnabled(!newButton.isEnabled());
3250 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3251 menuBar.noteAdd.setVisible(true);
3253 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3254 if (selections.size() == 0) {
3255 currentNoteGuid = trashNoteGuid;
3256 trashNoteGuid = tempGuid;
3257 Global.showDeleted = false;
3258 menuBar.noteRestoreAction.setEnabled(false);
3259 menuBar.noteRestoreAction.setVisible(false);
3262 currentNoteGuid = trashNoteGuid;
3263 trashNoteGuid = tempGuid;
3264 menuBar.noteRestoreAction.setEnabled(true);
3265 menuBar.noteRestoreAction.setVisible(true);
3266 Global.showDeleted = true;
3268 listManager.loadNotesIndex();
3269 noteIndexUpdated(false);
3270 //// browserWindow.setEnabled(newButton.isEnabled());
3271 browserWindow.setReadOnly(!newButton.isEnabled());
3272 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3274 // Empty the trash file
3275 @SuppressWarnings("unused")
3276 private void emptyTrash() {
3277 // browserWindow.clear();
3278 logger.log(logger.EXTREME, "Emptying Trash");
3279 listManager.emptyTrash();
3280 logger.log(logger.EXTREME, "Resetting view after trash empty");
3281 if (trashTree.selectedItems().size() > 0) {
3282 listManager.getSelectedNotebooks().clear();
3283 listManager.getSelectedTags().clear();
3284 listManager.setSelectedSavedSearch("");
3285 newButton.setEnabled(!newButton.isEnabled());
3286 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3287 menuBar.noteAdd.setVisible(true);
3288 browserWindow.clear();
3291 clearNotebookFilter();
3292 clearSavedSearchFilter();
3293 clearAttributeFilter();
3295 Global.showDeleted = false;
3296 menuBar.noteRestoreAction.setEnabled(false);
3297 menuBar.noteRestoreAction.setVisible(false);
3299 listManager.loadNotesIndex();
3300 noteIndexUpdated(false);
3303 // Show/Hide trash window
3304 @SuppressWarnings("unused")
3305 private void toggleTrashWindow() {
3306 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3307 if (trashTree.isVisible())
3311 menuBar.hideTrash.setChecked(trashTree.isVisible());
3313 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3314 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3316 private void clearTrashFilter() {
3317 Global.showDeleted = false;
3318 newButton.setEnabled(true);
3319 menuBar.noteAdd.setEnabled(true);
3320 menuBar.noteAdd.setVisible(true);
3321 trashTree.blockSignals(true);
3322 trashTree.clearSelection();
3323 trashTree.blockSignals(false);
3328 //***************************************************************
3329 //***************************************************************
3330 //** These functions deal with connection settings
3331 //***************************************************************
3332 //***************************************************************
3333 // SyncRunner had a problem and things are disconnected
3334 @SuppressWarnings("unused")
3335 private void remoteErrorDisconnect() {
3336 menuBar.connectAction.setText(tr("Connect"));
3337 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3338 menuBar.synchronizeAction.setEnabled(false);
3339 Global.isConnected = false;
3340 synchronizeAnimationTimer.stop();
3343 // Do a manual connect/disconnect
3344 private void remoteConnect() {
3345 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3347 if (Global.isConnected) {
3348 Global.isConnected = false;
3349 syncRunner.enDisconnect();
3350 setupConnectMenuOptions();
3355 AESEncrypter aes = new AESEncrypter();
3357 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3358 } catch (FileNotFoundException e) {
3359 // File not found, so we'll just get empty strings anyway.
3362 if (Global.getProxyValue("url").equals("")) {
3363 System.setProperty("http.proxyHost","") ;
3364 System.setProperty("http.proxyPort", "") ;
3365 System.setProperty("https.proxyHost","") ;
3366 System.setProperty("https.proxyPort", "") ;
3369 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3370 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3371 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3372 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3374 if (Global.getProxyValue("userid").equals("")) {
3375 Authenticator.setDefault(new Authenticator() {
3377 protected PasswordAuthentication getPasswordAuthentication() {
3379 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3385 syncRunner.userStoreUrl = Global.userStoreUrl;
3386 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3387 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3389 String userid = aes.getUserid();
3390 String password = aes.getPassword();
3391 if (!userid.equals("") && !password.equals("")) {
3392 Global.username = userid;
3393 Global.password = password;
3394 syncRunner.username = Global.username;
3395 syncRunner.password = Global.password;
3396 syncRunner.enConnect();
3399 Global.isConnected = syncRunner.isConnected;
3401 if (!Global.isConnected) {
3402 // Show the login dialog box
3403 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3404 LoginDialog login = new LoginDialog();
3407 if (!login.okPressed()) {
3411 Global.username = login.getUserid();
3412 Global.password = login.getPassword();
3414 syncRunner.username = Global.username;
3415 syncRunner.password = Global.password;
3416 syncRunner.enConnect();
3417 Global.isConnected = syncRunner.isConnected;
3420 if (!Global.isConnected)
3423 setupConnectMenuOptions();
3424 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3426 private void setupConnectMenuOptions() {
3427 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3428 if (!Global.isConnected) {
3429 menuBar.connectAction.setText(tr("Connect"));
3430 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3431 menuBar.synchronizeAction.setEnabled(false);
3433 menuBar.connectAction.setText(tr("Disconnect"));
3434 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3435 menuBar.synchronizeAction.setEnabled(true);
3437 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3442 //***************************************************************
3443 //***************************************************************
3444 //** These functions deal with the GUI Attribute tree
3445 //***************************************************************
3446 //***************************************************************
3447 @SuppressWarnings("unused")
3448 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3450 // clearTagFilter();
3451 // clearNotebookFilter();
3453 // clearSavedSearchFilter();
3455 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3456 if (item.childCount() > 0) {
3457 item.setSelected(false);
3459 Global.createdBeforeFilter.reset();
3460 Global.createdSinceFilter.reset();
3461 Global.changedBeforeFilter.reset();
3462 Global.changedSinceFilter.reset();
3463 Global.containsFilter.reset();
3464 attributeTreeSelected = item;
3465 DateAttributeFilterTable f = null;
3466 f = findDateAttributeFilterTable(item.parent());
3468 f.select(item.parent().indexOfChild(item));
3470 Global.containsFilter.select(item.parent().indexOfChild(item));
3473 listManager.loadNotesIndex();
3474 noteIndexUpdated(false);
3477 attributeTreeSelected = null;
3478 item.setSelected(false);
3479 Global.createdBeforeFilter.reset();
3480 Global.createdSinceFilter.reset();
3481 Global.changedBeforeFilter.reset();
3482 Global.changedSinceFilter.reset();
3483 Global.containsFilter.reset();
3484 listManager.loadNotesIndex();
3485 noteIndexUpdated(false);
3487 // This determines what attribute filter we need, depending upon the selection
3488 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3489 if (w.parent() != null && w.childCount() > 0) {
3490 QTreeWidgetItem parent = w.parent();
3491 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3492 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3493 return Global.createdSinceFilter;
3494 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3495 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3496 return Global.createdBeforeFilter;
3497 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3498 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3499 return Global.changedSinceFilter;
3500 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3501 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3502 return Global.changedBeforeFilter;
3507 // Show/Hide attribute search window
3508 @SuppressWarnings("unused")
3509 private void toggleAttributesWindow() {
3510 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3511 if (attributeTree.isVisible())
3512 attributeTree.hide();
3514 attributeTree.show();
3515 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3517 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3518 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3520 private void clearAttributeFilter() {
3521 Global.createdBeforeFilter.reset();
3522 Global.createdSinceFilter.reset();
3523 Global.changedBeforeFilter.reset();
3524 Global.changedSinceFilter.reset();
3525 Global.containsFilter.reset();
3526 attributeTreeSelected = null;
3527 attributeTree.blockSignals(true);
3528 attributeTree.clearSelection();
3529 attributeTree.blockSignals(false);
3533 //***************************************************************
3534 //***************************************************************
3535 //** These functions deal with the GUI Note index table
3536 //***************************************************************
3537 //***************************************************************
3538 // Initialize the note list table
3539 private void initializeNoteTable() {
3540 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3541 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3542 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3543 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3545 // Show/Hide trash window
3546 @SuppressWarnings("unused")
3547 private void toggleNoteListWindow() {
3548 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3549 if (noteTableView.isVisible())
3550 noteTableView.hide();
3552 noteTableView.show();
3553 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3555 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3556 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3558 // Handle the event that a user selects a note from the table
3559 @SuppressWarnings("unused")
3560 private void noteTableSelection() {
3561 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3565 // If the ctrl key is pressed, then they are selecting multiple
3566 // entries and we don't want to change the currently viewed note.
3567 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3568 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3571 if (historyGuids.size() == 0) {
3572 historyGuids.add(currentNoteGuid);
3573 historyPosition = 1;
3575 noteTableView.showColumn(Global.noteTableGuidPosition);
3577 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3578 if (!Global.isColumnVisible("guid"))
3579 noteTableView.hideColumn(Global.noteTableGuidPosition);
3581 if (selections.size() > 0) {
3583 menuBar.noteDuplicateAction.setEnabled(true);
3584 menuBar.noteOnlineHistoryAction.setEnabled(true);
3585 menuBar.noteMergeAction.setEnabled(true);
3586 selectedNoteGUIDs.clear();
3587 if (selections.size() != 1 || Global.showDeleted) {
3588 menuBar.noteDuplicateAction.setEnabled(false);
3590 if (selections.size() != 1 || !Global.isConnected) {
3591 menuBar.noteOnlineHistoryAction.setEnabled(false);
3593 if (selections.size() == 1) {
3594 menuBar.noteMergeAction.setEnabled(false);
3596 for (int i=0; i<selections.size(); i++) {
3597 int row = selections.get(i).row();
3599 upButton.setEnabled(false);
3601 upButton.setEnabled(true);
3602 if (row < listManager.getNoteTableModel().rowCount()-1)
3603 downButton.setEnabled(true);
3605 downButton.setEnabled(false);
3606 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3607 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3608 currentNoteGuid = (String)ix.values().toArray()[0];
3609 selectedNoteGUIDs.add(currentNoteGuid);
3613 nextButton.setEnabled(true);
3614 prevButton.setEnabled(true);
3616 int endPosition = historyGuids.size()-1;
3617 for (int j=historyPosition; j<=endPosition; j++) {
3618 historyGuids.remove(historyGuids.size()-1);
3620 historyGuids.add(currentNoteGuid);
3621 historyPosition = historyGuids.size();
3623 if (historyPosition <= 1)
3624 prevButton.setEnabled(false);
3625 if (historyPosition == historyGuids.size())
3626 nextButton.setEnabled(false);
3628 fromHistory = false;
3629 scrollToGuid(currentNoteGuid);
3630 refreshEvernoteNote(true);
3631 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3633 // Trigger a refresh when the note db has been updated
3634 private void noteIndexUpdated(boolean reload) {
3635 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3637 refreshEvernoteNoteList();
3638 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3639 noteTableView.load(reload);
3640 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3642 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3643 pos = noteTableView.proxyModel.rowCount();
3646 if (noteTableView.proxyModel.rowCount() == 0)
3649 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3651 currentNoteGuid = (String)i.data();
3655 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3657 scrollToGuid(currentNoteGuid);
3658 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3660 // Called when the list of notes is updated
3661 private void refreshEvernoteNoteList() {
3662 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3663 browserWindow.setDisabled(false);
3664 if (selectedNoteGUIDs == null)
3665 selectedNoteGUIDs = new ArrayList<String>();
3666 selectedNoteGUIDs.clear(); // clear out old entries
3668 String saveCurrentNoteGuid = new String();
3669 String tempNoteGuid = new String();
3671 historyGuids.clear();
3672 historyPosition = 0;
3673 prevButton.setEnabled(false);
3674 nextButton.setEnabled(false);
3676 if (currentNoteGuid == null)
3677 currentNoteGuid = new String();
3679 //determine current note guid
3680 for (Note note : listManager.getNoteIndex()) {
3681 tempNoteGuid = note.getGuid();
3682 if (currentNoteGuid.equals(tempNoteGuid)) {
3683 saveCurrentNoteGuid = tempNoteGuid;
3687 if (listManager.getNoteIndex().size() == 0) {
3688 currentNoteGuid = "";
3690 browserWindow.clear();
3691 browserWindow.setDisabled(true);
3694 if (!saveCurrentNoteGuid.equals("")) {
3695 refreshEvernoteNote(false);
3697 currentNoteGuid = "";
3699 reloadTagTree(false);
3701 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3703 // Called when the previous arrow button is clicked
3704 @SuppressWarnings("unused")
3705 private void previousViewedAction() {
3706 if (!prevButton.isEnabled())
3708 if (historyPosition == 0)
3711 if (historyPosition <= 0)
3713 String historyGuid = historyGuids.get(historyPosition-1);
3715 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3716 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3717 if (modelIndex != null) {
3718 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3719 String tableGuid = (String)ix.values().toArray()[0];
3720 if (tableGuid.equals(historyGuid)) {
3721 noteTableView.selectRow(i);
3727 @SuppressWarnings("unused")
3728 private void nextViewedAction() {
3729 if (!nextButton.isEnabled())
3731 String historyGuid = historyGuids.get(historyPosition);
3734 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3735 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3736 if (modelIndex != null) {
3737 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3738 String tableGuid = (String)ix.values().toArray()[0];
3739 if (tableGuid.equals(historyGuid)) {
3740 noteTableView.selectRow(i);
3746 // Called when the up arrow is clicked
3747 @SuppressWarnings("unused")
3748 private void upAction() {
3749 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3750 int row = selections.get(0).row();
3752 noteTableView.selectRow(row-1);
3755 // Called when the down arrow is clicked
3756 @SuppressWarnings("unused")
3757 private void downAction() {
3758 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3759 int row = selections.get(0).row();
3760 int max = listManager.getNoteTableModel().rowCount();
3762 noteTableView.selectRow(row+1);
3765 // Update a tag string for a specific note in the list
3766 @SuppressWarnings("unused")
3767 private void updateListTags(String guid, List<String> tags) {
3768 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3769 StringBuffer tagBuffer = new StringBuffer();
3770 for (int i=0; i<tags.size(); i++) {
3771 tagBuffer.append(tags.get(i));
3772 if (i<tags.size()-1)
3773 tagBuffer.append(", ");
3776 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3777 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3778 if (modelIndex != null) {
3779 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3780 String tableGuid = (String)ix.values().toArray()[0];
3781 if (tableGuid.equals(guid)) {
3782 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3783 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3784 noteTableView.proxyModel.invalidate();
3789 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3791 // Update a title for a specific note in the list
3792 @SuppressWarnings("unused")
3793 private void updateListAuthor(String guid, String author) {
3794 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3796 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3797 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3798 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3799 if (modelIndex != null) {
3800 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3801 String tableGuid = (String)ix.values().toArray()[0];
3802 if (tableGuid.equals(guid)) {
3803 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3804 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3805 noteTableView.proxyModel.invalidate();
3811 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3813 private void updateListNoteNotebook(String guid, String notebook) {
3814 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3815 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3816 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3818 // Update a title for a specific note in the list
3819 @SuppressWarnings("unused")
3820 private void updateListSourceUrl(String guid, String url) {
3821 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3823 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3824 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3825 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3826 if (modelIndex != null) {
3827 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3828 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3829 String tableGuid = (String)ix.values().toArray()[0];
3830 if (tableGuid.equals(guid)) {
3831 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3832 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3833 noteTableView.proxyModel.invalidate();
3838 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3840 @SuppressWarnings("unused")
3841 private void updateListGuid(String oldGuid, String newGuid) {
3842 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3844 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3845 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3846 if (modelIndex != null) {
3847 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3848 String tableGuid = (String)ix.values().toArray()[0];
3849 if (tableGuid.equals(oldGuid)) {
3850 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3851 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3856 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3858 private void updateListTagName(String guid) {
3859 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3861 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3862 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3863 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3865 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3866 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3867 if (modelIndex != null) {
3868 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3869 String noteGuid = (String)ix.values().toArray()[0];
3870 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3871 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3872 i=listManager.getNoteTableModel().rowCount();
3878 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3880 private void removeListTagName(String guid) {
3881 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3883 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3884 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3885 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3886 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3887 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3890 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3891 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3892 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3893 if (modelIndex != null) {
3894 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3895 String noteGuid = (String)ix.values().toArray()[0];
3896 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3897 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3898 i=listManager.getNoteTableModel().rowCount();
3904 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3906 private void updateListNotebookName(String oldName, String newName) {
3907 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3909 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3910 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3911 if (modelIndex != null) {
3912 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3913 String tableName = (String)ix.values().toArray()[0];
3914 if (tableName.equalsIgnoreCase(oldName)) {
3915 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3919 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3921 @SuppressWarnings("unused")
3922 private void updateListDateCreated(String guid, QDateTime date) {
3923 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3925 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3926 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3927 if (modelIndex != null) {
3928 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3929 String tableGuid = (String)ix.values().toArray()[0];
3930 if (tableGuid.equals(guid)) {
3931 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3932 noteTableView.proxyModel.invalidate();
3937 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3939 @SuppressWarnings("unused")
3940 private void updateListDateSubject(String guid, QDateTime date) {
3941 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3943 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3944 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3945 if (modelIndex != null) {
3946 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3947 String tableGuid = (String)ix.values().toArray()[0];
3948 if (tableGuid.equals(guid)) {
3949 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3950 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3951 noteTableView.proxyModel.invalidate();
3956 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3958 private void updateListDateChanged(String guid, QDateTime date) {
3959 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3961 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3962 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3963 if (modelIndex != null) {
3964 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3965 String tableGuid = (String)ix.values().toArray()[0];
3966 if (tableGuid.equals(guid)) {
3967 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3968 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3973 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3975 private void updateListDateChanged() {
3976 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3977 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3978 updateListDateChanged(currentNoteGuid, date);
3979 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3982 private void scrollToCurrentGuid() {
3983 //scrollToGuid(currentNoteGuid);
3984 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3985 if (selections.size() == 0)
3987 QModelIndex index = selections.get(0);
3988 int row = selections.get(0).row();
3989 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3992 // Scroll to the current GUID in tthe list.
3993 // Scroll to a particular index item
3994 private void scrollToGuid(String guid) {
3995 if (currentNote == null || guid == null)
3997 if (currentNote.isActive() && Global.showDeleted) {
3998 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3999 if (!listManager.getNoteIndex().get(i).isActive()) {
4000 currentNote = listManager.getNoteIndex().get(i);
4001 currentNoteGuid = currentNote.getGuid();
4002 i = listManager.getNoteIndex().size();
4006 if (!currentNote.isActive() && !Global.showDeleted) {
4007 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4008 if (listManager.getNoteIndex().get(i).isActive()) {
4009 currentNote = listManager.getNoteIndex().get(i);
4010 currentNoteGuid = currentNote.getGuid();
4011 i = listManager.getNoteIndex().size();
4016 for (int i=0; i<noteTableView.model().rowCount(); i++) {
4017 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4018 if (currentNoteGuid.equals(index.data())) {
4019 // noteTableView.selectionModel().blockSignals(true);
4020 noteTableView.selectRow(i);
4021 // noteTableView.selectionModel().blockSignals(false);
4022 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
4023 i=listManager.getNoteTableModel().rowCount();
4026 noteTableView.repaint();
4028 // Show/Hide columns
4029 private void showColumns() {
4030 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4031 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4032 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4033 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4034 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4035 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4036 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4037 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4038 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4039 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4040 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4042 // Title color has changed
4043 @SuppressWarnings("unused")
4044 private void titleColorChanged(Integer color) {
4045 logger.log(logger.HIGH, "Entering NeverNote.titleColorChanged");
4047 QColor backgroundColor = new QColor();
4048 QColor foregroundColor = new QColor(QColor.black);
4049 backgroundColor.setRgb(color);
4051 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4052 foregroundColor.setRgb(QColor.white.rgb());
4054 if (selectedNoteGUIDs.size() == 0)
4055 selectedNoteGUIDs.add(currentNoteGuid);
4057 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4058 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4059 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4060 if (modelIndex != null) {
4061 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4062 String tableGuid = (String)ix.values().toArray()[0];
4063 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4064 for (int k=0; k<Global.noteTableColumnCount; k++) {
4065 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4066 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4067 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4069 i=listManager.getNoteTableModel().rowCount();
4074 logger.log(logger.HIGH, "Leaving NeverNote.titleColorChanged");
4076 // A note has been pinned or unpinned
4077 @SuppressWarnings("unused")
4078 private void notePinned() {
4079 logger.log(logger.EXTREME, "Entering NeverNote.notePinned()");
4081 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4082 NoteMetadata meta = listManager.getNoteMetadata().get(selectedNoteGUIDs.get(j));
4083 boolean pinned = !meta.isPinned();
4084 meta.setPinned(pinned); // Toggle the pinned/unpinned
4086 // Update the list & table
4087 listManager.updateNoteMetadata(meta);
4088 noteTableView.proxyModel.addGuid(selectedNoteGUIDs.get(j), meta);
4091 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4093 // Wide list was chosen
4094 public void narrowListView() {
4095 saveNoteColumnPositions();
4096 saveNoteIndexWidth();
4098 int sortCol = noteTableView.proxyModel.sortColumn();
4099 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4100 Global.setSortColumn(sortCol);
4101 Global.setSortOrder(sortOrder);
4103 Global.setListView(Global.View_List_Narrow);
4105 menuBar.wideListView.blockSignals(true);
4106 menuBar.narrowListView.blockSignals(true);
4108 menuBar.wideListView.setChecked(false);
4109 menuBar.narrowListView.setChecked(true);
4111 menuBar.wideListView.blockSignals(false);
4112 menuBar.narrowListView.blockSignals(false);
4114 mainLeftRightSplitter.addWidget(noteTableView);
4115 mainLeftRightSplitter.addWidget(browserWindow);
4116 restoreWindowState(false);
4117 noteTableView.repositionColumns();
4118 noteTableView.resizeColumnWidths();
4119 noteTableView.resizeRowHeights();
4121 sortCol = Global.getSortColumn();
4122 sortOrder = Global.getSortOrder();
4123 noteTableView.proxyModel.blocked = true;
4124 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4125 noteTableView.proxyModel.blocked = false;
4129 noteTableView.load(false);
4130 refreshEvernoteNote(true);
4131 scrollToCurrentGuid();
4133 public void wideListView() {
4134 int sortCol = noteTableView.proxyModel.sortColumn();
4135 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4136 Global.setSortColumn(sortCol);
4137 Global.setSortOrder(sortOrder);
4140 saveNoteColumnPositions();
4141 saveNoteIndexWidth();
4142 Global.setListView(Global.View_List_Wide);
4144 menuBar.wideListView.blockSignals(true);
4145 menuBar.narrowListView.blockSignals(true);
4147 menuBar.wideListView.setChecked(true);
4148 menuBar.narrowListView.setChecked(false);
4150 menuBar.wideListView.blockSignals(false);
4151 menuBar.narrowListView.blockSignals(false);
4152 browserIndexSplitter.setVisible(true);
4153 browserIndexSplitter.addWidget(noteTableView);
4154 browserIndexSplitter.addWidget(browserWindow);
4155 restoreWindowState(false);
4156 noteTableView.repositionColumns();
4157 noteTableView.resizeColumnWidths();
4158 noteTableView.resizeRowHeights();
4160 sortCol = Global.getSortColumn();
4161 sortOrder = Global.getSortOrder();
4162 noteTableView.proxyModel.blocked = true;
4163 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4164 noteTableView.proxyModel.blocked = false;
4167 noteTableView.load(false);
4168 scrollToCurrentGuid();
4170 // Sort order for the notebook has changed
4171 public void tableSortOrderChanged(Integer column, Integer order) {
4173 // Find what notebook (if any) is selected. We ignore stacks & the "All Notebooks".
4174 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4175 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4176 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4178 notebook = currentSelectedNotebook.text(2);
4179 conn.getNotebookTable().setSortOrder(notebook, column, order);
4183 //***************************************************************
4184 @SuppressWarnings("unused")
4185 private void evernoteLinkClick(String syncGuid, String locGuid) {
4187 if (conn.getNoteTable().guidExists(syncGuid)) {
4190 // If we didn't find it via the synchronized guid, look under the local guid
4191 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4192 // later synchronized (that causes the guid to change so we need to find the new one).
4193 if (conn.getNoteTable().guidExists(locGuid))
4196 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4199 openExternalEditor(guid);
4203 //If we've gotten this far, we can't find the note
4204 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4205 " seem to find that note."));
4207 //***************************************************************
4208 //***************************************************************
4209 //** External editor window functions
4210 //***************************************************************
4211 //***************************************************************
4212 private void listDoubleClick() {
4214 openExternalEditor(currentNoteGuid);
4216 private void openExternalEditor(String guid) {
4218 if (externalWindows.containsKey(guid)) {
4219 externalWindows.get(guid).raise();
4222 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4223 // We have a new external editor to create
4224 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4225 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4226 newBrowser.setWindowIcon(appIcon);
4227 externalWindows.put(guid, newBrowser);
4228 showEditorButtons(newBrowser.getBrowserWindow());
4229 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4230 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4231 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4232 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4233 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4234 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4235 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4236 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4238 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4239 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4240 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4244 @SuppressWarnings("unused")
4245 private void externalWindowTitleEdited(String guid, String text) {
4246 if (guid.equals(currentNoteGuid)) {
4247 browserWindow.setTitle(text);
4250 @SuppressWarnings({ "rawtypes", "unused" })
4251 private void externalWindowTagsEdited(String guid, List values) {
4252 StringBuffer line = new StringBuffer(100);
4253 for (int i=0; i<values.size(); i++) {
4255 line.append(Global.tagDelimeter+" ");
4256 line.append(values.get(i));
4258 if (guid.equals(currentNoteGuid)) {
4259 browserWindow.setTag(line.toString());
4262 @SuppressWarnings("unused")
4263 private void externalWindowClosing(String guid) {
4264 externalWindows.remove(guid);
4269 //***************************************************************
4270 //***************************************************************
4271 //** These functions deal with Note specific things
4272 //***************************************************************
4273 //***************************************************************
4274 @SuppressWarnings("unused")
4275 private void setNoteDirty() {
4276 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4278 // Find if the note is being edited externally. If it is, update it.
4279 if (externalWindows.containsKey(currentNoteGuid)) {
4280 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4281 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4282 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4283 window.getBrowserWindow().setContent(unicode);
4286 // If the note is dirty, then it is unsynchronized by default.
4290 // Set the note as dirty and check if its status is synchronized in the display table
4292 if (listManager.getNoteMetadata().containsKey(currentNoteGuid) &&
4293 listManager.getNoteMetadata().get(currentNoteGuid).isDirty()) {
4297 // If this wasn't already marked as unsynchronized, then we need to update the table
4298 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4299 // listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4300 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4301 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4302 if (modelIndex != null) {
4303 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4304 String tableGuid = (String)ix.values().toArray()[0];
4305 if (tableGuid.equals(currentNoteGuid)) {
4306 listManager.getNoteTableModel().proxyModel.setData(i, Global.noteTableSynchronizedPosition, "false");
4312 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4314 @SuppressWarnings("unused")
4315 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4316 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4317 QByteArray unicode = codec.fromUnicode(content);
4318 noteCache.remove(guid);
4319 noteCache.put(guid, unicode.toString());
4320 if (guid.equals(currentNoteGuid)) {
4322 browserWindow.setContent(unicode);
4325 thumbnailRunner.addWork("GENERATE "+ guid);
4326 saveNote(guid, browser);
4330 private void saveNote() {
4332 saveNote(currentNoteGuid, browserWindow);
4333 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4337 private void saveNote(String guid, BrowserWindow window) {
4338 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4341 logger.log(logger.EXTREME, "Saving to cache");
4342 QTextCodec codec = QTextCodec.codecForLocale();
4343 // QTextDecoder decoder = codec.makeDecoder();
4344 codec = QTextCodec.codecForName("UTF-8");
4345 QByteArray unicode = codec.fromUnicode(window.getContent());
4346 noteCache.put(guid, unicode.toString());
4348 logger.log(logger.EXTREME, "updating list manager");
4349 listManager.updateNoteContent(guid, window.getContent());
4350 logger.log(logger.EXTREME, "Updating title");
4351 listManager.updateNoteTitle(guid, window.getTitle());
4352 updateListDateChanged();
4354 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4355 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4356 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4357 currentNote = listManager.getNoteIndex().get(i);
4358 i = listManager.getNoteIndex().size();
4363 // Get a note from Evernote (and put it in the browser)
4364 private void refreshEvernoteNote(boolean reload) {
4365 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4367 if (Global.disableViewing) {
4368 browserWindow.setEnabled(false);
4373 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4375 Global.cryptCounter =0;
4377 browserWindow.setReadOnly(true);
4385 browserWindow.loadingData(true);
4387 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4388 if (currentNote == null)
4390 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4393 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4394 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4395 formatter.setNote(note, Global.pdfPreview());
4396 formatter.setHighlight(listManager.getEnSearch());
4398 if (!noteCache.containsKey(guid)) {
4399 js = new QByteArray();
4400 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4401 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4402 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>");
4403 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4404 js.append("<style> img { max-width:100%; }</style>");
4405 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4406 js.append("</head>");
4407 formatter.setNote(note, Global.pdfPreview());
4408 js.append(formatter.rebuildNoteHTML());
4409 js.append("</HTML>");
4410 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4411 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4412 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4413 // if (Global.enableHTMLEntitiesFix) {
4414 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4416 browser.setContent(js);
4417 noteCache.put(guid, js.toString());
4419 if (formatter.resourceError)
4420 resourceErrorMessage();
4421 if (formatter.formatError) {
4423 QMessageBox.information(this, tr("Error"),
4424 tr("NixNote had issues formatting this note." +
4425 " To protect your data this note is being marked as read-only."));
4428 readOnly = formatter.readOnly;
4429 inkNote = formatter.inkNote;
4431 readOnlyCache.put(guid, true);
4433 inkNoteCache.put(guid, true);
4435 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4436 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4437 js = new QByteArray(cachedContent);
4438 browser.setContent(js);
4439 if (readOnlyCache.containsKey(guid))
4441 if (inkNoteCache.containsKey(guid))
4444 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4445 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4447 if (readOnly || inkNote)
4448 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4450 browser.getBrowser().page().setContentEditable(true);
4451 browser.setReadOnly(readOnly);
4452 deleteButton.setEnabled(!readOnly);
4453 tagButton.setEnabled(!readOnly);
4454 menuBar.noteDelete.setEnabled(!readOnly);
4455 menuBar.noteTags.setEnabled(!readOnly);
4456 browser.setNote(note);
4458 if (note != null && note.getNotebookGuid() != null &&
4459 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4460 deleteButton.setEnabled(false);
4461 menuBar.notebookDeleteAction.setEnabled(false);
4463 deleteButton.setEnabled(true);
4464 menuBar.notebookDeleteAction.setEnabled(true);
4467 // Build a list of non-closed notebooks
4468 List<Notebook> nbooks = new ArrayList<Notebook>();
4469 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4470 boolean found=false;
4471 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4472 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4476 nbooks.add(listManager.getNotebookIndex().get(i));
4479 browser.setTitle(note.getTitle());
4480 browser.setTag(getTagNamesForNote(note));
4481 browser.setAuthor(note.getAttributes().getAuthor());
4483 browser.setAltered(note.getUpdated());
4484 browser.setCreation(note.getCreated());
4485 if (note.getAttributes().getSubjectDate() > 0)
4486 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4488 browser.setSubjectDate(note.getCreated());
4489 browser.setUrl(note.getAttributes().getSourceURL());
4491 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4492 List<Tag> tagList = tagFilter.getValidTags(note);
4493 browser.setAllTags(tagList);
4495 browser.setCurrentTags(note.getTagNames());
4499 browser.loadingData(false);
4500 if (thumbnailViewer.isActiveWindow())
4503 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4504 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4507 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4509 // Save a generated thumbnail
4510 private void toggleNoteInformation() {
4511 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4512 browserWindow.toggleInformation();
4513 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4514 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4515 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4517 // Listener triggered when a print button is pressed
4518 @SuppressWarnings("unused")
4519 private void printNote() {
4520 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4522 QPrintDialog dialog = new QPrintDialog();
4523 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4524 QPrinter printer = dialog.printer();
4525 browserWindow.getBrowser().print(printer);
4527 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4530 // Listener triggered when the email button is pressed
4531 @SuppressWarnings("unused")
4532 private void emailNote() {
4533 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4535 if (Desktop.isDesktopSupported()) {
4536 Desktop desktop = Desktop.getDesktop();
4538 String text2 = browserWindow.getContentsToEmail();
4539 QUrl url = new QUrl("mailto:");
4540 url.addQueryItem("subject", currentNote.getTitle());
4541 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4542 url.addQueryItem("body", text2);
4543 QDesktopServices.openUrl(url);
4547 if (desktop.isSupported(Desktop.Action.MAIL)) {
4548 URI uriMailTo = null;
4550 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4551 String text = browserWindow.getContentsToEmail();
4552 //text = "<b>" +text +"</b>";
4553 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4554 +"&BODY=" +text, null);
4555 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4556 +"&ATTACHMENT=d:/test.pdf", null);
4557 desktop.mail(uriMailTo);
4558 } catch (URISyntaxException e) {
4559 e.printStackTrace();
4560 } catch (IOException e) {
4561 e.printStackTrace();
4568 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4570 // Reindex all notes
4571 @SuppressWarnings("unused")
4572 private void fullReindex() {
4573 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4574 indexRunner.addWork("REINDEXALL");
4575 setMessage(tr("Database will be reindexed."));
4576 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4578 // Listener when a user wants to reindex a specific note
4579 @SuppressWarnings("unused")
4580 private void reindexNote() {
4581 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4582 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4583 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4585 if (selectedNotebookGUIDs.size() > 1)
4586 setMessage(tr("Notes will be reindexed."));
4588 setMessage(tr("Note will be reindexed."));
4589 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4592 @SuppressWarnings("unused")
4593 private void deleteNote() {
4594 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4595 if (currentNote == null)
4597 if (currentNoteGuid.equals(""))
4599 String title = null;
4600 if (selectedNoteGUIDs.size() == 1)
4601 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4603 // If we are deleting non-trash notes
4604 if (currentNote.isActive()) {
4605 if (Global.verifyDelete()) {
4607 if (selectedNoteGUIDs.size() > 1) {
4608 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4611 msg = new String(tr("Delete note \"") +title +"\"?");
4613 msg = new String(tr("Delete note selected note?"));
4615 if (QMessageBox.question(this, tr("Confirmation"), msg,
4616 QMessageBox.StandardButton.Yes,
4617 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4621 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4622 selectedNoteGUIDs.add(currentNoteGuid);
4623 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4624 listManager.deleteNote(selectedNoteGUIDs.get(i));
4627 // If we are deleting from the trash.
4628 if (Global.verifyDelete()) {
4630 if (selectedNoteGUIDs.size() > 1) {
4631 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4634 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4636 msg = new String(tr("Permanently delete note selected note?"));
4638 if (QMessageBox.question(this, "Confirmation", msg,
4639 QMessageBox.StandardButton.Yes,
4640 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4644 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4645 selectedNoteGUIDs.add(currentNoteGuid);
4646 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4647 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4648 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4649 if (modelIndex != null) {
4650 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4651 String tableGuid = (String)ix.values().toArray()[0];
4652 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4653 listManager.getNoteTableModel().removeRow(j);
4658 listManager.expungeNote(selectedNoteGUIDs.get(i));
4661 currentNoteGuid = "";
4662 listManager.loadNotesIndex();
4663 noteIndexUpdated(false);
4664 refreshEvernoteNote(true);
4665 scrollToGuid(currentNoteGuid);
4666 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4669 @SuppressWarnings("unused")
4670 private void addNote() {
4671 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4672 // browserWindow.setEnabled(true);
4673 browserWindow.setReadOnly(false);
4675 Calendar currentTime = new GregorianCalendar();
4676 StringBuffer noteString = new StringBuffer(100);
4677 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4678 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4681 if (Global.overrideDefaultFont()) {
4682 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4683 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4684 noteString.append("<br clear=\"none\" />\n");
4685 noteString.append("</span>\n</font>\n");
4687 noteString.append("<br clear=\"none\" />\n");
4688 noteString.append("</en-note>");
4690 Long l = new Long(currentTime.getTimeInMillis());
4691 String randint = new String(Long.toString(l));
4693 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4695 // for the first non-archived notebook. Finally, if nothing else we
4696 // pick the first notebook in the list.
4697 String notebook = null;
4698 listManager.getNotebookIndex().get(0).getGuid();
4699 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4700 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4701 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4702 notebook = currentSelectedNotebook.text(2);
4704 boolean found = false;
4705 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4706 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4707 boolean match = false;
4708 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4709 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4711 j = listManager.getArchiveNotebookIndex().size();
4715 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4716 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4718 // Now we have a list of good notebooks, so we can look for the default
4720 for (int i=0; i<goodNotebooks.size(); i++) {
4721 if (goodNotebooks.get(i).isDefaultNotebook()) {
4722 notebook = goodNotebooks.get(i).getGuid();
4724 i = goodNotebooks.size();
4728 if (goodNotebooks.size() > 0 && !found)
4729 notebook = goodNotebooks.get(0).getGuid();
4732 notebook = listManager.getNotebookIndex().get(0).getGuid();
4735 Note newNote = new Note();
4736 newNote.setUpdateSequenceNum(0);
4737 newNote.setGuid(randint);
4738 newNote.setNotebookGuid(notebook);
4739 newNote.setTitle("Untitled Note");
4740 newNote.setContent(noteString.toString());
4741 newNote.setDeleted(0);
4742 newNote.setCreated(System.currentTimeMillis());
4743 newNote.setUpdated(System.currentTimeMillis());
4744 newNote.setActive(true);
4745 NoteAttributes na = new NoteAttributes();
4746 na.setLatitude(0.0);
4747 na.setLongitude(0.0);
4748 na.setAltitude(0.0);
4749 newNote.setAttributes(new NoteAttributes());
4750 newNote.setTagGuids(new ArrayList<String>());
4751 newNote.setTagNames(new ArrayList<String>());
4753 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4754 if (Global.newNoteWithSelectedTags()) {
4755 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4756 QTreeWidgetItem currentSelection;
4757 for (int i=0; i<selections.size(); i++) {
4758 currentSelection = selections.get(i);
4759 newNote.getTagGuids().add(currentSelection.text(2));
4760 newNote.getTagNames().add(currentSelection.text(0));
4764 conn.getNoteTable().addNote(newNote, true);
4765 NoteMetadata metadata = new NoteMetadata();
4766 metadata.setGuid(newNote.getGuid());
4767 metadata.setDirty(true);
4768 listManager.addNote(newNote, metadata);
4769 // noteTableView.insertRow(newNote, true, -1);
4771 currentNote = newNote;
4772 currentNoteGuid = currentNote.getGuid();
4773 noteTableView.clearSelection();
4774 refreshEvernoteNote(true);
4775 listManager.countNotebookResults(listManager.getNoteIndex());
4776 browserWindow.titleLabel.setFocus();
4777 browserWindow.titleLabel.selectAll();
4778 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4780 // If the window is hidden, then we want to popup this in an external window &
4784 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4786 // Restore a note from the trash;
4787 @SuppressWarnings("unused")
4788 private void restoreNote() {
4790 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4791 selectedNoteGUIDs.add(currentNoteGuid);
4792 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4793 listManager.restoreNote(selectedNoteGUIDs.get(i));
4795 currentNoteGuid = "";
4796 listManager.loadNotesIndex();
4797 noteIndexUpdated(false);
4800 // Search a note for specific txt
4801 @SuppressWarnings("unused")
4802 private void findText() {
4804 find.setFocusOnTextField();
4806 @SuppressWarnings("unused")
4807 private void doFindText() {
4808 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4811 @SuppressWarnings("unused")
4812 private void updateNoteTitle(String guid, String title) {
4813 listManager.setNoteSynchronized(guid, false);
4815 // Signal received that note content has changed. Normally we just need the guid to remove
4816 // it from the cache.
4817 @SuppressWarnings("unused")
4818 private void invalidateNoteCache(String guid, String content) {
4819 noteCache.remove(guid);
4820 refreshEvernoteNote(true);
4822 // Signal received that a note guid has changed
4823 @SuppressWarnings("unused")
4824 private void noteGuidChanged(String oldGuid, String newGuid) {
4825 if (noteCache.containsKey(oldGuid)) {
4826 if (!oldGuid.equals(currentNoteGuid)) {
4827 String cache = noteCache.get(oldGuid);
4828 noteCache.put(newGuid, cache);
4829 noteCache.remove(oldGuid);
4831 noteCache.remove(oldGuid);
4832 noteCache.put(newGuid, browserWindow.getContent());
4836 listManager.updateNoteGuid(oldGuid, newGuid, false);
4837 if (currentNoteGuid.equals(oldGuid)) {
4838 if (currentNote != null)
4839 currentNote.setGuid(newGuid);
4840 currentNoteGuid = newGuid;
4843 if (externalWindows.containsKey(oldGuid)) {
4844 ExternalBrowse b = externalWindows.get(oldGuid);
4845 externalWindows.remove(oldGuid);
4846 b.getBrowserWindow().getNote().setGuid(newGuid);
4847 externalWindows.put(newGuid, b);
4850 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4851 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4852 noteTableView.proxyModel.addGuid(newGuid, listManager.getNoteMetadata().get(newGuid));
4853 i=listManager.getNoteIndex().size();
4857 if (listManager.getNoteTableModel().metaData.containsKey(oldGuid)) {
4858 NoteMetadata meta = listManager.getNoteTableModel().metaData.get(oldGuid);
4859 listManager.getNoteTableModel().metaData.put(newGuid, meta);
4860 listManager.getNoteTableModel().metaData.remove(oldGuid);
4864 // Toggle the note editor button bar
4865 private void toggleEditorButtonBar() {
4866 if (browserWindow.buttonsVisible) {
4867 browserWindow.hideButtons();
4868 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4869 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4871 browserWindow.buttonsVisible = true;
4872 showEditorButtons(browserWindow);
4874 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4876 // Show editor buttons
4877 private void showEditorButtons(BrowserWindow browser) {
4878 browser.buttonLayout.setVisible(true);
4879 browser.undoAction.setVisible(false);
4881 browser.undoButton.setVisible(false);
4883 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4884 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4885 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4886 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4887 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4888 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4889 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4890 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4891 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4892 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4893 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4894 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4895 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4896 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4897 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4898 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4899 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4900 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4901 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4902 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4903 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4904 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4905 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4907 private void duplicateNote(String guid) {
4909 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4910 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4911 oldNote.setContent(conn.getNoteTable().getNoteContentNoUTFConversion(guid));
4912 oldNote.setResources(resList);
4913 duplicateNote(oldNote);
4915 private void duplicateNote(Note oldNote) {
4917 // Now that we have a good notebook guid, we need to move the conflicting note
4918 // to the local notebook
4919 Calendar currentTime = new GregorianCalendar();
4920 Long l = new Long(currentTime.getTimeInMillis());
4921 String newGuid = new String(Long.toString(l));
4923 // Note newNote = oldNote.deepCopy();
4924 Note newNote = (Note)Global.deepCopy(oldNote);
4925 newNote.setUpdateSequenceNum(0);
4926 newNote.setGuid(newGuid);
4927 newNote.setDeleted(0);
4928 newNote.setActive(true);
4931 List<String> tagNames = new ArrayList<String>();
4932 List<String> tagGuids = new ArrayList<String>();;
4933 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4934 tagNames.add(oldNote.getTagNames().get(i));
4935 tagGuids.add(oldNote.getTagGuids().get(i));
4938 // Sort note Tags to make them look nice
4939 for (int i=0; i<tagNames.size()-1; i++) {
4940 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4941 String n1 = tagNames.get(i);
4942 String n2 = tagNames.get(i+1);
4943 tagNames.set(i, n2);
4944 tagNames.set(i+1, n1);
4947 newNote.setTagGuids(tagGuids);
4948 newNote.setTagNames(tagNames);
4950 // Add tag guids to note
4953 // Duplicate resources
4954 List<Resource> resList = oldNote.getResources();
4955 if (resList == null)
4956 resList = new ArrayList<Resource>();
4958 for (int i=0; i<resList.size(); i++) {
4960 while (l == prevGuid) {
4961 currentTime = new GregorianCalendar();
4962 l = new Long(currentTime.getTimeInMillis());
4965 String newResGuid = new String(Long.toString(l));
4966 resList.get(i).setNoteGuid(newGuid);
4967 resList.get(i).setGuid(newResGuid);
4968 resList.get(i).setUpdateSequenceNum(0);
4969 resList.get(i).setActive(true);
4970 conn.getNoteTable().noteResourceTable.saveNoteResource(
4971 (Resource)Global.deepCopy(resList.get(i)), true);
4973 newNote.setResources(resList);
4975 // Add note to the database
4976 conn.getNoteTable().addNote(newNote, true);
4977 NoteMetadata metaData = new NoteMetadata();
4978 NoteMetadata oldMeta = listManager.getNoteMetadata().get(oldNote.getGuid());
4979 metaData.copy(oldMeta);
4980 metaData.setGuid(newNote.getGuid());
4981 listManager.addNote(newNote, metaData);
4982 noteTableView.insertRow(newNote, metaData, true, -1);
4983 currentNoteGuid = newNote.getGuid();
4984 currentNote = newNote;
4985 refreshEvernoteNote(true);
4986 listManager.countNotebookResults(listManager.getNoteIndex());
4990 @SuppressWarnings("unused")
4991 private void allNotes() {
4992 clearAttributeFilter();
4993 clearNotebookFilter();
4994 clearSavedSearchFilter();
4997 searchField.clear();
4998 if (Global.mimicEvernoteInterface) {
4999 notebookTree.selectGuid("");
5001 notebookTreeSelection();
5002 refreshEvernoteNote(true);
5005 @SuppressWarnings("unused")
5006 private void mergeNotes() {
5007 logger.log(logger.HIGH, "Merging notes");
5010 String masterGuid = null;
5011 List<String> sources = new ArrayList<String>();
5013 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
5014 int r = noteTableView.selectionModel().selectedRows().get(i).row();
5015 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
5016 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5018 masterGuid = (String)ix.values().toArray()[0];
5020 sources.add((String)ix.values().toArray()[0]);
5023 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
5024 logger.log(logger.EXTREME, "Children count: "+sources.size());
5025 mergeNoteContents(masterGuid, sources);
5026 currentNoteGuid = masterGuid;
5027 noteIndexUpdated(false);
5028 refreshEvernoteNote(true);
5031 private void mergeNoteContents(String targetGuid, List<String> sources) {
5032 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
5033 String newContent = target.getContent();
5034 newContent = newContent.replace("</en-note>", "<br></br>");
5036 for (int i=0; i<sources.size(); i++) {
5037 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
5038 if (source.isSetTitle()) {
5039 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
5041 String sourceContent = source.getContent();
5042 logger.log(logger.EXTREME, "Merging contents into note");
5043 logger.log(logger.EXTREME, sourceContent);
5044 logger.log(logger.EXTREME, "End of content");
5045 int startOfNote = sourceContent.indexOf("<en-note>");
5046 sourceContent = sourceContent.substring(startOfNote+9);
5047 int endOfNote = sourceContent.indexOf("</en-note>");
5048 sourceContent = sourceContent.substring(0,endOfNote);
5049 newContent = newContent + sourceContent;
5050 logger.log(logger.EXTREME, "New note content");
5051 logger.log(logger.EXTREME, newContent);
5052 logger.log(logger.EXTREME, "End of content");
5053 for (int j=0; j<source.getResourcesSize(); j++) {
5054 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
5055 Resource r = source.getResources().get(j);
5056 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
5058 Calendar currentTime = new GregorianCalendar();
5059 Long l = new Long(currentTime.getTimeInMillis());
5063 while (l == prevGuid) {
5064 currentTime = new GregorianCalendar();
5065 l = new Long(currentTime.getTimeInMillis());
5067 String newResGuid = new String(Long.toString(l));
5068 newRes.setNoteGuid(targetGuid);
5069 newRes.setGuid(newResGuid);
5070 newRes.setUpdateSequenceNum(0);
5071 newRes.setActive(true);
5072 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5075 logger.log(logger.EXTREME, "Updating note");
5076 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5077 for (int i=0; i<sources.size(); i++) {
5078 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5079 listManager.deleteNote(sources.get(i));
5081 logger.log(logger.EXTREME, "Exiting merge note");
5083 // A resource within a note has had a guid change
5084 @SuppressWarnings("unused")
5085 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5086 if (oldGuid != null && !oldGuid.equals(newGuid))
5087 Global.resourceMap.put(oldGuid, newGuid);
5089 // View a thumbnail of the note
5090 public void thumbnailView() {
5092 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5093 QFile thumbnail = new QFile(thumbnailName);
5094 if (!thumbnail.exists()) {
5096 QImage img = new QImage();
5097 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5098 thumbnailViewer.setThumbnail(img);
5100 thumbnailViewer.setThumbnail(thumbnailName);
5101 if (!thumbnailViewer.isVisible())
5102 thumbnailViewer.showFullScreen();
5104 // An error happened while saving a note. Inform the user
5105 @SuppressWarnings("unused")
5106 private void saveRunnerError(String guid, String msg) {
5108 String title = "*Unknown*";
5109 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5110 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5111 title = listManager.getMasterNoteIndex().get(i).getTitle();
5112 i=listManager.getMasterNoteIndex().size();
5115 msg = tr("An error has happened while saving the note \"") +title+
5116 tr("\".\n\nThis is probably due to a document that is too complex for NixNote to process. "+
5117 "As a result, changes to the note may not be saved properly in the database."+
5118 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5119 "\nbe lost. Please review the note to recover any critical data before restarting.");
5121 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5124 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5125 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5126 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5127 // Find an idle preview object
5128 for (int i=0; i<thumbGenerators.size(); i++) {
5129 if (thumbGenerators.get(i).mutex.tryLock()) {
5130 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5131 thumbGenerators.get(i).loadContent(guid, html, zoom);
5135 if (thumbGenerators.size() >= 1) {
5136 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5140 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5141 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5142 thumbGenerators.add(preview);
5144 if (preview.mutex.tryLock()) {
5145 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5146 preview.loadContent(guid, html, zoom);
5148 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5153 //**********************************************************
5154 //**********************************************************
5155 //* Online user actions
5156 //**********************************************************
5157 //**********************************************************
5158 private void setupOnlineMenu() {
5159 if (!Global.isConnected) {
5160 menuBar.noteOnlineHistoryAction.setEnabled(false);
5161 menuBar.selectiveSyncAction.setEnabled(false);
5164 menuBar.noteOnlineHistoryAction.setEnabled(true);
5165 menuBar.selectiveSyncAction.setEnabled(true);
5168 @SuppressWarnings("unused")
5169 private void viewNoteHistory() {
5170 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5172 if (currentNote.getUpdateSequenceNum() == 0) {
5173 setMessage(tr("Note has never been synchronized."));
5174 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5178 setMessage(tr("Getting Note History"));
5180 Note currentOnlineNote = null;
5183 if (Global.isPremium())
5184 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5186 versions = new ArrayList<NoteVersionId>();
5187 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5188 } catch (EDAMUserException e) {
5189 setMessage("EDAMUserException: " +e.getMessage());
5191 } catch (EDAMSystemException e) {
5192 setMessage("EDAMSystemException: " +e.getMessage());
5194 } catch (EDAMNotFoundException e) {
5195 setMessage(tr("Note not found on server."));
5196 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5198 } catch (TException e) {
5199 setMessage("EDAMTransactionException: " +e.getMessage());
5203 // If we've gotten this far, we have a good note.
5204 if (historyWindow == null) {
5205 historyWindow = new OnlineNoteHistory(logger, conn);
5206 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5207 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5208 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5210 historyWindow.historyCombo.clear();
5212 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5213 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5215 historyWindow.setCurrent(isDirty);
5217 loadHistoryWindowContent(currentOnlineNote);
5218 historyWindow.load(versions);
5219 setMessage(tr("History retrieved"));
5221 historyWindow.exec();
5223 private Note reloadHistoryWindow(String selection) {
5225 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5226 String dateTimeFormat = new String(fmt);
5227 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5231 for (int i=0; i<versions.size(); i++) {
5232 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5233 if (versionDate.toString().equals(selection))
5237 if (index > -1 || selection.indexOf("Current") > -1) {
5238 Note historyNote = null;
5241 usn = versions.get(index).getUpdateSequenceNum();
5242 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5244 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5245 } catch (EDAMUserException e) {
5246 setMessage("EDAMUserException: " +e.getMessage());
5249 } catch (EDAMSystemException e) {
5250 setMessage("EDAMSystemException: " +e.getMessage());
5253 } catch (EDAMNotFoundException e) {
5254 setMessage("EDAMNotFoundException: " +e.getMessage());
5257 } catch (TException e) {
5258 setMessage("EDAMTransactionException: " +e.getMessage());
5264 if (historyNote != null)
5265 historyWindow.setContent(historyNote);
5271 private void loadHistoryWindowContent(Note note) {
5272 note.setUpdateSequenceNum(0);
5273 historyWindow.setContent(note);
5275 @SuppressWarnings("unused")
5276 private void restoreHistoryNoteAsNew() {
5277 setMessage(tr("Restoring as new note."));
5278 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5279 setMessage(tr("Note has been restored as a new note."));
5281 @SuppressWarnings("unused")
5282 private void restoreHistoryNote() {
5283 setMessage(tr("Restoring note."));
5284 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5285 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5288 for (int i=0; i<n.getResourcesSize(); i++) {
5289 n.getResources().get(i).setActive(true);
5290 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5292 NoteMetadata metadata = new NoteMetadata();
5293 metadata.setGuid(n.getGuid());
5294 listManager.addNote(n, metadata);
5295 conn.getNoteTable().addNote(n, true);
5296 refreshEvernoteNote(true);
5297 setMessage(tr("Note has been restored."));
5299 @SuppressWarnings("unused")
5300 private void setupSelectiveSync() {
5302 // Get a list of valid notebooks
5303 List<Notebook> notebooks = null;
5304 List<Tag> tags = null;
5305 List<LinkedNotebook> linkedNotebooks = null;
5307 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5308 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5309 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5310 } catch (EDAMUserException e) {
5311 setMessage("EDAMUserException: " +e.getMessage());
5313 } catch (EDAMSystemException e) {
5314 setMessage("EDAMSystemException: " +e.getMessage());
5316 } catch (TException e) {
5317 setMessage("EDAMTransactionException: " +e.getMessage());
5319 } catch (EDAMNotFoundException e) {
5320 setMessage("EDAMNotFoundException: " +e.getMessage());
5324 // Split up notebooks into synchronized & non-synchronized
5325 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5326 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5328 for (int i=notebooks.size()-1; i>=0; i--) {
5329 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5330 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5331 ignoredBooks.add(notebooks.get(i));
5332 j=dbIgnoredNotebooks.size();
5337 // split up tags into synchronized & non-synchronized
5338 List<Tag> ignoredTags = new ArrayList<Tag>();
5339 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5341 for (int i=tags.size()-1; i>=0; i--) {
5342 for (int j=0; j<dbIgnoredTags.size(); j++) {
5343 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5344 ignoredTags.add(tags.get(i));
5345 j=dbIgnoredTags.size();
5350 // split up linked notebooks into synchronized & non-synchronized
5351 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5352 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5353 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5354 String notebookGuid = linkedNotebooks.get(i).getGuid();
5355 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5356 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5357 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5358 j=dbIgnoredLinkedNotebooks.size();
5363 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5365 if (!ignore.okClicked())
5370 // Clear out old notebooks & add the new ones
5371 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5372 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5373 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5376 List<String> newNotebooks = new ArrayList<String>();
5377 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5378 String text = ignore.getIgnoredBookList().takeItem(i).text();
5379 for (int j=0; j<notebooks.size(); j++) {
5380 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5381 Notebook n = notebooks.get(j);
5382 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5384 newNotebooks.add(n.getGuid());
5389 // Clear out old tags & add new ones
5390 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5391 for (int i=0; i<oldIgnoreTags.size(); i++) {
5392 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5395 List<String> newTags = new ArrayList<String>();
5396 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5397 String text = ignore.getIgnoredTagList().takeItem(i).text();
5398 for (int j=0; j<tags.size(); j++) {
5399 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5400 Tag t = tags.get(j);
5401 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5402 newTags.add(t.getGuid());
5408 // Clear out old tags & add new ones
5409 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5410 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5411 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5414 List<String> newLinked = new ArrayList<String>();
5415 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5416 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5417 for (int j=0; j<linkedNotebooks.size(); j++) {
5418 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5419 LinkedNotebook t = linkedNotebooks.get(j);
5420 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5421 newLinked.add(t.getGuid());
5422 j=linkedNotebooks.size();
5427 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5433 //**********************************************************
5434 //**********************************************************
5435 //* XML Modifying methods
5436 //**********************************************************
5437 //**********************************************************
5438 // An error has happended fetching a resource. let the user know
5439 private void resourceErrorMessage() {
5443 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5444 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5445 "In a perfect world this wouldn't happen, but it has.\n" +
5446 "It is embarasing when a program like me, designed to save all your\n"+
5447 "precious data, has a problem finding data.\n\n" +
5448 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5449 "In the mean time, I'm not going to let you make changes to this note.\n" +
5450 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5451 "this note on the Evernote servers. Sorry."+
5452 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5454 browserWindow.setReadOnly(true);
5461 //**********************************************************
5462 //**********************************************************
5464 //**********************************************************
5465 //**********************************************************
5466 // We should now do a sync with Evernote
5467 private void syncTimer() {
5468 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5469 syncRunner.syncNeeded = true;
5470 syncRunner.disableUploads = Global.disableUploads;
5472 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5474 private void syncStart() {
5475 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5477 if (!syncRunning && Global.isConnected) {
5478 syncRunner.setConnected(true);
5479 syncRunner.setKeepRunning(Global.keepRunning);
5480 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5482 if (syncThreadsReady > 0) {
5483 thumbnailRunner.interrupt = true;
5484 saveNoteIndexWidth();
5485 saveNoteColumnPositions();
5486 if (syncRunner.addWork("SYNC")) {
5488 syncRunner.syncNeeded = true;
5493 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5495 @SuppressWarnings("unused")
5496 private void syncThreadComplete(Boolean refreshNeeded) {
5497 setMessage(tr("Finalizing Synchronization"));
5499 syncRunning = false;
5500 syncRunner.syncNeeded = false;
5501 synchronizeAnimationTimer.stop();
5502 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5504 if (currentNote == null) {
5505 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5507 listManager.refreshNoteMetadata();
5508 noteIndexUpdated(true);
5509 noteTableView.selectionModel().blockSignals(true);
5510 scrollToGuid(currentNoteGuid);
5511 noteTableView.selectionModel().blockSignals(false);
5512 refreshEvernoteNote(false);
5513 scrollToGuid(currentNoteGuid);
5516 // Check to see if there were any shared notebook errors
5517 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5518 String guid = syncRunner.errorSharedNotebooks.get(0);
5519 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5520 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5521 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5523 if (syncDialog.okPressed()) {
5524 if (syncDialog.doNothing.isChecked()) {
5525 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5528 if (syncDialog.deleteNotebook.isChecked()) {
5529 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5530 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5531 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5532 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5540 // Finalize the synchronization
5541 if (!syncRunner.error)
5542 setMessage(tr("Synchronization Complete"));
5544 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5545 logger.log(logger.MEDIUM, "Sync complete.");
5547 public void saveUploadAmount(long t) {
5548 Global.saveUploadAmount(t);
5550 public void saveUserInformation(User user) {
5551 Global.saveUserInformation(user);
5553 public void saveEvernoteUpdateCount(int i) {
5554 Global.saveEvernoteUpdateCount(i);
5556 public void refreshLists() {
5557 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5559 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5560 tagIndexUpdated(true);
5561 notebookIndexUpdated();
5562 savedSearchIndexUpdated();
5563 listManager.loadNotesIndex();
5565 noteTableView.selectionModel().blockSignals(true);
5566 noteIndexUpdated(true);
5567 noteTableView.selectionModel().blockSignals(false);
5568 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5572 @SuppressWarnings("unused")
5573 private void authTimer() {
5574 Calendar cal = Calendar.getInstance();
5576 // If we are not connected let's get out of here
5577 if (!Global.isConnected)
5580 // If this is the first time through, then we need to set this
5581 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5582 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5584 // long now = new Date().getTime();
5585 // if (now > Global.authRefreshTime && Global.isConnected) {
5586 syncRunner.authRefreshNeeded = true;
5590 @SuppressWarnings("unused")
5591 private void authRefreshComplete(boolean goodSync) {
5592 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5593 Global.isConnected = syncRunner.isConnected;
5595 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5596 authTimer.start(1000*60*15);
5597 logger.log(logger.LOW, "Authentication token has been renewed");
5598 // setMessage("Authentication token has been renewed.");
5600 authTimer.start(1000*60*5);
5601 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5602 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5604 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5608 @SuppressWarnings("unused")
5609 private synchronized void indexTimer() {
5610 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5613 if (!indexDisabled && indexRunner.idle) {
5614 thumbnailRunner.interrupt = true;
5615 indexRunner.addWork("SCAN");
5617 logger.log(logger.EXTREME, "Leaving NixNote index timer");
5620 @SuppressWarnings("unused")
5621 private void indexStarted() {
5622 setMessage(tr("Indexing notes"));
5624 @SuppressWarnings("unused")
5625 private void indexComplete() {
5626 setMessage(tr("Index complete"));
5628 @SuppressWarnings("unused")
5629 private synchronized void toggleNoteIndexing() {
5630 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5631 indexDisabled = !indexDisabled;
5633 setMessage(tr("Indexing is now enabled."));
5635 setMessage(tr("Indexing is now disabled."));
5636 menuBar.disableIndexing.setChecked(indexDisabled);
5637 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5640 @SuppressWarnings("unused")
5641 private void threadMonitorCheck() {
5646 alive = listManager.threadCheck(Global.tagCounterThreadId);
5649 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5650 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died. I recommend "+
5651 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5652 disableTagThreadCheck = true;
5657 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5659 notebookThreadDeadCount++;
5660 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5661 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died. I recommend "+
5662 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5663 disableNotebookThreadCheck=true;
5666 notebookThreadDeadCount=0;
5668 alive = listManager.threadCheck(Global.trashCounterThreadId);
5671 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5672 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died. I recommend "+
5673 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5674 disableTrashThreadCheck = true;
5679 alive = listManager.threadCheck(Global.saveThreadId);
5681 saveThreadDeadCount++;
5682 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5683 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died. I recommend "+
5684 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5685 disableSaveThreadCheck = true;
5688 saveThreadDeadCount=0;
5690 if (!syncThread.isAlive()) {
5691 syncThreadDeadCount++;
5692 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5693 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died. I recommend "+
5694 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5695 disableSyncThreadCheck = true;
5698 syncThreadDeadCount=0;
5700 if (!indexThread.isAlive()) {
5701 indexThreadDeadCount++;
5702 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5703 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died. I recommend "+
5704 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5705 disableIndexThreadCheck = true;
5708 indexThreadDeadCount=0;
5713 private void thumbnailTimer() {
5714 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5715 thumbnailRunner.addWork("SCAN");
5719 //**************************************************
5720 //* Backup & Restore
5721 //**************************************************
5722 @SuppressWarnings("unused")
5723 private void databaseBackup() {
5724 QFileDialog fd = new QFileDialog(this);
5725 fd.setFileMode(FileMode.AnyFile);
5726 fd.setConfirmOverwrite(true);
5727 fd.setWindowTitle(tr("Backup Database"));
5728 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5729 fd.setAcceptMode(AcceptMode.AcceptSave);
5730 if (saveLastPath == null || saveLastPath.equals(""))
5731 fd.setDirectory(System.getProperty("user.home"));
5733 fd.setDirectory(saveLastPath);
5734 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5740 saveLastPath = fd.selectedFiles().get(0);
5741 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5742 setMessage(tr("Backing up database"));
5744 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5746 ExportData noteWriter = new ExportData(conn, true);
5747 String fileName = fd.selectedFiles().get(0);
5749 if (!fileName.endsWith(".nnex"))
5750 fileName = fileName +".nnex";
5751 noteWriter.exportData(fileName);
5752 setMessage(tr("Database backup completed."));
5757 @SuppressWarnings("unused")
5758 private void databaseRestore() {
5759 if (QMessageBox.question(this, tr("Confirmation"),
5760 tr("This is used to restore a database from backups.\n" +
5761 "It is HIGHLY recommened that this only be used to populate\n" +
5762 "an empty database. Restoring into a database that\n already has data" +
5763 " can cause problems.\n\nAre you sure you want to continue?"),
5764 QMessageBox.StandardButton.Yes,
5765 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5770 QFileDialog fd = new QFileDialog(this);
5771 fd.setFileMode(FileMode.ExistingFile);
5772 fd.setConfirmOverwrite(true);
5773 fd.setWindowTitle(tr("Restore Database"));
5774 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5775 fd.setAcceptMode(AcceptMode.AcceptOpen);
5776 if (saveLastPath == null || saveLastPath.equals(""))
5777 fd.setDirectory(System.getProperty("user.home"));
5779 fd.setDirectory(saveLastPath);
5780 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5786 saveLastPath = fd.selectedFiles().get(0);
5787 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5789 setMessage(tr("Restoring database"));
5790 ImportData noteReader = new ImportData(conn, true);
5791 noteReader.importData(fd.selectedFiles().get(0));
5793 if (noteReader.lastError != 0) {
5794 setMessage(noteReader.getErrorMessage());
5795 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5800 listManager.loadNoteTitleColors();
5802 refreshEvernoteNote(true);
5803 setMessage(tr("Database has been restored."));
5806 @SuppressWarnings("unused")
5807 private void exportNotes() {
5808 QFileDialog fd = new QFileDialog(this);
5809 fd.setFileMode(FileMode.AnyFile);
5810 fd.setConfirmOverwrite(true);
5811 fd.setWindowTitle(tr("Backup Database"));
5812 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5813 fd.setAcceptMode(AcceptMode.AcceptSave);
5814 fd.setDirectory(System.getProperty("user.home"));
5815 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5821 setMessage(tr("Exporting Notes"));
5824 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5825 selectedNoteGUIDs.add(currentNoteGuid);
5827 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5828 String fileName = fd.selectedFiles().get(0);
5830 if (!fileName.endsWith(".nnex"))
5831 fileName = fileName +".nnex";
5832 noteWriter.exportData(fileName);
5833 setMessage(tr("Export completed."));
5839 @SuppressWarnings("unused")
5840 private void importNotes() {
5841 QFileDialog fd = new QFileDialog(this);
5842 fd.setFileMode(FileMode.ExistingFile);
5843 fd.setConfirmOverwrite(true);
5844 fd.setWindowTitle(tr("Import Notes"));
5845 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5846 fd.setAcceptMode(AcceptMode.AcceptOpen);
5847 if (saveLastPath == null || saveLastPath.equals(""))
5848 fd.setDirectory(System.getProperty("user.home"));
5850 fd.setDirectory(saveLastPath);
5851 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5857 setMessage(tr("Importing Notes"));
5860 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5861 selectedNoteGUIDs.add(currentNoteGuid);
5863 ImportData noteReader = new ImportData(conn, false);
5864 String fileName = fd.selectedFiles().get(0);
5865 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5867 if (!fileName.endsWith(".nnex"))
5868 fileName = fileName +".nnex";
5869 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5870 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5872 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5874 noteReader.importData(fileName);
5876 if (noteReader.lastError != 0) {
5877 setMessage(noteReader.getErrorMessage());
5878 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5883 listManager.loadNoteTitleColors();
5885 refreshEvernoteNote(false);
5886 setMessage(tr("Notes have been imported."));
5889 setMessage(tr("Import completed."));
5896 //**************************************************
5897 //* Duplicate a note
5898 //**************************************************
5899 @SuppressWarnings("unused")
5900 private void duplicateNote() {
5902 duplicateNote(currentNoteGuid);
5905 //**************************************************
5906 //* Action from when a user clicks Copy As URL
5907 //**************************************************
5908 @SuppressWarnings("unused")
5909 private void copyAsUrlClicked() {
5910 QClipboard clipboard = QApplication.clipboard();
5911 QMimeData mime = new QMimeData();
5913 mime.setText(currentNoteGuid);
5914 List<QUrl> urls = new ArrayList<QUrl>();
5916 // Start building the URL
5917 User user = Global.getUserInformation();
5919 // Check that we have everything we need
5920 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
5921 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
5923 if (!warning.neverSynchronize())
5926 Global.setBypassSynchronizationWarning(true);
5927 user.setShardId("s0");
5933 // Start building a list of URLs based upon the selected notes
5934 noteTableView.showColumn(Global.noteTableGuidPosition);
5936 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
5937 if (!Global.isColumnVisible("guid"))
5938 noteTableView.hideColumn(Global.noteTableGuidPosition);
5940 // Check that the note is either synchronized, or in a local notebook
5941 for (int i=0; i<selections.size(); i++) {
5943 int row = selections.get(i).row();
5944 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5945 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5946 String selectedGuid = (String)ix.values().toArray()[0];
5948 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5949 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
5950 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
5951 "new notes to a local notebook."));
5956 // Start building the URLs
5957 for (int i=0; i<selections.size(); i++) {
5959 int row = selections.get(i).row();
5960 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5961 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5962 String selectedGuid = (String)ix.values().toArray()[0];
5963 mime.setText(selectedGuid);
5967 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5968 if (selectedNote.getUpdateSequenceNum() > 0) {
5972 gid = "00000000-0000-0000-0000-000000000000";
5975 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
5977 urls.add(new QUrl(url));
5980 clipboard.setMimeData(mime);
5984 //**************************************************
5986 //**************************************************
5987 public void setupFolderImports() {
5988 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5990 if (importKeepWatcher == null)
5991 importKeepWatcher = new QFileSystemWatcher();
5992 if (importDeleteWatcher == null) {
5993 importDeleteWatcher = new QFileSystemWatcher();
5994 for (int i=0; i<records.size(); i++) {
5995 if (!records.get(i).keep)
5996 folderImportDelete(records.get(i).folder);
6002 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
6003 for (int i=0; i<records.size(); i++) {
6004 if (records.get(i).keep)
6005 importKeepWatcher.addPath(records.get(i).folder);
6007 importDeleteWatcher.addPath(records.get(i).folder);
6010 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
6011 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
6013 // Look at the files already there so we don't import them again if a new file is created
6014 if (importedFiles == null) {
6015 importedFiles = new ArrayList<String>();
6016 for (int j=0; j<records.size(); j++) {
6017 QDir dir = new QDir(records.get(j).folder);
6018 List<QFileInfo> list = dir.entryInfoList();
6019 for (int k=0; k<list.size(); k++) {
6020 if (list.get(k).isFile())
6021 importedFiles.add(list.get(k).absoluteFilePath());
6026 public void folderImport() {
6027 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
6028 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
6030 if (!dialog.okClicked())
6033 // We have some sort of update.
6034 if (importKeepWatcher.directories().size() > 0)
6035 importKeepWatcher.removePaths(importKeepWatcher.directories());
6036 if (importDeleteWatcher.directories().size() > 0)
6037 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
6039 conn.getWatchFolderTable().expungeAll();
6040 // Start building from the table
6041 for (int i=0; i<dialog.table.rowCount(); i++) {
6042 QTableWidgetItem item = dialog.table.item(i, 0);
6043 String dir = item.text();
6044 item = dialog.table.item(i, 1);
6045 String notebook = item.text();
6046 item = dialog.table.item(i, 2);
6048 if (item.text().equalsIgnoreCase("Keep"))
6053 String guid = conn.getNotebookTable().findNotebookByName(notebook);
6054 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
6056 setupFolderImports();
6059 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
6061 String whichOS = System.getProperty("os.name");
6062 if (whichOS.contains("Windows"))
6063 dirName = dirName.replace('/','\\');
6065 FileImporter importer = new FileImporter(logger, conn);
6067 QDir dir = new QDir(dirName);
6068 List<QFileInfo> list = dir.entryInfoList();
6069 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6071 for (int i=0; i<list.size(); i++){
6073 boolean redundant = false;
6074 // Check if we've already imported this one or if it existed before
6075 for (int j=0; j<importedFiles.size(); j++) {
6076 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6081 importer.setFileInfo(list.get(i));
6082 importer.setFileName(list.get(i).absoluteFilePath());
6085 if (list.get(i).isFile() && importer.isValidType()) {
6087 if (!importer.importFile()) {
6088 // If we can't get to the file, it is probably locked. We'll try again later.
6089 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6090 importFilesKeep.add(list.get(i).absoluteFilePath());
6094 Note newNote = importer.getNote();
6095 newNote.setNotebookGuid(notebook);
6096 newNote.setTitle(dir.at(i));
6097 NoteMetadata metadata = new NoteMetadata();
6098 metadata.setDirty(true);
6099 metadata.setGuid(newNote.getGuid());
6100 listManager.addNote(newNote, metadata);
6101 conn.getNoteTable().addNote(newNote, true);
6102 noteTableView.insertRow(newNote, metadata, true, -1);
6103 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6104 listManager.countNotebookResults(listManager.getNoteIndex());
6105 importedFiles.add(list.get(i).absoluteFilePath());
6113 public void folderImportDelete(String dirName) {
6115 String whichOS = System.getProperty("os.name");
6116 if (whichOS.contains("Windows"))
6117 dirName = dirName.replace('/','\\');
6119 FileImporter importer = new FileImporter(logger, conn);
6120 QDir dir = new QDir(dirName);
6121 List<QFileInfo> list = dir.entryInfoList();
6122 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6124 for (int i=0; i<list.size(); i++){
6125 importer.setFileInfo(list.get(i));
6126 importer.setFileName(list.get(i).absoluteFilePath());
6128 if (list.get(i).isFile() && importer.isValidType()) {
6130 if (!importer.importFile()) {
6131 // If we can't get to the file, it is probably locked. We'll try again later.
6132 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6133 importFilesKeep.add(list.get(i).absoluteFilePath());
6137 Note newNote = importer.getNote();
6138 newNote.setNotebookGuid(notebook);
6139 newNote.setTitle(dir.at(i));
6140 NoteMetadata metadata = new NoteMetadata();
6141 metadata.setDirty(true);
6142 metadata.setGuid(newNote.getGuid());
6143 listManager.addNote(newNote, metadata);
6144 conn.getNoteTable().addNote(newNote, true);
6145 noteTableView.insertRow(newNote, metadata, true, -1);
6146 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6147 listManager.countNotebookResults(listManager.getNoteIndex());
6148 dir.remove(dir.at(i));
6154 //**************************************************
6156 //**************************************************
6157 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6158 logger.log(logger.HIGH, "Entering exernalFileEdited");
6160 // Strip URL prefix and base dir path
6161 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6162 String name = fileName.replace(dPath, "");
6163 int pos = name.lastIndexOf('.');
6166 guid = guid.substring(0,pos);
6168 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6170 guid = name.substring(0, pos);
6173 QFile file = new QFile(fileName);
6174 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6175 // If we can't get to the file, it is probably locked. We'll try again later.
6176 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6177 externalFiles.add(fileName);
6180 QByteArray binData = file.readAll();
6182 if (binData.size() == 0) {
6183 // If we can't get to the file, it is probably locked. We'll try again later.
6184 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6185 externalFiles.add(fileName);
6189 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6191 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6192 if (r == null || r.getData() == null || r.getData().getBody() == null)
6194 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6195 MessageDigest md = MessageDigest.getInstance("MD5");
6196 md.update(binData.toByteArray());
6197 byte[] hash = md.digest();
6198 String newHash = Global.byteArrayToHexString(hash);
6199 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6200 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6202 if (externalWindows.containsKey(r.getNoteGuid())) {
6203 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6204 r.getGuid(), oldHash, newHash);
6206 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6207 Data data = r.getData();
6208 data.setBody(binData.toByteArray());
6209 data.setBodyHash(hash);
6210 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6212 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6214 if (r.getNoteGuid().equals(currentNoteGuid)) {
6215 QWebSettings.setMaximumPagesInCache(0);
6216 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6217 refreshEvernoteNote(true);
6218 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6221 if (externalWindows.containsKey(r.getNoteGuid())) {
6222 QWebSettings.setMaximumPagesInCache(0);
6223 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6224 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6228 logger.log(logger.HIGH, "Exiting externalFielEdited");
6230 // This is a timer event that tries to save any external files that were edited. This
6231 // is only needed if we couldn't save a file earlier.
6232 public void externalFileEditedSaver() {
6233 for (int i=externalFiles.size()-1; i>=0; i--) {
6235 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6236 externalFileEdited(externalFiles.get(i));
6237 externalFiles.remove(i);
6238 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6240 for (int i=0; i<importFilesKeep.size(); i++) {
6242 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6243 folderImportKeep(importFilesKeep.get(i));
6244 importFilesKeep.remove(i);
6245 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6247 for (int i=0; i<importFilesDelete.size(); i++) {
6248 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6249 folderImportDelete(importFilesDelete.get(i));
6250 importFilesDelete.remove(i);
6257 // If an attachment on the current note was edited, we need to update the current notes's hash
6258 // Update a note content's hash. This happens if a resource is edited outside of NN
6259 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6260 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6262 for (;position>-1;) {
6263 endPos = browser.getContent().indexOf(">", position+1);
6264 String oldSegment = browser.getContent().substring(position,endPos);
6265 int hashPos = oldSegment.indexOf("hash=\"");
6266 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6267 String hash = oldSegment.substring(hashPos+6, hashEnd);
6268 if (hash.equalsIgnoreCase(oldHash)) {
6269 String newSegment = oldSegment.replace(oldHash, newHash);
6270 String content = browser.getContent().substring(0,position) +
6272 browser.getContent().substring(endPos);
6273 browser.setContent(new QByteArray(content));;
6276 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6281 //*************************************************
6282 //* Minimize to tray
6283 //*************************************************
6285 public void changeEvent(QEvent e) {
6286 if (e.type() == QEvent.Type.WindowStateChange) {
6287 if (isMinimized() && Global.showTrayIcon()) {
6289 QTimer.singleShot(10, this, "hide()");
6293 windowMaximized = true;
6295 windowMaximized = false;
6299 //*************************************************
6300 //* Check database userid & passwords
6301 //*************************************************
6302 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6303 Connection connection;
6306 Class.forName("org.h2.Driver");
6307 } catch (ClassNotFoundException e1) {
6308 e1.printStackTrace();
6313 String passwordString = null;
6314 if (cypherPassword==null || cypherPassword.trim().equals(""))
6315 passwordString = userPassword;
6317 passwordString = cypherPassword+" "+userPassword;
6318 connection = DriverManager.getConnection(url,userid,passwordString);
6319 } catch (SQLException e) {
6324 } catch (SQLException e) {
6325 e.printStackTrace();
6330 //*************************************************
6331 //* View / Hide source HTML for a note
6332 //*************************************************
6333 public void viewSource() {
6334 browserWindow.showSource(menuBar.viewSource.isChecked());
6336 //*************************************************
6337 // Block the program. This is used for things
6338 // like async web calls.
6339 //*************************************************
6340 @SuppressWarnings("unused")
6341 private void blockApplication(BrowserWindow b) {
6342 // Block all signals
6346 blockTimer = new QTimer();
6347 blockTimer.setSingleShot(true);
6348 blockTimer.setInterval(15000);
6349 blockTimer.timeout.connect(this, "unblockApplication()");
6354 @SuppressWarnings("unused")
6355 private void unblockApplication() {
6357 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6358 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6359 blockingWindow.unblockTime = -1;
6360 blockingWindow.awaitingHttpResponse = false;
6362 blockingWindow = null;
6363 blockSignals(false);