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 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2062 // Edit an existing tag
2063 @SuppressWarnings("unused")
2064 private void editTag() {
2065 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2066 TagEdit edit = new TagEdit();
2067 edit.setTitle("Edit Tag");
2068 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2069 QTreeWidgetItem currentSelection;
2070 currentSelection = selections.get(0);
2071 edit.setTag(currentSelection.text(0));
2072 edit.setTagList(listManager.getTagIndex());
2075 if (!edit.okPressed())
2078 String guid = currentSelection.text(2);
2079 currentSelection.setText(0,edit.getTag());
2081 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2082 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2083 listManager.getTagIndex().get(i).setName(edit.getTag());
2084 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2085 updateListTagName(guid);
2086 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2087 browserWindow.setTag(getTagNamesForNote(currentNote));
2088 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2092 browserWindow.setTag(getTagNamesForNote(currentNote));
2093 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2095 // Delete an existing tag
2096 @SuppressWarnings("unused")
2097 private void deleteTag() {
2098 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2100 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2101 QMessageBox.StandardButton.Yes,
2102 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2106 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2107 for (int i=selections.size()-1; i>=0; i--) {
2108 QTreeWidgetItem currentSelection;
2109 currentSelection = selections.get(i);
2110 removeTagItem(currentSelection.text(2));
2112 tagIndexUpdated(true);
2114 listManager.countTagResults(listManager.getNoteIndex());
2115 // tagTree.updateCounts(listManager.getTagCounter());
2116 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2118 // Remove a tag tree item. Go recursively down & remove the children too
2119 private void removeTagItem(String guid) {
2120 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2121 String parent = listManager.getTagIndex().get(j).getParentGuid();
2122 if (parent != null && parent.equals(guid)) {
2123 //Remove this tag's children
2124 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2127 //Now, remove this tag
2128 removeListTagName(guid);
2129 conn.getTagTable().expungeTag(guid, true);
2130 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2131 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2132 listManager.getTagIndex().remove(a);
2137 // Setup the tree containing the user's tags
2138 private void initializeTagTree() {
2139 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2140 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2141 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2142 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2143 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2144 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2146 // Listener when a tag is selected
2147 private void tagTreeSelection() {
2148 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2151 clearAttributeFilter();
2152 clearSavedSearchFilter();
2154 menuBar.noteRestoreAction.setVisible(false);
2156 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2157 QTreeWidgetItem currentSelection;
2158 selectedTagGUIDs.clear();
2159 for (int i=0; i<selections.size(); i++) {
2160 currentSelection = selections.get(i);
2161 selectedTagGUIDs.add(currentSelection.text(2));
2163 if (selections.size() > 0) {
2164 menuBar.tagEditAction.setEnabled(true);
2165 menuBar.tagDeleteAction.setEnabled(true);
2166 menuBar.tagIconAction.setEnabled(true);
2169 menuBar.tagEditAction.setEnabled(false);
2170 menuBar.tagDeleteAction.setEnabled(false);
2171 menuBar.tagIconAction.setEnabled(true);
2173 if (selections.size() > 1)
2174 menuBar.tagMergeAction.setEnabled(true);
2176 menuBar.tagMergeAction.setEnabled(false);
2177 listManager.setSelectedTags(selectedTagGUIDs);
2178 listManager.loadNotesIndex();
2179 noteIndexUpdated(false);
2180 refreshEvernoteNote(true);
2181 listManager.refreshCounters = true;
2182 listManager.refreshCounters();
2183 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2185 // trigger the tag index to be refreshed
2186 @SuppressWarnings("unused")
2187 private void tagIndexUpdated() {
2188 tagIndexUpdated(true);
2190 private void tagIndexUpdated(boolean reload) {
2191 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2192 if (selectedTagGUIDs == null)
2193 selectedTagGUIDs = new ArrayList<String>();
2195 listManager.reloadTagIndex();
2197 tagTree.blockSignals(true);
2199 tagTree.setIcons(conn.getTagTable().getAllIcons());
2200 tagTree.load(listManager.getTagIndex());
2203 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2204 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2206 selectedTagGUIDs.remove(i);
2208 tagTree.blockSignals(false);
2210 browserWindow.setTag(getTagNamesForNote(currentNote));
2211 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2213 // Show/Hide note information
2214 @SuppressWarnings("unused")
2215 private void toggleTagWindow() {
2216 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2217 if (tagTree.isVisible())
2221 menuBar.hideTags.setChecked(tagTree.isVisible());
2222 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2223 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2225 // A note's tags have been updated
2226 @SuppressWarnings("unused")
2227 private void updateNoteTags(String guid, List<String> tags) {
2228 // Save any new tags. We'll need them later.
2229 List<String> newTags = new ArrayList<String>();
2230 for (int i=0; i<tags.size(); i++) {
2231 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2232 newTags.add(tags.get(i));
2235 listManager.saveNoteTags(guid, tags);
2236 listManager.countTagResults(listManager.getNoteIndex());
2237 StringBuffer names = new StringBuffer("");
2238 for (int i=0; i<tags.size(); i++) {
2239 names = names.append(tags.get(i));
2240 if (i<tags.size()-1) {
2241 names.append(Global.tagDelimeter + " ");
2244 browserWindow.setTag(names.toString());
2247 // Now, we need to add any new tags to the tag tree
2248 for (int i=0; i<newTags.size(); i++)
2249 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2251 // Get a string containing all tag names for a note
2252 private String getTagNamesForNote(Note n) {
2253 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2254 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2256 StringBuffer buffer = new StringBuffer(100);
2257 Vector<String> v = new Vector<String>();
2258 List<String> guids = n.getTagGuids();
2263 for (int i=0; i<guids.size(); i++) {
2264 v.add(listManager.getTagNameByGuid(guids.get(i)));
2266 Comparator<String> comparator = Collections.reverseOrder();
2267 Collections.sort(v,comparator);
2268 Collections.reverse(v);
2270 for (int i = 0; i<v.size(); i++) {
2272 buffer.append(", ");
2273 buffer.append(v.get(i));
2276 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2277 return buffer.toString();
2279 // Tags were added via dropping notes from the note list
2280 @SuppressWarnings("unused")
2281 private void tagsAdded(String noteGuid, String tagGuid) {
2282 String tagName = null;
2283 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2284 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2285 tagName = listManager.getTagIndex().get(i).getName();
2286 i=listManager.getTagIndex().size();
2289 if (tagName == null)
2292 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2293 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2294 List<String> tagNames = new ArrayList<String>();
2295 tagNames.add(new String(tagName));
2296 Note n = listManager.getMasterNoteIndex().get(i);
2297 for (int j=0; j<n.getTagNames().size(); j++) {
2298 tagNames.add(new String(n.getTagNames().get(j)));
2300 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2301 if (n.getGuid().equals(currentNoteGuid)) {
2302 Collections.sort(tagNames);
2303 String display = "";
2304 for (int j=0; j<tagNames.size(); j++) {
2305 display = display+tagNames.get(j);
2306 if (j+2<tagNames.size())
2307 display = display+Global.tagDelimeter+" ";
2309 browserWindow.setTag(display);
2311 i=listManager.getMasterNoteIndex().size();
2316 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2318 private void clearTagFilter() {
2319 tagTree.blockSignals(true);
2320 tagTree.clearSelection();
2321 menuBar.noteRestoreAction.setVisible(false);
2322 menuBar.tagEditAction.setEnabled(false);
2323 menuBar.tagMergeAction.setEnabled(false);
2324 menuBar.tagDeleteAction.setEnabled(false);
2325 menuBar.tagIconAction.setEnabled(false);
2326 selectedTagGUIDs.clear();
2327 listManager.setSelectedTags(selectedTagGUIDs);
2328 tagTree.blockSignals(false);
2330 // Change the icon for a tag
2331 @SuppressWarnings("unused")
2332 private void setTagIcon() {
2333 QTreeWidgetItem currentSelection;
2334 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2335 if (selections.size() == 0)
2338 currentSelection = selections.get(0);
2339 String guid = currentSelection.text(2);
2341 QIcon currentIcon = currentSelection.icon(0);
2342 QIcon icon = conn.getTagTable().getIcon(guid);
2345 dialog = new SetIcon(currentIcon, saveLastPath);
2346 dialog.setUseDefaultIcon(true);
2348 dialog = new SetIcon(icon, saveLastPath);
2349 dialog.setUseDefaultIcon(false);
2352 if (dialog.okPressed()) {
2353 saveLastPath = dialog.getPath();
2354 QIcon newIcon = dialog.getIcon();
2355 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2356 if (newIcon == null)
2357 newIcon = new QIcon(iconPath+"tag.png");
2358 currentSelection.setIcon(0, newIcon);
2363 @SuppressWarnings("unused")
2364 private void mergeTags() {
2365 List<Tag> tags = new ArrayList<Tag>();
2366 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2367 for (int i=0; i<selections.size(); i++) {
2368 Tag record = new Tag();
2369 record.setGuid(selections.get(i).text(2));
2370 record.setName(selections.get(i).text(0));
2374 TagMerge mergeDialog = new TagMerge(tags);
2376 if (!mergeDialog.okClicked())
2378 String newGuid = mergeDialog.getNewTagGuid();
2380 for (int i=0; i<tags.size(); i++) {
2381 if (!tags.get(i).getGuid().equals(newGuid)) {
2382 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2383 for (int j=0; j<noteGuids.size(); j++) {
2384 String noteGuid = noteGuids.get(j);
2385 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2386 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2387 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2391 listManager.reloadIndexes();
2394 //***************************************************************
2395 //***************************************************************
2396 //** These functions deal with Saved Search menu items
2397 //***************************************************************
2398 //***************************************************************
2399 // Add a new notebook
2400 @SuppressWarnings("unused")
2401 private void addSavedSearch() {
2402 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2403 SavedSearchEdit edit = new SavedSearchEdit();
2404 edit.setSearchList(listManager.getSavedSearchIndex());
2407 if (!edit.okPressed())
2410 Calendar currentTime = new GregorianCalendar();
2411 Long l = new Long(currentTime.getTimeInMillis());
2412 String randint = new String(Long.toString(l));
2414 SavedSearch search = new SavedSearch();
2415 search.setUpdateSequenceNum(0);
2416 search.setGuid(randint);
2417 search.setName(edit.getName());
2418 search.setQuery(edit.getQuery());
2419 search.setFormat(QueryFormat.USER);
2420 listManager.getSavedSearchIndex().add(search);
2421 conn.getSavedSearchTable().addSavedSearch(search, true);
2422 savedSearchIndexUpdated();
2423 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2425 // Edit an existing tag
2426 @SuppressWarnings("unused")
2427 private void editSavedSearch() {
2428 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2429 SavedSearchEdit edit = new SavedSearchEdit();
2430 edit.setTitle(tr("Edit Search"));
2431 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2432 QTreeWidgetItem currentSelection;
2433 currentSelection = selections.get(0);
2434 String guid = currentSelection.text(1);
2435 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2436 edit.setName(currentSelection.text(0));
2437 edit.setQuery(s.getQuery());
2438 edit.setSearchList(listManager.getSavedSearchIndex());
2441 if (!edit.okPressed())
2444 List<SavedSearch> list = listManager.getSavedSearchIndex();
2445 SavedSearch search = null;
2446 boolean found = false;
2447 for (int i=0; i<list.size(); i++) {
2448 search = list.get(i);
2449 if (search.getGuid().equals(guid)) {
2456 search.setName(edit.getName());
2457 search.setQuery(edit.getQuery());
2458 conn.getSavedSearchTable().updateSavedSearch(search, true);
2459 savedSearchIndexUpdated();
2460 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2462 // Delete an existing tag
2463 @SuppressWarnings("unused")
2464 private void deleteSavedSearch() {
2465 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2467 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2468 QMessageBox.StandardButton.Yes,
2469 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2473 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2474 for (int i=selections.size()-1; i>=0; i--) {
2475 QTreeWidgetItem currentSelection;
2476 currentSelection = selections.get(i);
2477 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2478 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2479 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2480 listManager.getSavedSearchIndex().remove(j);
2481 j=listManager.getSavedSearchIndex().size()+1;
2484 selections.remove(i);
2486 savedSearchIndexUpdated();
2487 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2489 // Setup the tree containing the user's tags
2490 private void initializeSavedSearchTree() {
2491 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2492 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2493 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2495 // Listener when a tag is selected
2496 @SuppressWarnings("unused")
2497 private void savedSearchTreeSelection() {
2498 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2500 clearNotebookFilter();
2503 clearAttributeFilter();
2505 String currentGuid = selectedSavedSearchGUID;
2506 menuBar.savedSearchEditAction.setEnabled(true);
2507 menuBar.savedSearchDeleteAction.setEnabled(true);
2508 menuBar.savedSearchIconAction.setEnabled(true);
2509 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2510 QTreeWidgetItem currentSelection;
2511 selectedSavedSearchGUID = "";
2512 for (int i=0; i<selections.size(); i++) {
2513 currentSelection = selections.get(i);
2514 if (currentSelection.text(1).equals(currentGuid)) {
2515 currentSelection.setSelected(false);
2517 selectedSavedSearchGUID = currentSelection.text(1);
2519 // i = selections.size() +1;
2522 // There is the potential for no notebooks to be selected if this
2523 // happens then we make it look like all notebooks were selecetd.
2524 // If that happens, just select the "all notebooks"
2525 if (selections.size()==0) {
2526 clearSavedSearchFilter();
2528 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2530 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2532 private void clearSavedSearchFilter() {
2533 menuBar.savedSearchEditAction.setEnabled(false);
2534 menuBar.savedSearchDeleteAction.setEnabled(false);
2535 menuBar.savedSearchIconAction.setEnabled(false);
2536 savedSearchTree.blockSignals(true);
2537 savedSearchTree.clearSelection();
2538 savedSearchTree.blockSignals(false);
2539 selectedSavedSearchGUID = "";
2540 searchField.setEditText("");
2541 searchPerformed = false;
2542 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2544 // trigger the tag index to be refreshed
2545 private void savedSearchIndexUpdated() {
2546 if (selectedSavedSearchGUID == null)
2547 selectedSavedSearchGUID = new String();
2548 savedSearchTree.blockSignals(true);
2549 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2550 savedSearchTree.load(listManager.getSavedSearchIndex());
2551 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2552 savedSearchTree.blockSignals(false);
2554 // trigger when the saved search selection changes
2555 @SuppressWarnings("unused")
2556 private void updateSavedSearchSelection() {
2557 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2559 menuBar.savedSearchEditAction.setEnabled(true);
2560 menuBar.savedSearchDeleteAction.setEnabled(true);
2561 menuBar.savedSearchIconAction.setEnabled(true);
2562 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2564 if (selections.size() > 0) {
2565 menuBar.savedSearchEditAction.setEnabled(true);
2566 menuBar.savedSearchDeleteAction.setEnabled(true);
2567 menuBar.savedSearchIconAction.setEnabled(true);
2568 selectedSavedSearchGUID = selections.get(0).text(1);
2569 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2570 searchField.setEditText(s.getQuery());
2572 menuBar.savedSearchEditAction.setEnabled(false);
2573 menuBar.savedSearchDeleteAction.setEnabled(false);
2574 menuBar.savedSearchIconAction.setEnabled(false);
2575 selectedSavedSearchGUID = "";
2576 searchField.setEditText("");
2578 searchFieldChanged();
2580 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2584 // Show/Hide note information
2585 @SuppressWarnings("unused")
2586 private void toggleSavedSearchWindow() {
2587 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2588 if (savedSearchTree.isVisible())
2589 savedSearchTree.hide();
2591 savedSearchTree.show();
2592 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2594 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2595 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2597 // Change the icon for a saved search
2598 @SuppressWarnings("unused")
2599 private void setSavedSearchIcon() {
2600 QTreeWidgetItem currentSelection;
2601 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2602 if (selections.size() == 0)
2605 currentSelection = selections.get(0);
2606 String guid = currentSelection.text(1);
2608 QIcon currentIcon = currentSelection.icon(0);
2609 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2612 dialog = new SetIcon(currentIcon, saveLastPath);
2613 dialog.setUseDefaultIcon(true);
2615 dialog = new SetIcon(icon, saveLastPath);
2616 dialog.setUseDefaultIcon(false);
2619 if (dialog.okPressed()) {
2620 saveLastPath = dialog.getPath();
2621 QIcon newIcon = dialog.getIcon();
2622 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2623 if (newIcon == null)
2624 newIcon = new QIcon(iconPath+"search.png");
2625 currentSelection.setIcon(0, newIcon);
2633 //***************************************************************
2634 //***************************************************************
2635 //** These functions deal with Help menu & tool menu items
2636 //***************************************************************
2637 //***************************************************************
2638 // Show database status
2639 @SuppressWarnings("unused")
2640 private void databaseStatus() {
2642 indexRunner.interrupt = true;
2643 int dirty = conn.getNoteTable().getDirtyCount();
2644 int unindexed = conn.getNoteTable().getUnindexedCount();
2645 DatabaseStatus status = new DatabaseStatus();
2646 status.setUnsynchronized(dirty);
2647 status.setUnindexed(unindexed);
2648 status.setNoteCount(conn.getNoteTable().getNoteCount());
2649 status.setNotebookCount(listManager.getNotebookIndex().size());
2650 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2651 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2652 status.setTagCount(listManager.getTagIndex().size());
2653 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2654 status.setWordCount(conn.getWordsTable().getWordCount());
2658 // Compact the database
2659 @SuppressWarnings("unused")
2660 private void compactDatabase() {
2661 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2662 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2663 "but please be aware that depending upon the size of your database this can be time consuming " +
2664 "and NixNote will be unresponsive until it is complete. Do you wish to continue?"),
2665 QMessageBox.StandardButton.Yes,
2666 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2669 setMessage("Compacting database.");
2671 listManager.compactDatabase();
2673 setMessage("Database compact is complete.");
2674 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2676 @SuppressWarnings("unused")
2677 private void accountInformation() {
2678 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2679 AccountDialog dialog = new AccountDialog();
2681 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2683 @SuppressWarnings("unused")
2684 private void releaseNotes() {
2685 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2686 QDialog dialog = new QDialog(this);
2687 QHBoxLayout layout = new QHBoxLayout();
2688 QTextEdit textBox = new QTextEdit();
2689 layout.addWidget(textBox);
2690 textBox.setReadOnly(true);
2691 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2692 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2693 QIODevice.OpenModeFlag.Text)))
2695 textBox.setText(file.readAll().toString());
2697 dialog.setWindowTitle(tr("Release Notes"));
2698 dialog.setLayout(layout);
2700 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2702 // Called when user picks Log from the help menu
2703 @SuppressWarnings("unused")
2704 private void logger() {
2705 logger.log(logger.HIGH, "Entering NeverNote.logger");
2706 LogFileDialog dialog = new LogFileDialog(emitLog);
2708 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2710 // Menu option "help/about" was selected
2711 @SuppressWarnings("unused")
2712 private void about() {
2713 logger.log(logger.HIGH, "Entering NeverNote.about");
2714 QMessageBox.about(this,
2715 tr("About NixNote"),
2716 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2718 +tr("<hr></center>Evernote"
2719 +"An Open Source Evernote Client.<br><br>"
2720 +"Licensed under GPL v2. <br><hr><br>"
2721 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2722 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2723 +"PDFRenderer is licened under the LGPL<br>"
2724 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2725 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2726 +"Jazzy is licened under the LGPL<br>"
2727 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2728 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2729 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2730 logger.log(logger.HIGH, "Leaving NeverNote.about");
2732 // Hide the entire left hand side
2733 @SuppressWarnings("unused")
2734 private void toggleLeftSide() {
2737 hidden = !menuBar.hideLeftSide.isChecked();
2738 menuBar.hideLeftSide.setChecked(!hidden);
2741 leftSplitter1.setHidden(true);
2743 leftSplitter1.setHidden(false);
2745 Global.saveWindowVisible("leftPanel", hidden);
2748 public void checkForUpdates() {
2749 // Send off thread to check for a new version
2750 versionChecker = new QNetworkAccessManager(this);
2751 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2752 QNetworkRequest request = new QNetworkRequest();
2753 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2754 versionChecker.get(request);
2756 @SuppressWarnings("unused")
2757 private void upgradeFileRead(QNetworkReply reply) {
2758 if (!reply.isReadable())
2761 String winVersion = Global.version;
2762 String osxVersion = Global.version;
2763 String linuxVersion = Global.version;
2764 String linux64Version = Global.version;
2765 String version = Global.version;
2767 // Determine the versions available
2768 QByteArray data = reply.readLine();
2769 while (data != null && !reply.atEnd()) {
2770 String line = data.toString();
2772 if (line.contains(":"))
2773 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2776 if (line.toLowerCase().contains("windows"))
2777 winVersion = lineVersion;
2778 else if (line.toLowerCase().contains("os-x"))
2779 osxVersion = lineVersion;
2780 else if (line.toLowerCase().contains("linux amd64"))
2781 linux64Version = lineVersion;
2782 else if (line.toLowerCase().contains("linux i386"))
2783 linuxVersion = lineVersion;
2784 else if (line.toLowerCase().contains("default"))
2785 version = lineVersion;
2787 // Read the next line
2788 data = reply.readLine();
2791 // Now we need to determine what system we are on.
2792 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2793 version = winVersion;
2794 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2795 version = osxVersion;
2796 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2797 if (System.getProperty("os.arch").contains("amd64") ||
2798 System.getProperty("os.arch").contains("x86_64"))
2799 version = linux64Version;
2801 version = linuxVersion;
2805 for (String validVersion : Global.validVersions) {
2806 if (version.equals(validVersion))
2810 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2812 if (dialog.remindMe())
2813 Global.setCheckVersionUpgrade(true);
2815 Global.setCheckVersionUpgrade(false);
2819 //***************************************************************
2820 //***************************************************************
2821 //** These functions deal with the Toolbar
2822 //***************************************************************
2823 //***************************************************************
2824 @SuppressWarnings("unused")
2825 private void focusSearch() {
2826 searchField.setFocus();
2829 // Text in the search bar has been cleared
2830 private void searchFieldCleared() {
2833 // This is done because we want to force a reload of
2834 // images. Some images we may want to highlight the text.
2835 readOnlyCache.clear();
2836 inkNoteCache.clear();
2838 QWebSettings.setMaximumPagesInCache(0);
2839 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2841 searchField.setEditText("");
2842 saveNoteColumnPositions();
2843 saveNoteIndexWidth();
2844 noteIndexUpdated(true);
2845 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2846 currentNote = listManager.getNoteIndex().get(0);
2847 currentNoteGuid = currentNote.getGuid();
2849 refreshEvernoteNote(true);
2850 if (currentNote != null)
2851 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2853 // text in the search bar changed. We only use this to tell if it was cleared,
2854 // otherwise we trigger off searchFieldChanged.
2855 @SuppressWarnings("unused")
2856 private void searchFieldTextChanged(String text) {
2857 QWebSettings.setMaximumPagesInCache(0);
2858 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2860 if (text.trim().equals("")) {
2861 searchFieldCleared();
2862 if (searchPerformed) {
2864 // This is done because we want to force a reload of
2865 // images. Some images we may want to highlight the text.
2867 readOnlyCache.clear();
2868 inkNoteCache.clear();
2870 listManager.setEnSearch("");
2871 listManager.loadNotesIndex();
2872 refreshEvernoteNote(true);
2873 noteIndexUpdated(false);
2874 refreshEvernoteNote(true);
2876 searchPerformed = false;
2879 // Text in the toolbar has changed
2880 private void searchFieldChanged() {
2881 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2883 readOnlyCache.clear();
2884 inkNoteCache.clear();
2885 saveNoteColumnPositions();
2886 saveNoteIndexWidth();
2887 String text = searchField.currentText();
2888 listManager.setEnSearch(text.trim());
2889 listManager.loadNotesIndex();
2890 noteIndexUpdated(false);
2891 refreshEvernoteNote(true);
2892 searchPerformed = true;
2893 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2896 // Build the window tool bar
2897 private void setupToolBar() {
2898 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2899 toolBar = addToolBar(tr("Tool Bar"));
2900 toolBar.setObjectName("toolBar");
2901 menuBar.setupToolBarVisible();
2902 if (!Global.isWindowVisible("toolBar"))
2903 toolBar.setVisible(false);
2905 toolBar.setVisible(true);
2907 // toolBar.addWidget(menuBar);
2908 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2909 // toolBar.addSeparator();
2910 prevButton = toolBar.addAction(tr("Previous"));
2911 QIcon prevIcon = new QIcon(iconPath+"back.png");
2912 prevButton.setIcon(prevIcon);
2913 prevButton.triggered.connect(this, "previousViewedAction()");
2914 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2916 nextButton = toolBar.addAction(tr("Next"));
2917 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2918 nextButton.setIcon(nextIcon);
2919 nextButton.triggered.connect(this, "nextViewedAction()");
2920 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2922 upButton = toolBar.addAction(tr("Up"));
2923 QIcon upIcon = new QIcon(iconPath+"up.png");
2924 upButton.setIcon(upIcon);
2925 upButton.triggered.connect(this, "upAction()");
2926 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2929 downButton = toolBar.addAction(tr("Down"));
2930 QIcon downIcon = new QIcon(iconPath+"down.png");
2931 downButton.setIcon(downIcon);
2932 downButton.triggered.connect(this, "downAction()");
2933 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2935 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2936 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2937 synchronizeIconAngle = 0;
2938 synchronizeButton.triggered.connect(this, "evernoteSync()");
2939 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2941 printButton = toolBar.addAction(tr("Print"));
2942 QIcon printIcon = new QIcon(iconPath+"print.png");
2943 printButton.setIcon(printIcon);
2944 printButton.triggered.connect(this, "printNote()");
2945 togglePrintButton(Global.isToolbarButtonVisible("print"));
2947 tagButton = toolBar.addAction(tr("Tag"));
2948 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2949 tagButton.setIcon(tagIcon);
2950 tagButton.triggered.connect(browserWindow, "modifyTags()");
2951 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2953 attributeButton = toolBar.addAction(tr("Attributes"));
2954 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2955 attributeButton.setIcon(attributeIcon);
2956 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2957 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2959 emailButton = toolBar.addAction(tr("Email"));
2960 QIcon emailIcon = new QIcon(iconPath+"email.png");
2961 emailButton.setIcon(emailIcon);
2962 emailButton.triggered.connect(this, "emailNote()");
2963 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2965 deleteButton = toolBar.addAction(tr("Delete"));
2966 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2967 deleteButton.setIcon(deleteIcon);
2968 deleteButton.triggered.connect(this, "deleteNote()");
2969 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2971 newButton = toolBar.addAction(tr("New"));
2972 QIcon newIcon = new QIcon(iconPath+"new.png");
2973 newButton.triggered.connect(this, "addNote()");
2974 newButton.setIcon(newIcon);
2975 toggleNewButton(Global.isToolbarButtonVisible("new"));
2977 allNotesButton = toolBar.addAction(tr("All Notes"));
2978 QIcon allIcon = new QIcon(iconPath+"books.png");
2979 allNotesButton.triggered.connect(this, "allNotes()");
2980 allNotesButton.setIcon(allIcon);
2981 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2983 //toolBar.addSeparator();
2984 //toolBar.addWidget(new QLabel(tr("Quota:")));
2985 //toolBar.addWidget(quotaBar);
2986 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2988 //toolBar.addSeparator();
2990 //toolBar.addWidget(new QLabel(tr("Zoom")));
2991 //toolBar.addWidget(zoomSpinner);
2993 //toolBar.addWidget(new QLabel(" "));
2994 //toolBar.addSeparator();
2995 //toolBar.addWidget(new QLabel(tr(" Search:")));
2996 //toolBar.addWidget(searchField);
2997 QSizePolicy sizePolicy = new QSizePolicy();
2998 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2999 QLabel spacer = new QLabel("");
3000 spacer.setSizePolicy(sizePolicy);
3001 toolBar.addWidget(spacer);
3002 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3004 //searchClearButton = toolBar.addAction("Search Clear");
3005 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3006 //searchClearButton.setIcon(searchClearIcon);
3007 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3008 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3010 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3012 // Update the sychronize button picture
3014 public QMenu createPopupMenu() {
3015 QMenu contextMenu = super.createPopupMenu();
3017 contextMenu.addSeparator();
3018 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3019 contextMenu.addAction(prevAction);
3020 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3022 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3023 contextMenu.addAction(nextAction);
3024 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3026 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3027 contextMenu.addAction(upAction);
3028 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3030 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3031 contextMenu.addAction(downAction);
3032 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3034 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3035 contextMenu.addAction(synchronizeAction);
3036 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3038 QAction printAction = addContextAction("print", tr("Print"));
3039 contextMenu.addAction(printAction);
3040 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3042 QAction tagAction = addContextAction("tag", tr("Tag"));
3043 contextMenu.addAction(tagAction);
3044 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3046 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3047 contextMenu.addAction(attributeAction);
3048 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3050 QAction emailAction = addContextAction("email", tr("Email"));
3051 contextMenu.addAction(emailAction);
3052 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3054 QAction deleteAction = addContextAction("delete", tr("Delete"));
3055 contextMenu.addAction(deleteAction);
3056 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3058 QAction newAction = addContextAction("new", tr("Add"));
3059 contextMenu.addAction(newAction);
3060 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3062 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3063 contextMenu.addAction(allNotesAction);
3064 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3066 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3067 contextMenu.addAction(searchClearAction);
3068 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3073 private QAction addContextAction(String config, String name) {
3074 QAction newAction = new QAction(this);
3075 newAction.setText(name);
3076 newAction.setCheckable(true);
3077 newAction.setChecked(Global.isToolbarButtonVisible(config));
3080 private void togglePrevArrowButton(Boolean toggle) {
3081 prevButton.setVisible(toggle);
3082 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3084 private void toggleNextArrowButton(Boolean toggle) {
3085 nextButton.setVisible(toggle);
3086 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3088 private void toggleUpArrowButton(Boolean toggle) {
3089 upButton.setVisible(toggle);
3090 Global.saveToolbarButtonsVisible("upArrow", toggle);
3092 private void toggleDownArrowButton(Boolean toggle) {
3093 downButton.setVisible(toggle);
3094 Global.saveToolbarButtonsVisible("downArrow", toggle);
3096 private void toggleSynchronizeButton(Boolean toggle) {
3097 synchronizeButton.setVisible(toggle);
3098 Global.saveToolbarButtonsVisible("synchronize", toggle);
3100 private void togglePrintButton(Boolean toggle) {
3101 printButton.setVisible(toggle);
3102 Global.saveToolbarButtonsVisible("print", toggle);
3104 private void toggleTagButton(Boolean toggle) {
3105 tagButton.setVisible(toggle);
3106 Global.saveToolbarButtonsVisible("tag", toggle);
3108 private void toggleAttributeButton(Boolean toggle) {
3109 attributeButton.setVisible(toggle);
3110 Global.saveToolbarButtonsVisible("attribute", toggle);
3112 private void toggleEmailButton(Boolean toggle) {
3113 emailButton.setVisible(toggle);
3114 Global.saveToolbarButtonsVisible("email", toggle);
3116 private void toggleDeleteButton(Boolean toggle) {
3117 deleteButton.setVisible(toggle);
3118 Global.saveToolbarButtonsVisible("delete", toggle);
3120 private void toggleNewButton(Boolean toggle) {
3121 newButton.setVisible(toggle);
3122 Global.saveToolbarButtonsVisible("new", toggle);
3124 private void toggleAllNotesButton(Boolean toggle) {
3125 allNotesButton.setVisible(toggle);
3126 Global.saveToolbarButtonsVisible("allNotes", toggle);
3128 @SuppressWarnings("unused")
3129 private void toggleSearchClearButton(Boolean toggle) {
3130 searchClearButton.setVisible(toggle);
3131 Global.saveToolbarButtonsVisible("searchClear", toggle);
3138 @SuppressWarnings("unused")
3139 private void updateSyncButton() {
3141 if (syncIcons == null) {
3142 syncIcons = new ArrayList<QPixmap>();
3144 synchronizeIconAngle = 0;
3145 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3147 for (int i=0; i<=360; i++) {
3148 QPixmap rotatedPix = new QPixmap(pix.size());
3149 QPainter p = new QPainter(rotatedPix);
3150 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3151 QSize size = pix.size();
3152 p.translate(size.width()/2, size.height()/2);
3155 p.setBackgroundMode(BGMode.OpaqueMode);
3156 p.translate(-size.width()/2, -size.height()/2);
3157 p.drawPixmap(0,0, pix);
3159 syncIcons.add(rotatedPix);
3163 synchronizeIconAngle++;
3164 if (synchronizeIconAngle > 359)
3165 synchronizeIconAngle=0;
3166 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3169 // Synchronize with Evernote
3171 private void evernoteSync() {
3172 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3173 if (!Global.isConnected)
3175 if (Global.isConnected)
3176 synchronizeAnimationTimer.start(5);
3177 // synchronizeAnimationTimer.start(200);
3179 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3181 private void updateQuotaBar() {
3182 long limit = Global.getUploadLimit();
3183 long amount = Global.getUploadAmount();
3184 if (amount>0 && limit>0) {
3185 int percent =(int)(amount*100/limit);
3186 quotaBar.setValue(percent);
3188 quotaBar.setValue(0);
3191 @SuppressWarnings("unused")
3192 private void zoomChanged() {
3193 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3196 //****************************************************************
3197 //****************************************************************
3198 //* System Tray functions
3199 //****************************************************************
3200 //****************************************************************
3201 private void trayToggleVisible() {
3206 if (windowMaximized)
3213 @SuppressWarnings("unused")
3214 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3215 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3216 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3217 trayToggleVisible();
3222 //***************************************************************
3223 //***************************************************************
3224 //** These functions deal with the trash tree
3225 //***************************************************************
3226 //***************************************************************
3227 // Setup the tree containing the trash.
3228 @SuppressWarnings("unused")
3229 private void trashTreeSelection() {
3230 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3232 clearNotebookFilter();
3234 clearAttributeFilter();
3235 clearSavedSearchFilter();
3237 String tempGuid = currentNoteGuid;
3239 // currentNoteGuid = "";
3240 currentNote = new Note();
3241 selectedNoteGUIDs.clear();
3242 listManager.getSelectedNotebooks().clear();
3243 listManager.getSelectedTags().clear();
3244 listManager.setSelectedSavedSearch("");
3245 browserWindow.clear();
3247 // toggle the add buttons
3248 newButton.setEnabled(!newButton.isEnabled());
3249 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3250 menuBar.noteAdd.setVisible(true);
3252 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3253 if (selections.size() == 0) {
3254 currentNoteGuid = trashNoteGuid;
3255 trashNoteGuid = tempGuid;
3256 Global.showDeleted = false;
3257 menuBar.noteRestoreAction.setEnabled(false);
3258 menuBar.noteRestoreAction.setVisible(false);
3261 currentNoteGuid = trashNoteGuid;
3262 trashNoteGuid = tempGuid;
3263 menuBar.noteRestoreAction.setEnabled(true);
3264 menuBar.noteRestoreAction.setVisible(true);
3265 Global.showDeleted = true;
3267 listManager.loadNotesIndex();
3268 noteIndexUpdated(false);
3269 //// browserWindow.setEnabled(newButton.isEnabled());
3270 browserWindow.setReadOnly(!newButton.isEnabled());
3271 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3273 // Empty the trash file
3274 @SuppressWarnings("unused")
3275 private void emptyTrash() {
3276 // browserWindow.clear();
3277 logger.log(logger.EXTREME, "Emptying Trash");
3278 listManager.emptyTrash();
3279 logger.log(logger.EXTREME, "Resetting view after trash empty");
3280 if (trashTree.selectedItems().size() > 0) {
3281 listManager.getSelectedNotebooks().clear();
3282 listManager.getSelectedTags().clear();
3283 listManager.setSelectedSavedSearch("");
3284 newButton.setEnabled(!newButton.isEnabled());
3285 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3286 menuBar.noteAdd.setVisible(true);
3287 browserWindow.clear();
3290 clearNotebookFilter();
3291 clearSavedSearchFilter();
3292 clearAttributeFilter();
3294 Global.showDeleted = false;
3295 menuBar.noteRestoreAction.setEnabled(false);
3296 menuBar.noteRestoreAction.setVisible(false);
3298 listManager.loadNotesIndex();
3299 noteIndexUpdated(false);
3302 // Show/Hide trash window
3303 @SuppressWarnings("unused")
3304 private void toggleTrashWindow() {
3305 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3306 if (trashTree.isVisible())
3310 menuBar.hideTrash.setChecked(trashTree.isVisible());
3312 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3313 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3315 private void clearTrashFilter() {
3316 Global.showDeleted = false;
3317 newButton.setEnabled(true);
3318 menuBar.noteAdd.setEnabled(true);
3319 menuBar.noteAdd.setVisible(true);
3320 trashTree.blockSignals(true);
3321 trashTree.clearSelection();
3322 trashTree.blockSignals(false);
3327 //***************************************************************
3328 //***************************************************************
3329 //** These functions deal with connection settings
3330 //***************************************************************
3331 //***************************************************************
3332 // SyncRunner had a problem and things are disconnected
3333 @SuppressWarnings("unused")
3334 private void remoteErrorDisconnect() {
3335 menuBar.connectAction.setText(tr("Connect"));
3336 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3337 menuBar.synchronizeAction.setEnabled(false);
3338 Global.isConnected = false;
3339 synchronizeAnimationTimer.stop();
3342 // Do a manual connect/disconnect
3343 private void remoteConnect() {
3344 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3346 if (Global.isConnected) {
3347 Global.isConnected = false;
3348 syncRunner.enDisconnect();
3349 setupConnectMenuOptions();
3354 AESEncrypter aes = new AESEncrypter();
3356 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3357 } catch (FileNotFoundException e) {
3358 // File not found, so we'll just get empty strings anyway.
3361 if (Global.getProxyValue("url").equals("")) {
3362 System.setProperty("http.proxyHost","") ;
3363 System.setProperty("http.proxyPort", "") ;
3364 System.setProperty("https.proxyHost","") ;
3365 System.setProperty("https.proxyPort", "") ;
3368 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3369 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3370 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3371 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3373 if (Global.getProxyValue("userid").equals("")) {
3374 Authenticator.setDefault(new Authenticator() {
3376 protected PasswordAuthentication getPasswordAuthentication() {
3378 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3384 syncRunner.userStoreUrl = Global.userStoreUrl;
3385 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3386 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3388 String userid = aes.getUserid();
3389 String password = aes.getPassword();
3390 if (!userid.equals("") && !password.equals("")) {
3391 Global.username = userid;
3392 Global.password = password;
3393 syncRunner.username = Global.username;
3394 syncRunner.password = Global.password;
3395 syncRunner.enConnect();
3398 Global.isConnected = syncRunner.isConnected;
3400 if (!Global.isConnected) {
3401 // Show the login dialog box
3402 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3403 LoginDialog login = new LoginDialog();
3406 if (!login.okPressed()) {
3410 Global.username = login.getUserid();
3411 Global.password = login.getPassword();
3413 syncRunner.username = Global.username;
3414 syncRunner.password = Global.password;
3415 syncRunner.enConnect();
3416 Global.isConnected = syncRunner.isConnected;
3419 if (!Global.isConnected)
3422 setupConnectMenuOptions();
3423 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3425 private void setupConnectMenuOptions() {
3426 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3427 if (!Global.isConnected) {
3428 menuBar.connectAction.setText(tr("Connect"));
3429 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3430 menuBar.synchronizeAction.setEnabled(false);
3432 menuBar.connectAction.setText(tr("Disconnect"));
3433 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3434 menuBar.synchronizeAction.setEnabled(true);
3436 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3441 //***************************************************************
3442 //***************************************************************
3443 //** These functions deal with the GUI Attribute tree
3444 //***************************************************************
3445 //***************************************************************
3446 @SuppressWarnings("unused")
3447 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3449 // clearTagFilter();
3450 // clearNotebookFilter();
3452 // clearSavedSearchFilter();
3454 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3455 if (item.childCount() > 0) {
3456 item.setSelected(false);
3458 Global.createdBeforeFilter.reset();
3459 Global.createdSinceFilter.reset();
3460 Global.changedBeforeFilter.reset();
3461 Global.changedSinceFilter.reset();
3462 Global.containsFilter.reset();
3463 attributeTreeSelected = item;
3464 DateAttributeFilterTable f = null;
3465 f = findDateAttributeFilterTable(item.parent());
3467 f.select(item.parent().indexOfChild(item));
3469 Global.containsFilter.select(item.parent().indexOfChild(item));
3472 listManager.loadNotesIndex();
3473 noteIndexUpdated(false);
3476 attributeTreeSelected = null;
3477 item.setSelected(false);
3478 Global.createdBeforeFilter.reset();
3479 Global.createdSinceFilter.reset();
3480 Global.changedBeforeFilter.reset();
3481 Global.changedSinceFilter.reset();
3482 Global.containsFilter.reset();
3483 listManager.loadNotesIndex();
3484 noteIndexUpdated(false);
3486 // This determines what attribute filter we need, depending upon the selection
3487 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3488 if (w.parent() != null && w.childCount() > 0) {
3489 QTreeWidgetItem parent = w.parent();
3490 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3491 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3492 return Global.createdSinceFilter;
3493 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3494 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3495 return Global.createdBeforeFilter;
3496 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3497 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3498 return Global.changedSinceFilter;
3499 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3500 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3501 return Global.changedBeforeFilter;
3506 // Show/Hide attribute search window
3507 @SuppressWarnings("unused")
3508 private void toggleAttributesWindow() {
3509 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3510 if (attributeTree.isVisible())
3511 attributeTree.hide();
3513 attributeTree.show();
3514 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3516 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3517 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3519 private void clearAttributeFilter() {
3520 Global.createdBeforeFilter.reset();
3521 Global.createdSinceFilter.reset();
3522 Global.changedBeforeFilter.reset();
3523 Global.changedSinceFilter.reset();
3524 Global.containsFilter.reset();
3525 attributeTreeSelected = null;
3526 attributeTree.blockSignals(true);
3527 attributeTree.clearSelection();
3528 attributeTree.blockSignals(false);
3532 //***************************************************************
3533 //***************************************************************
3534 //** These functions deal with the GUI Note index table
3535 //***************************************************************
3536 //***************************************************************
3537 // Initialize the note list table
3538 private void initializeNoteTable() {
3539 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3540 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3541 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3542 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3544 // Show/Hide trash window
3545 @SuppressWarnings("unused")
3546 private void toggleNoteListWindow() {
3547 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3548 if (noteTableView.isVisible())
3549 noteTableView.hide();
3551 noteTableView.show();
3552 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3554 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3555 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3557 // Handle the event that a user selects a note from the table
3558 @SuppressWarnings("unused")
3559 private void noteTableSelection() {
3560 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3564 // If the ctrl key is pressed, then they are selecting multiple
3565 // entries and we don't want to change the currently viewed note.
3566 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3567 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3570 if (historyGuids.size() == 0) {
3571 historyGuids.add(currentNoteGuid);
3572 historyPosition = 1;
3574 noteTableView.showColumn(Global.noteTableGuidPosition);
3576 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3577 if (!Global.isColumnVisible("guid"))
3578 noteTableView.hideColumn(Global.noteTableGuidPosition);
3580 if (selections.size() > 0) {
3582 menuBar.noteDuplicateAction.setEnabled(true);
3583 menuBar.noteOnlineHistoryAction.setEnabled(true);
3584 menuBar.noteMergeAction.setEnabled(true);
3585 selectedNoteGUIDs.clear();
3586 if (selections.size() != 1 || Global.showDeleted) {
3587 menuBar.noteDuplicateAction.setEnabled(false);
3589 if (selections.size() != 1 || !Global.isConnected) {
3590 menuBar.noteOnlineHistoryAction.setEnabled(false);
3592 if (selections.size() == 1) {
3593 menuBar.noteMergeAction.setEnabled(false);
3595 for (int i=0; i<selections.size(); i++) {
3596 int row = selections.get(i).row();
3598 upButton.setEnabled(false);
3600 upButton.setEnabled(true);
3601 if (row < listManager.getNoteTableModel().rowCount()-1)
3602 downButton.setEnabled(true);
3604 downButton.setEnabled(false);
3605 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3606 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3607 currentNoteGuid = (String)ix.values().toArray()[0];
3608 selectedNoteGUIDs.add(currentNoteGuid);
3612 nextButton.setEnabled(true);
3613 prevButton.setEnabled(true);
3615 int endPosition = historyGuids.size()-1;
3616 for (int j=historyPosition; j<=endPosition; j++) {
3617 historyGuids.remove(historyGuids.size()-1);
3619 historyGuids.add(currentNoteGuid);
3620 historyPosition = historyGuids.size();
3622 if (historyPosition <= 1)
3623 prevButton.setEnabled(false);
3624 if (historyPosition == historyGuids.size())
3625 nextButton.setEnabled(false);
3627 fromHistory = false;
3628 scrollToGuid(currentNoteGuid);
3629 refreshEvernoteNote(true);
3630 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3632 // Trigger a refresh when the note db has been updated
3633 private void noteIndexUpdated(boolean reload) {
3634 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3636 refreshEvernoteNoteList();
3637 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3638 noteTableView.load(reload);
3639 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3641 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3642 pos = noteTableView.proxyModel.rowCount();
3645 if (noteTableView.proxyModel.rowCount() == 0)
3648 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3650 currentNoteGuid = (String)i.data();
3654 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3656 scrollToGuid(currentNoteGuid);
3657 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3659 // Called when the list of notes is updated
3660 private void refreshEvernoteNoteList() {
3661 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3662 browserWindow.setDisabled(false);
3663 if (selectedNoteGUIDs == null)
3664 selectedNoteGUIDs = new ArrayList<String>();
3665 selectedNoteGUIDs.clear(); // clear out old entries
3667 String saveCurrentNoteGuid = new String();
3668 String tempNoteGuid = new String();
3670 historyGuids.clear();
3671 historyPosition = 0;
3672 prevButton.setEnabled(false);
3673 nextButton.setEnabled(false);
3675 if (currentNoteGuid == null)
3676 currentNoteGuid = new String();
3678 //determine current note guid
3679 for (Note note : listManager.getNoteIndex()) {
3680 tempNoteGuid = note.getGuid();
3681 if (currentNoteGuid.equals(tempNoteGuid)) {
3682 saveCurrentNoteGuid = tempNoteGuid;
3686 if (listManager.getNoteIndex().size() == 0) {
3687 currentNoteGuid = "";
3689 browserWindow.clear();
3690 browserWindow.setDisabled(true);
3693 if (!saveCurrentNoteGuid.equals("")) {
3694 refreshEvernoteNote(false);
3696 currentNoteGuid = "";
3698 reloadTagTree(false);
3700 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3702 // Called when the previous arrow button is clicked
3703 @SuppressWarnings("unused")
3704 private void previousViewedAction() {
3705 if (!prevButton.isEnabled())
3707 if (historyPosition == 0)
3710 if (historyPosition <= 0)
3712 String historyGuid = historyGuids.get(historyPosition-1);
3714 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3715 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3716 if (modelIndex != null) {
3717 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3718 String tableGuid = (String)ix.values().toArray()[0];
3719 if (tableGuid.equals(historyGuid)) {
3720 noteTableView.selectRow(i);
3726 @SuppressWarnings("unused")
3727 private void nextViewedAction() {
3728 if (!nextButton.isEnabled())
3730 String historyGuid = historyGuids.get(historyPosition);
3733 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3734 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3735 if (modelIndex != null) {
3736 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3737 String tableGuid = (String)ix.values().toArray()[0];
3738 if (tableGuid.equals(historyGuid)) {
3739 noteTableView.selectRow(i);
3745 // Called when the up arrow is clicked
3746 @SuppressWarnings("unused")
3747 private void upAction() {
3748 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3749 int row = selections.get(0).row();
3751 noteTableView.selectRow(row-1);
3754 // Called when the down arrow is clicked
3755 @SuppressWarnings("unused")
3756 private void downAction() {
3757 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3758 int row = selections.get(0).row();
3759 int max = listManager.getNoteTableModel().rowCount();
3761 noteTableView.selectRow(row+1);
3764 // Update a tag string for a specific note in the list
3765 @SuppressWarnings("unused")
3766 private void updateListTags(String guid, List<String> tags) {
3767 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3768 StringBuffer tagBuffer = new StringBuffer();
3769 for (int i=0; i<tags.size(); i++) {
3770 tagBuffer.append(tags.get(i));
3771 if (i<tags.size()-1)
3772 tagBuffer.append(", ");
3775 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3776 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3777 if (modelIndex != null) {
3778 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3779 String tableGuid = (String)ix.values().toArray()[0];
3780 if (tableGuid.equals(guid)) {
3781 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3782 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3783 noteTableView.proxyModel.invalidate();
3788 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3790 // Update a title for a specific note in the list
3791 @SuppressWarnings("unused")
3792 private void updateListAuthor(String guid, String author) {
3793 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3795 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3796 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3797 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3798 if (modelIndex != null) {
3799 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3800 String tableGuid = (String)ix.values().toArray()[0];
3801 if (tableGuid.equals(guid)) {
3802 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3803 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3804 noteTableView.proxyModel.invalidate();
3810 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3812 private void updateListNoteNotebook(String guid, String notebook) {
3813 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3814 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3815 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3817 // Update a title for a specific note in the list
3818 @SuppressWarnings("unused")
3819 private void updateListSourceUrl(String guid, String url) {
3820 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3822 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3823 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3824 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3825 if (modelIndex != null) {
3826 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3827 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3828 String tableGuid = (String)ix.values().toArray()[0];
3829 if (tableGuid.equals(guid)) {
3830 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3831 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3832 noteTableView.proxyModel.invalidate();
3837 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3839 @SuppressWarnings("unused")
3840 private void updateListGuid(String oldGuid, String newGuid) {
3841 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3843 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3844 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3845 if (modelIndex != null) {
3846 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3847 String tableGuid = (String)ix.values().toArray()[0];
3848 if (tableGuid.equals(oldGuid)) {
3849 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3850 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3855 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3857 private void updateListTagName(String guid) {
3858 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3860 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3861 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3862 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3864 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3865 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3866 if (modelIndex != null) {
3867 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3868 String noteGuid = (String)ix.values().toArray()[0];
3869 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3870 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3871 i=listManager.getNoteTableModel().rowCount();
3877 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3879 private void removeListTagName(String guid) {
3880 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3882 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3883 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3884 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3885 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3886 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3889 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3890 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3891 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3892 if (modelIndex != null) {
3893 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3894 String noteGuid = (String)ix.values().toArray()[0];
3895 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3896 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3897 i=listManager.getNoteTableModel().rowCount();
3903 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3905 private void updateListNotebookName(String oldName, String newName) {
3906 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3908 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3909 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3910 if (modelIndex != null) {
3911 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3912 String tableName = (String)ix.values().toArray()[0];
3913 if (tableName.equalsIgnoreCase(oldName)) {
3914 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3918 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3920 @SuppressWarnings("unused")
3921 private void updateListDateCreated(String guid, QDateTime date) {
3922 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3924 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3925 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3926 if (modelIndex != null) {
3927 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3928 String tableGuid = (String)ix.values().toArray()[0];
3929 if (tableGuid.equals(guid)) {
3930 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3931 noteTableView.proxyModel.invalidate();
3936 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3938 @SuppressWarnings("unused")
3939 private void updateListDateSubject(String guid, QDateTime date) {
3940 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3942 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3943 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3944 if (modelIndex != null) {
3945 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3946 String tableGuid = (String)ix.values().toArray()[0];
3947 if (tableGuid.equals(guid)) {
3948 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3949 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3950 noteTableView.proxyModel.invalidate();
3955 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3957 private void updateListDateChanged(String guid, QDateTime date) {
3958 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3960 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3961 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3962 if (modelIndex != null) {
3963 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3964 String tableGuid = (String)ix.values().toArray()[0];
3965 if (tableGuid.equals(guid)) {
3966 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3967 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3972 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3974 private void updateListDateChanged() {
3975 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3976 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3977 updateListDateChanged(currentNoteGuid, date);
3978 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3981 private void scrollToCurrentGuid() {
3982 //scrollToGuid(currentNoteGuid);
3983 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3984 if (selections.size() == 0)
3986 QModelIndex index = selections.get(0);
3987 int row = selections.get(0).row();
3988 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3991 // Scroll to the current GUID in tthe list.
3992 // Scroll to a particular index item
3993 private void scrollToGuid(String guid) {
3994 if (currentNote == null || guid == null)
3996 if (currentNote.isActive() && Global.showDeleted) {
3997 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3998 if (!listManager.getNoteIndex().get(i).isActive()) {
3999 currentNote = listManager.getNoteIndex().get(i);
4000 currentNoteGuid = currentNote.getGuid();
4001 i = listManager.getNoteIndex().size();
4005 if (!currentNote.isActive() && !Global.showDeleted) {
4006 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4007 if (listManager.getNoteIndex().get(i).isActive()) {
4008 currentNote = listManager.getNoteIndex().get(i);
4009 currentNoteGuid = currentNote.getGuid();
4010 i = listManager.getNoteIndex().size();
4015 for (int i=0; i<noteTableView.model().rowCount(); i++) {
4016 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4017 if (currentNoteGuid.equals(index.data())) {
4018 // noteTableView.selectionModel().blockSignals(true);
4019 noteTableView.selectRow(i);
4020 // noteTableView.selectionModel().blockSignals(false);
4021 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
4022 i=listManager.getNoteTableModel().rowCount();
4025 noteTableView.repaint();
4027 // Show/Hide columns
4028 private void showColumns() {
4029 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4030 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4031 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4032 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4033 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4034 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4035 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4036 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4037 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4038 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4039 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4041 // Title color has changed
4042 @SuppressWarnings("unused")
4043 private void titleColorChanged(Integer color) {
4044 logger.log(logger.HIGH, "Entering NeverNote.titleColorChanged");
4046 QColor backgroundColor = new QColor();
4047 QColor foregroundColor = new QColor(QColor.black);
4048 backgroundColor.setRgb(color);
4050 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4051 foregroundColor.setRgb(QColor.white.rgb());
4053 if (selectedNoteGUIDs.size() == 0)
4054 selectedNoteGUIDs.add(currentNoteGuid);
4056 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4057 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4058 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4059 if (modelIndex != null) {
4060 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4061 String tableGuid = (String)ix.values().toArray()[0];
4062 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4063 for (int k=0; k<Global.noteTableColumnCount; k++) {
4064 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4065 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4066 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4068 i=listManager.getNoteTableModel().rowCount();
4073 logger.log(logger.HIGH, "Leaving NeverNote.titleColorChanged");
4075 // A note has been pinned or unpinned
4076 private void notePinned() {
4077 logger.log(logger.EXTREME, "Entering NeverNote.notePinned()");
4079 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4080 NoteMetadata meta = listManager.getNoteMetadata().get(selectedNoteGUIDs.get(j));
4081 boolean pinned = !meta.isPinned();
4082 meta.setPinned(pinned); // Toggle the pinned/unpinned
4084 // Update the list & table
4085 listManager.updateNoteMetadata(meta);
4086 noteTableView.proxyModel.addGuid(selectedNoteGUIDs.get(j), meta);
4089 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4091 // Wide list was chosen
4092 public void narrowListView() {
4093 saveNoteColumnPositions();
4094 saveNoteIndexWidth();
4096 int sortCol = noteTableView.proxyModel.sortColumn();
4097 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4098 Global.setSortColumn(sortCol);
4099 Global.setSortOrder(sortOrder);
4101 Global.setListView(Global.View_List_Narrow);
4103 menuBar.wideListView.blockSignals(true);
4104 menuBar.narrowListView.blockSignals(true);
4106 menuBar.wideListView.setChecked(false);
4107 menuBar.narrowListView.setChecked(true);
4109 menuBar.wideListView.blockSignals(false);
4110 menuBar.narrowListView.blockSignals(false);
4112 mainLeftRightSplitter.addWidget(noteTableView);
4113 mainLeftRightSplitter.addWidget(browserWindow);
4114 restoreWindowState(false);
4115 noteTableView.repositionColumns();
4116 noteTableView.resizeColumnWidths();
4117 noteTableView.resizeRowHeights();
4119 sortCol = Global.getSortColumn();
4120 sortOrder = Global.getSortOrder();
4121 noteTableView.proxyModel.blocked = true;
4122 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4123 noteTableView.proxyModel.blocked = false;
4127 noteTableView.load(false);
4128 refreshEvernoteNote(true);
4129 scrollToCurrentGuid();
4131 public void wideListView() {
4132 int sortCol = noteTableView.proxyModel.sortColumn();
4133 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4134 Global.setSortColumn(sortCol);
4135 Global.setSortOrder(sortOrder);
4138 saveNoteColumnPositions();
4139 saveNoteIndexWidth();
4140 Global.setListView(Global.View_List_Wide);
4142 menuBar.wideListView.blockSignals(true);
4143 menuBar.narrowListView.blockSignals(true);
4145 menuBar.wideListView.setChecked(true);
4146 menuBar.narrowListView.setChecked(false);
4148 menuBar.wideListView.blockSignals(false);
4149 menuBar.narrowListView.blockSignals(false);
4150 browserIndexSplitter.setVisible(true);
4151 browserIndexSplitter.addWidget(noteTableView);
4152 browserIndexSplitter.addWidget(browserWindow);
4153 restoreWindowState(false);
4154 noteTableView.repositionColumns();
4155 noteTableView.resizeColumnWidths();
4156 noteTableView.resizeRowHeights();
4158 sortCol = Global.getSortColumn();
4159 sortOrder = Global.getSortOrder();
4160 noteTableView.proxyModel.blocked = true;
4161 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4162 noteTableView.proxyModel.blocked = false;
4165 noteTableView.load(false);
4166 scrollToCurrentGuid();
4168 // Sort order for the notebook has changed
4169 public void tableSortOrderChanged(Integer column, Integer order) {
4171 // Find what notebook (if any) is selected. We ignore stacks & the "All Notebooks".
4172 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4173 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4174 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4176 notebook = currentSelectedNotebook.text(2);
4177 conn.getNotebookTable().setSortOrder(notebook, column, order);
4181 //***************************************************************
4182 @SuppressWarnings("unused")
4183 private void evernoteLinkClick(String syncGuid, String locGuid) {
4185 if (conn.getNoteTable().guidExists(syncGuid)) {
4188 // If we didn't find it via the synchronized guid, look under the local guid
4189 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4190 // later synchronized (that causes the guid to change so we need to find the new one).
4191 if (conn.getNoteTable().guidExists(locGuid))
4194 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4197 openExternalEditor(guid);
4201 //If we've gotten this far, we can't find the note
4202 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4203 " seem to find that note."));
4205 //***************************************************************
4206 //***************************************************************
4207 //** External editor window functions
4208 //***************************************************************
4209 //***************************************************************
4210 private void listDoubleClick() {
4212 openExternalEditor(currentNoteGuid);
4214 private void openExternalEditor(String guid) {
4216 if (externalWindows.containsKey(guid)) {
4217 externalWindows.get(guid).raise();
4220 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4221 // We have a new external editor to create
4222 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4223 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4224 newBrowser.setWindowIcon(appIcon);
4225 externalWindows.put(guid, newBrowser);
4226 showEditorButtons(newBrowser.getBrowserWindow());
4227 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4228 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4229 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4230 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4231 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4232 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4233 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4234 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4236 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4237 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4238 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4242 @SuppressWarnings("unused")
4243 private void externalWindowTitleEdited(String guid, String text) {
4244 if (guid.equals(currentNoteGuid)) {
4245 browserWindow.setTitle(text);
4248 @SuppressWarnings({ "rawtypes", "unused" })
4249 private void externalWindowTagsEdited(String guid, List values) {
4250 StringBuffer line = new StringBuffer(100);
4251 for (int i=0; i<values.size(); i++) {
4253 line.append(Global.tagDelimeter+" ");
4254 line.append(values.get(i));
4256 if (guid.equals(currentNoteGuid)) {
4257 browserWindow.setTag(line.toString());
4260 @SuppressWarnings("unused")
4261 private void externalWindowClosing(String guid) {
4262 externalWindows.remove(guid);
4267 //***************************************************************
4268 //***************************************************************
4269 //** These functions deal with Note specific things
4270 //***************************************************************
4271 //***************************************************************
4272 @SuppressWarnings("unused")
4273 private void setNoteDirty() {
4274 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4276 // Find if the note is being edited externally. If it is, update it.
4277 if (externalWindows.containsKey(currentNoteGuid)) {
4278 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4279 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4280 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4281 window.getBrowserWindow().setContent(unicode);
4284 // If the note is dirty, then it is unsynchronized by default.
4288 // Set the note as dirty and check if its status is synchronized in the display table
4290 if (listManager.getNoteMetadata().containsKey(currentNoteGuid) &&
4291 listManager.getNoteMetadata().get(currentNoteGuid).isDirty()) {
4295 // If this wasn't already marked as unsynchronized, then we need to update the table
4296 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4297 // listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4298 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4299 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4300 if (modelIndex != null) {
4301 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4302 String tableGuid = (String)ix.values().toArray()[0];
4303 if (tableGuid.equals(currentNoteGuid)) {
4304 listManager.getNoteTableModel().proxyModel.setData(i, Global.noteTableSynchronizedPosition, "false");
4310 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4312 @SuppressWarnings("unused")
4313 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4314 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4315 QByteArray unicode = codec.fromUnicode(content);
4316 noteCache.remove(guid);
4317 noteCache.put(guid, unicode.toString());
4318 if (guid.equals(currentNoteGuid)) {
4320 browserWindow.setContent(unicode);
4323 thumbnailRunner.addWork("GENERATE "+ guid);
4324 saveNote(guid, browser);
4328 private void saveNote() {
4330 saveNote(currentNoteGuid, browserWindow);
4331 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4335 private void saveNote(String guid, BrowserWindow window) {
4336 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4339 logger.log(logger.EXTREME, "Saving to cache");
4340 QTextCodec codec = QTextCodec.codecForLocale();
4341 // QTextDecoder decoder = codec.makeDecoder();
4342 codec = QTextCodec.codecForName("UTF-8");
4343 QByteArray unicode = codec.fromUnicode(window.getContent());
4344 noteCache.put(guid, unicode.toString());
4346 logger.log(logger.EXTREME, "updating list manager");
4347 listManager.updateNoteContent(guid, window.getContent());
4348 logger.log(logger.EXTREME, "Updating title");
4349 listManager.updateNoteTitle(guid, window.getTitle());
4350 updateListDateChanged();
4352 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4353 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4354 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4355 currentNote = listManager.getNoteIndex().get(i);
4356 i = listManager.getNoteIndex().size();
4361 // Get a note from Evernote (and put it in the browser)
4362 private void refreshEvernoteNote(boolean reload) {
4363 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4365 if (Global.disableViewing) {
4366 browserWindow.setEnabled(false);
4371 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4373 Global.cryptCounter =0;
4375 browserWindow.setReadOnly(true);
4383 browserWindow.loadingData(true);
4385 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4386 if (currentNote == null)
4388 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4391 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4392 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4393 formatter.setNote(note, Global.pdfPreview());
4394 formatter.setHighlight(listManager.getEnSearch());
4396 if (!noteCache.containsKey(guid)) {
4397 js = new QByteArray();
4398 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4399 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4400 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>");
4401 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4402 js.append("<style> img { max-width:100%; }</style>");
4403 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4404 js.append("</head>");
4405 formatter.setNote(note, Global.pdfPreview());
4406 js.append(formatter.rebuildNoteHTML());
4407 js.append("</HTML>");
4408 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4409 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4410 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4411 // if (Global.enableHTMLEntitiesFix) {
4412 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4414 browser.setContent(js);
4415 noteCache.put(guid, js.toString());
4417 if (formatter.resourceError)
4418 resourceErrorMessage();
4419 if (formatter.formatError) {
4421 QMessageBox.information(this, tr("Error"),
4422 tr("NixNote had issues formatting this note." +
4423 " To protect your data this note is being marked as read-only."));
4426 readOnly = formatter.readOnly;
4427 inkNote = formatter.inkNote;
4429 readOnlyCache.put(guid, true);
4431 inkNoteCache.put(guid, true);
4433 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4434 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4435 js = new QByteArray(cachedContent);
4436 browser.setContent(js);
4437 if (readOnlyCache.containsKey(guid))
4439 if (inkNoteCache.containsKey(guid))
4442 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4443 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4445 if (readOnly || inkNote)
4446 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4448 browser.getBrowser().page().setContentEditable(true);
4449 browser.setReadOnly(readOnly);
4450 deleteButton.setEnabled(!readOnly);
4451 tagButton.setEnabled(!readOnly);
4452 menuBar.noteDelete.setEnabled(!readOnly);
4453 menuBar.noteTags.setEnabled(!readOnly);
4454 browser.setNote(note);
4456 if (note != null && note.getNotebookGuid() != null &&
4457 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4458 deleteButton.setEnabled(false);
4459 menuBar.notebookDeleteAction.setEnabled(false);
4461 deleteButton.setEnabled(true);
4462 menuBar.notebookDeleteAction.setEnabled(true);
4465 // Build a list of non-closed notebooks
4466 List<Notebook> nbooks = new ArrayList<Notebook>();
4467 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4468 boolean found=false;
4469 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4470 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4474 nbooks.add(listManager.getNotebookIndex().get(i));
4477 browser.setTitle(note.getTitle());
4478 browser.setTag(getTagNamesForNote(note));
4479 browser.setAuthor(note.getAttributes().getAuthor());
4481 browser.setAltered(note.getUpdated());
4482 browser.setCreation(note.getCreated());
4483 if (note.getAttributes().getSubjectDate() > 0)
4484 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4486 browser.setSubjectDate(note.getCreated());
4487 browser.setUrl(note.getAttributes().getSourceURL());
4489 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4490 List<Tag> tagList = tagFilter.getValidTags(note);
4491 browser.setAllTags(tagList);
4493 browser.setCurrentTags(note.getTagNames());
4497 browser.loadingData(false);
4498 if (thumbnailViewer.isActiveWindow())
4501 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4502 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4505 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4507 // Save a generated thumbnail
4508 private void toggleNoteInformation() {
4509 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4510 browserWindow.toggleInformation();
4511 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4512 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4513 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4515 // Listener triggered when a print button is pressed
4516 @SuppressWarnings("unused")
4517 private void printNote() {
4518 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4520 QPrintDialog dialog = new QPrintDialog();
4521 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4522 QPrinter printer = dialog.printer();
4523 browserWindow.getBrowser().print(printer);
4525 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4528 // Listener triggered when the email button is pressed
4529 @SuppressWarnings("unused")
4530 private void emailNote() {
4531 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4533 if (Desktop.isDesktopSupported()) {
4534 Desktop desktop = Desktop.getDesktop();
4536 String text2 = browserWindow.getContentsToEmail();
4537 QUrl url = new QUrl("mailto:");
4538 url.addQueryItem("subject", currentNote.getTitle());
4539 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4540 url.addQueryItem("body", text2);
4541 QDesktopServices.openUrl(url);
4545 if (desktop.isSupported(Desktop.Action.MAIL)) {
4546 URI uriMailTo = null;
4548 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4549 String text = browserWindow.getContentsToEmail();
4550 //text = "<b>" +text +"</b>";
4551 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4552 +"&BODY=" +text, null);
4553 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4554 +"&ATTACHMENT=d:/test.pdf", null);
4555 desktop.mail(uriMailTo);
4556 } catch (URISyntaxException e) {
4557 e.printStackTrace();
4558 } catch (IOException e) {
4559 e.printStackTrace();
4566 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4568 // Reindex all notes
4569 @SuppressWarnings("unused")
4570 private void fullReindex() {
4571 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4572 indexRunner.addWork("REINDEXALL");
4573 setMessage(tr("Database will be reindexed."));
4574 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4576 // Listener when a user wants to reindex a specific note
4577 @SuppressWarnings("unused")
4578 private void reindexNote() {
4579 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4580 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4581 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4583 if (selectedNotebookGUIDs.size() > 1)
4584 setMessage(tr("Notes will be reindexed."));
4586 setMessage(tr("Note will be reindexed."));
4587 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4590 @SuppressWarnings("unused")
4591 private void deleteNote() {
4592 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4593 if (currentNote == null)
4595 if (currentNoteGuid.equals(""))
4597 String title = null;
4598 if (selectedNoteGUIDs.size() == 1)
4599 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4601 // If we are deleting non-trash notes
4602 if (currentNote.isActive()) {
4603 if (Global.verifyDelete()) {
4605 if (selectedNoteGUIDs.size() > 1) {
4606 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4609 msg = new String(tr("Delete note \"") +title +"\"?");
4611 msg = new String(tr("Delete note selected note?"));
4613 if (QMessageBox.question(this, tr("Confirmation"), msg,
4614 QMessageBox.StandardButton.Yes,
4615 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4619 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4620 selectedNoteGUIDs.add(currentNoteGuid);
4621 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4622 listManager.deleteNote(selectedNoteGUIDs.get(i));
4625 // If we are deleting from the trash.
4626 if (Global.verifyDelete()) {
4628 if (selectedNoteGUIDs.size() > 1) {
4629 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4632 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4634 msg = new String(tr("Permanently delete note selected note?"));
4636 if (QMessageBox.question(this, "Confirmation", msg,
4637 QMessageBox.StandardButton.Yes,
4638 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4642 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4643 selectedNoteGUIDs.add(currentNoteGuid);
4644 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4645 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4646 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4647 if (modelIndex != null) {
4648 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4649 String tableGuid = (String)ix.values().toArray()[0];
4650 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4651 listManager.getNoteTableModel().removeRow(j);
4656 listManager.expungeNote(selectedNoteGUIDs.get(i));
4659 currentNoteGuid = "";
4660 listManager.loadNotesIndex();
4661 noteIndexUpdated(false);
4662 refreshEvernoteNote(true);
4663 scrollToGuid(currentNoteGuid);
4664 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4667 @SuppressWarnings("unused")
4668 private void addNote() {
4669 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4670 // browserWindow.setEnabled(true);
4671 browserWindow.setReadOnly(false);
4673 Calendar currentTime = new GregorianCalendar();
4674 StringBuffer noteString = new StringBuffer(100);
4675 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4676 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4679 if (Global.overrideDefaultFont()) {
4680 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4681 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4682 noteString.append("<br clear=\"none\" />\n");
4683 noteString.append("</span>\n</font>\n");
4685 noteString.append("<br clear=\"none\" />\n");
4686 noteString.append("</en-note>");
4688 Long l = new Long(currentTime.getTimeInMillis());
4689 String randint = new String(Long.toString(l));
4691 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4693 // for the first non-archived notebook. Finally, if nothing else we
4694 // pick the first notebook in the list.
4695 String notebook = null;
4696 listManager.getNotebookIndex().get(0).getGuid();
4697 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4698 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4699 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4700 notebook = currentSelectedNotebook.text(2);
4702 boolean found = false;
4703 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4704 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4705 boolean match = false;
4706 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4707 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4709 j = listManager.getArchiveNotebookIndex().size();
4713 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4714 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4716 // Now we have a list of good notebooks, so we can look for the default
4718 for (int i=0; i<goodNotebooks.size(); i++) {
4719 if (goodNotebooks.get(i).isDefaultNotebook()) {
4720 notebook = goodNotebooks.get(i).getGuid();
4722 i = goodNotebooks.size();
4726 if (goodNotebooks.size() > 0 && !found)
4727 notebook = goodNotebooks.get(0).getGuid();
4730 notebook = listManager.getNotebookIndex().get(0).getGuid();
4733 Note newNote = new Note();
4734 newNote.setUpdateSequenceNum(0);
4735 newNote.setGuid(randint);
4736 newNote.setNotebookGuid(notebook);
4737 newNote.setTitle("Untitled Note");
4738 newNote.setContent(noteString.toString());
4739 newNote.setDeleted(0);
4740 newNote.setCreated(System.currentTimeMillis());
4741 newNote.setUpdated(System.currentTimeMillis());
4742 newNote.setActive(true);
4743 NoteAttributes na = new NoteAttributes();
4744 na.setLatitude(0.0);
4745 na.setLongitude(0.0);
4746 na.setAltitude(0.0);
4747 newNote.setAttributes(new NoteAttributes());
4748 newNote.setTagGuids(new ArrayList<String>());
4749 newNote.setTagNames(new ArrayList<String>());
4751 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4752 if (Global.newNoteWithSelectedTags()) {
4753 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4754 QTreeWidgetItem currentSelection;
4755 for (int i=0; i<selections.size(); i++) {
4756 currentSelection = selections.get(i);
4757 newNote.getTagGuids().add(currentSelection.text(2));
4758 newNote.getTagNames().add(currentSelection.text(0));
4762 conn.getNoteTable().addNote(newNote, true);
4763 NoteMetadata metadata = new NoteMetadata();
4764 metadata.setGuid(newNote.getGuid());
4765 metadata.setDirty(true);
4766 listManager.addNote(newNote, metadata);
4767 // noteTableView.insertRow(newNote, true, -1);
4769 currentNote = newNote;
4770 currentNoteGuid = currentNote.getGuid();
4771 noteTableView.clearSelection();
4772 refreshEvernoteNote(true);
4773 listManager.countNotebookResults(listManager.getNoteIndex());
4774 browserWindow.titleLabel.setFocus();
4775 browserWindow.titleLabel.selectAll();
4776 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4778 // If the window is hidden, then we want to popup this in an external window &
4782 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4784 // Restore a note from the trash;
4785 @SuppressWarnings("unused")
4786 private void restoreNote() {
4788 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4789 selectedNoteGUIDs.add(currentNoteGuid);
4790 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4791 listManager.restoreNote(selectedNoteGUIDs.get(i));
4793 currentNoteGuid = "";
4794 listManager.loadNotesIndex();
4795 noteIndexUpdated(false);
4798 // Search a note for specific txt
4799 @SuppressWarnings("unused")
4800 private void findText() {
4802 find.setFocusOnTextField();
4804 @SuppressWarnings("unused")
4805 private void doFindText() {
4806 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4809 @SuppressWarnings("unused")
4810 private void updateNoteTitle(String guid, String title) {
4811 listManager.setNoteSynchronized(guid, false);
4813 // Signal received that note content has changed. Normally we just need the guid to remove
4814 // it from the cache.
4815 @SuppressWarnings("unused")
4816 private void invalidateNoteCache(String guid, String content) {
4817 noteCache.remove(guid);
4818 refreshEvernoteNote(true);
4820 // Signal received that a note guid has changed
4821 @SuppressWarnings("unused")
4822 private void noteGuidChanged(String oldGuid, String newGuid) {
4823 if (noteCache.containsKey(oldGuid)) {
4824 if (!oldGuid.equals(currentNoteGuid)) {
4825 String cache = noteCache.get(oldGuid);
4826 noteCache.put(newGuid, cache);
4827 noteCache.remove(oldGuid);
4829 noteCache.remove(oldGuid);
4830 noteCache.put(newGuid, browserWindow.getContent());
4834 listManager.updateNoteGuid(oldGuid, newGuid, false);
4835 if (currentNoteGuid.equals(oldGuid)) {
4836 if (currentNote != null)
4837 currentNote.setGuid(newGuid);
4838 currentNoteGuid = newGuid;
4841 if (externalWindows.containsKey(oldGuid)) {
4842 ExternalBrowse b = externalWindows.get(oldGuid);
4843 externalWindows.remove(oldGuid);
4844 b.getBrowserWindow().getNote().setGuid(newGuid);
4845 externalWindows.put(newGuid, b);
4848 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4849 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4850 noteTableView.proxyModel.addGuid(newGuid, listManager.getNoteMetadata().get(newGuid));
4851 i=listManager.getNoteIndex().size();
4855 if (listManager.getNoteTableModel().metaData.containsKey(oldGuid)) {
4856 NoteMetadata meta = listManager.getNoteTableModel().metaData.get(oldGuid);
4857 listManager.getNoteTableModel().metaData.put(newGuid, meta);
4858 listManager.getNoteTableModel().metaData.remove(oldGuid);
4862 // Toggle the note editor button bar
4863 private void toggleEditorButtonBar() {
4864 if (browserWindow.buttonsVisible) {
4865 browserWindow.hideButtons();
4866 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4867 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4869 browserWindow.buttonsVisible = true;
4870 showEditorButtons(browserWindow);
4872 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4874 // Show editor buttons
4875 private void showEditorButtons(BrowserWindow browser) {
4876 browser.buttonLayout.setVisible(true);
4877 browser.undoAction.setVisible(false);
4879 browser.undoButton.setVisible(false);
4881 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4882 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4883 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4884 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4885 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4886 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4887 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4888 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4889 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4890 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4891 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4892 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4893 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4894 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4895 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4896 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4897 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4898 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4899 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4900 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4901 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4902 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4903 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4905 private void duplicateNote(String guid) {
4907 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4908 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4909 oldNote.setContent(conn.getNoteTable().getNoteContentNoUTFConversion(guid));
4910 oldNote.setResources(resList);
4911 duplicateNote(oldNote);
4913 private void duplicateNote(Note oldNote) {
4915 // Now that we have a good notebook guid, we need to move the conflicting note
4916 // to the local notebook
4917 Calendar currentTime = new GregorianCalendar();
4918 Long l = new Long(currentTime.getTimeInMillis());
4919 String newGuid = new String(Long.toString(l));
4921 // Note newNote = oldNote.deepCopy();
4922 Note newNote = (Note)Global.deepCopy(oldNote);
4923 newNote.setUpdateSequenceNum(0);
4924 newNote.setGuid(newGuid);
4925 newNote.setDeleted(0);
4926 newNote.setActive(true);
4929 List<String> tagNames = new ArrayList<String>();
4930 List<String> tagGuids = new ArrayList<String>();;
4931 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4932 tagNames.add(oldNote.getTagNames().get(i));
4933 tagGuids.add(oldNote.getTagGuids().get(i));
4936 // Sort note Tags to make them look nice
4937 for (int i=0; i<tagNames.size()-1; i++) {
4938 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4939 String n1 = tagNames.get(i);
4940 String n2 = tagNames.get(i+1);
4941 tagNames.set(i, n2);
4942 tagNames.set(i+1, n1);
4945 newNote.setTagGuids(tagGuids);
4946 newNote.setTagNames(tagNames);
4948 // Add tag guids to note
4951 // Duplicate resources
4952 List<Resource> resList = oldNote.getResources();
4953 if (resList == null)
4954 resList = new ArrayList<Resource>();
4956 for (int i=0; i<resList.size(); i++) {
4958 while (l == prevGuid) {
4959 currentTime = new GregorianCalendar();
4960 l = new Long(currentTime.getTimeInMillis());
4963 String newResGuid = new String(Long.toString(l));
4964 resList.get(i).setNoteGuid(newGuid);
4965 resList.get(i).setGuid(newResGuid);
4966 resList.get(i).setUpdateSequenceNum(0);
4967 resList.get(i).setActive(true);
4968 conn.getNoteTable().noteResourceTable.saveNoteResource(
4969 (Resource)Global.deepCopy(resList.get(i)), true);
4971 newNote.setResources(resList);
4973 // Add note to the database
4974 conn.getNoteTable().addNote(newNote, true);
4975 NoteMetadata metaData = new NoteMetadata();
4976 NoteMetadata oldMeta = listManager.getNoteMetadata().get(oldNote.getGuid());
4977 metaData.copy(oldMeta);
4978 metaData.setGuid(newNote.getGuid());
4979 listManager.addNote(newNote, metaData);
4980 noteTableView.insertRow(newNote, metaData, true, -1);
4981 currentNoteGuid = newNote.getGuid();
4982 currentNote = newNote;
4983 refreshEvernoteNote(true);
4984 listManager.countNotebookResults(listManager.getNoteIndex());
4988 @SuppressWarnings("unused")
4989 private void allNotes() {
4990 clearAttributeFilter();
4991 clearNotebookFilter();
4992 clearSavedSearchFilter();
4995 searchField.clear();
4996 if (Global.mimicEvernoteInterface) {
4997 notebookTree.selectGuid("");
4999 notebookTreeSelection();
5000 refreshEvernoteNote(true);
5003 @SuppressWarnings("unused")
5004 private void mergeNotes() {
5005 logger.log(logger.HIGH, "Merging notes");
5008 String masterGuid = null;
5009 List<String> sources = new ArrayList<String>();
5011 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
5012 int r = noteTableView.selectionModel().selectedRows().get(i).row();
5013 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
5014 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5016 masterGuid = (String)ix.values().toArray()[0];
5018 sources.add((String)ix.values().toArray()[0]);
5021 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
5022 logger.log(logger.EXTREME, "Children count: "+sources.size());
5023 mergeNoteContents(masterGuid, sources);
5024 currentNoteGuid = masterGuid;
5025 noteIndexUpdated(false);
5026 refreshEvernoteNote(true);
5029 private void mergeNoteContents(String targetGuid, List<String> sources) {
5030 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
5031 String newContent = target.getContent();
5032 newContent = newContent.replace("</en-note>", "<br></br>");
5034 for (int i=0; i<sources.size(); i++) {
5035 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
5036 if (source.isSetTitle()) {
5037 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
5039 String sourceContent = source.getContent();
5040 logger.log(logger.EXTREME, "Merging contents into note");
5041 logger.log(logger.EXTREME, sourceContent);
5042 logger.log(logger.EXTREME, "End of content");
5043 int startOfNote = sourceContent.indexOf("<en-note>");
5044 sourceContent = sourceContent.substring(startOfNote+9);
5045 int endOfNote = sourceContent.indexOf("</en-note>");
5046 sourceContent = sourceContent.substring(0,endOfNote);
5047 newContent = newContent + sourceContent;
5048 logger.log(logger.EXTREME, "New note content");
5049 logger.log(logger.EXTREME, newContent);
5050 logger.log(logger.EXTREME, "End of content");
5051 for (int j=0; j<source.getResourcesSize(); j++) {
5052 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
5053 Resource r = source.getResources().get(j);
5054 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
5056 Calendar currentTime = new GregorianCalendar();
5057 Long l = new Long(currentTime.getTimeInMillis());
5061 while (l == prevGuid) {
5062 currentTime = new GregorianCalendar();
5063 l = new Long(currentTime.getTimeInMillis());
5065 String newResGuid = new String(Long.toString(l));
5066 newRes.setNoteGuid(targetGuid);
5067 newRes.setGuid(newResGuid);
5068 newRes.setUpdateSequenceNum(0);
5069 newRes.setActive(true);
5070 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5073 logger.log(logger.EXTREME, "Updating note");
5074 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5075 for (int i=0; i<sources.size(); i++) {
5076 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5077 listManager.deleteNote(sources.get(i));
5079 logger.log(logger.EXTREME, "Exiting merge note");
5081 // A resource within a note has had a guid change
5082 @SuppressWarnings("unused")
5083 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5084 if (oldGuid != null && !oldGuid.equals(newGuid))
5085 Global.resourceMap.put(oldGuid, newGuid);
5087 // View a thumbnail of the note
5088 public void thumbnailView() {
5090 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5091 QFile thumbnail = new QFile(thumbnailName);
5092 if (!thumbnail.exists()) {
5094 QImage img = new QImage();
5095 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5096 thumbnailViewer.setThumbnail(img);
5098 thumbnailViewer.setThumbnail(thumbnailName);
5099 if (!thumbnailViewer.isVisible())
5100 thumbnailViewer.showFullScreen();
5102 // An error happened while saving a note. Inform the user
5103 @SuppressWarnings("unused")
5104 private void saveRunnerError(String guid, String msg) {
5106 String title = "*Unknown*";
5107 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5108 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5109 title = listManager.getMasterNoteIndex().get(i).getTitle();
5110 i=listManager.getMasterNoteIndex().size();
5113 msg = tr("An error has happened while saving the note \"") +title+
5114 tr("\".\n\nThis is probably due to a document that is too complex for NixNote to process. "+
5115 "As a result, changes to the note may not be saved properly in the database."+
5116 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5117 "\nbe lost. Please review the note to recover any critical data before restarting.");
5119 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5122 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5123 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5124 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5125 // Find an idle preview object
5126 for (int i=0; i<thumbGenerators.size(); i++) {
5127 if (thumbGenerators.get(i).mutex.tryLock()) {
5128 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5129 thumbGenerators.get(i).loadContent(guid, html, zoom);
5133 if (thumbGenerators.size() >= 1) {
5134 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5138 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5139 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5140 thumbGenerators.add(preview);
5142 if (preview.mutex.tryLock()) {
5143 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5144 preview.loadContent(guid, html, zoom);
5146 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5151 //**********************************************************
5152 //**********************************************************
5153 //* Online user actions
5154 //**********************************************************
5155 //**********************************************************
5156 private void setupOnlineMenu() {
5157 if (!Global.isConnected) {
5158 menuBar.noteOnlineHistoryAction.setEnabled(false);
5159 menuBar.selectiveSyncAction.setEnabled(false);
5162 menuBar.noteOnlineHistoryAction.setEnabled(true);
5163 menuBar.selectiveSyncAction.setEnabled(true);
5166 @SuppressWarnings("unused")
5167 private void viewNoteHistory() {
5168 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5170 if (currentNote.getUpdateSequenceNum() == 0) {
5171 setMessage(tr("Note has never been synchronized."));
5172 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5176 setMessage(tr("Getting Note History"));
5178 Note currentOnlineNote = null;
5181 if (Global.isPremium())
5182 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5184 versions = new ArrayList<NoteVersionId>();
5185 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5186 } catch (EDAMUserException e) {
5187 setMessage("EDAMUserException: " +e.getMessage());
5189 } catch (EDAMSystemException e) {
5190 setMessage("EDAMSystemException: " +e.getMessage());
5192 } catch (EDAMNotFoundException e) {
5193 setMessage(tr("Note not found on server."));
5194 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5196 } catch (TException e) {
5197 setMessage("EDAMTransactionException: " +e.getMessage());
5201 // If we've gotten this far, we have a good note.
5202 if (historyWindow == null) {
5203 historyWindow = new OnlineNoteHistory(logger, conn);
5204 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5205 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5206 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5208 historyWindow.historyCombo.clear();
5210 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5211 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5213 historyWindow.setCurrent(isDirty);
5215 loadHistoryWindowContent(currentOnlineNote);
5216 historyWindow.load(versions);
5217 setMessage(tr("History retrieved"));
5219 historyWindow.exec();
5221 private Note reloadHistoryWindow(String selection) {
5223 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5224 String dateTimeFormat = new String(fmt);
5225 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5229 for (int i=0; i<versions.size(); i++) {
5230 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5231 if (versionDate.toString().equals(selection))
5235 if (index > -1 || selection.indexOf("Current") > -1) {
5236 Note historyNote = null;
5239 usn = versions.get(index).getUpdateSequenceNum();
5240 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5242 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5243 } catch (EDAMUserException e) {
5244 setMessage("EDAMUserException: " +e.getMessage());
5247 } catch (EDAMSystemException e) {
5248 setMessage("EDAMSystemException: " +e.getMessage());
5251 } catch (EDAMNotFoundException e) {
5252 setMessage("EDAMNotFoundException: " +e.getMessage());
5255 } catch (TException e) {
5256 setMessage("EDAMTransactionException: " +e.getMessage());
5262 if (historyNote != null)
5263 historyWindow.setContent(historyNote);
5269 private void loadHistoryWindowContent(Note note) {
5270 note.setUpdateSequenceNum(0);
5271 historyWindow.setContent(note);
5273 @SuppressWarnings("unused")
5274 private void restoreHistoryNoteAsNew() {
5275 setMessage(tr("Restoring as new note."));
5276 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5277 setMessage(tr("Note has been restored as a new note."));
5279 @SuppressWarnings("unused")
5280 private void restoreHistoryNote() {
5281 setMessage(tr("Restoring note."));
5282 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5283 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5286 for (int i=0; i<n.getResourcesSize(); i++) {
5287 n.getResources().get(i).setActive(true);
5288 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5290 NoteMetadata metadata = new NoteMetadata();
5291 metadata.setGuid(n.getGuid());
5292 listManager.addNote(n, metadata);
5293 conn.getNoteTable().addNote(n, true);
5294 refreshEvernoteNote(true);
5295 setMessage(tr("Note has been restored."));
5297 @SuppressWarnings("unused")
5298 private void setupSelectiveSync() {
5300 // Get a list of valid notebooks
5301 List<Notebook> notebooks = null;
5302 List<Tag> tags = null;
5303 List<LinkedNotebook> linkedNotebooks = null;
5305 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5306 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5307 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5308 } catch (EDAMUserException e) {
5309 setMessage("EDAMUserException: " +e.getMessage());
5311 } catch (EDAMSystemException e) {
5312 setMessage("EDAMSystemException: " +e.getMessage());
5314 } catch (TException e) {
5315 setMessage("EDAMTransactionException: " +e.getMessage());
5317 } catch (EDAMNotFoundException e) {
5318 setMessage("EDAMNotFoundException: " +e.getMessage());
5322 // Split up notebooks into synchronized & non-synchronized
5323 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5324 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5326 for (int i=notebooks.size()-1; i>=0; i--) {
5327 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5328 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5329 ignoredBooks.add(notebooks.get(i));
5330 j=dbIgnoredNotebooks.size();
5335 // split up tags into synchronized & non-synchronized
5336 List<Tag> ignoredTags = new ArrayList<Tag>();
5337 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5339 for (int i=tags.size()-1; i>=0; i--) {
5340 for (int j=0; j<dbIgnoredTags.size(); j++) {
5341 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5342 ignoredTags.add(tags.get(i));
5343 j=dbIgnoredTags.size();
5348 // split up linked notebooks into synchronized & non-synchronized
5349 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5350 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5351 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5352 String notebookGuid = linkedNotebooks.get(i).getGuid();
5353 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5354 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5355 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5356 j=dbIgnoredLinkedNotebooks.size();
5361 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5363 if (!ignore.okClicked())
5368 // Clear out old notebooks & add the new ones
5369 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5370 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5371 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5374 List<String> newNotebooks = new ArrayList<String>();
5375 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5376 String text = ignore.getIgnoredBookList().takeItem(i).text();
5377 for (int j=0; j<notebooks.size(); j++) {
5378 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5379 Notebook n = notebooks.get(j);
5380 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5382 newNotebooks.add(n.getGuid());
5387 // Clear out old tags & add new ones
5388 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5389 for (int i=0; i<oldIgnoreTags.size(); i++) {
5390 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5393 List<String> newTags = new ArrayList<String>();
5394 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5395 String text = ignore.getIgnoredTagList().takeItem(i).text();
5396 for (int j=0; j<tags.size(); j++) {
5397 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5398 Tag t = tags.get(j);
5399 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5400 newTags.add(t.getGuid());
5406 // Clear out old tags & add new ones
5407 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5408 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5409 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5412 List<String> newLinked = new ArrayList<String>();
5413 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5414 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5415 for (int j=0; j<linkedNotebooks.size(); j++) {
5416 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5417 LinkedNotebook t = linkedNotebooks.get(j);
5418 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5419 newLinked.add(t.getGuid());
5420 j=linkedNotebooks.size();
5425 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5431 //**********************************************************
5432 //**********************************************************
5433 //* XML Modifying methods
5434 //**********************************************************
5435 //**********************************************************
5436 // An error has happended fetching a resource. let the user know
5437 private void resourceErrorMessage() {
5441 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5442 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5443 "In a perfect world this wouldn't happen, but it has.\n" +
5444 "It is embarasing when a program like me, designed to save all your\n"+
5445 "precious data, has a problem finding data.\n\n" +
5446 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5447 "In the mean time, I'm not going to let you make changes to this note.\n" +
5448 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5449 "this note on the Evernote servers. Sorry."+
5450 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5452 browserWindow.setReadOnly(true);
5459 //**********************************************************
5460 //**********************************************************
5462 //**********************************************************
5463 //**********************************************************
5464 // We should now do a sync with Evernote
5465 private void syncTimer() {
5466 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5467 syncRunner.syncNeeded = true;
5468 syncRunner.disableUploads = Global.disableUploads;
5470 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5472 private void syncStart() {
5473 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5475 if (!syncRunning && Global.isConnected) {
5476 syncRunner.setConnected(true);
5477 syncRunner.setKeepRunning(Global.keepRunning);
5478 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5480 if (syncThreadsReady > 0) {
5481 thumbnailRunner.interrupt = true;
5482 saveNoteIndexWidth();
5483 saveNoteColumnPositions();
5484 if (syncRunner.addWork("SYNC")) {
5486 syncRunner.syncNeeded = true;
5491 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5493 @SuppressWarnings("unused")
5494 private void syncThreadComplete(Boolean refreshNeeded) {
5495 setMessage(tr("Finalizing Synchronization"));
5497 syncRunning = false;
5498 syncRunner.syncNeeded = false;
5499 synchronizeAnimationTimer.stop();
5500 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5502 if (currentNote == null) {
5503 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5505 listManager.refreshNoteMetadata();
5506 noteIndexUpdated(false);
5507 noteTableView.selectionModel().blockSignals(true);
5508 scrollToGuid(currentNoteGuid);
5509 noteTableView.selectionModel().blockSignals(false);
5510 refreshEvernoteNote(false);
5511 scrollToGuid(currentNoteGuid);
5514 // Check to see if there were any shared notebook errors
5515 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5516 String guid = syncRunner.errorSharedNotebooks.get(0);
5517 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5518 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5519 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5521 if (syncDialog.okPressed()) {
5522 if (syncDialog.doNothing.isChecked()) {
5523 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5526 if (syncDialog.deleteNotebook.isChecked()) {
5527 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5528 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5529 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5530 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5533 /* if (syncDialog.convertToLocal.isChecked()) {
5534 conn.getNotebookTable().convertFromSharedNotebook(notebookGuid, true);
5535 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5538 if (syncDialog.convertToShared.isChecked()) {
5539 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5540 conn.getNotebookTable().convertFromSharedNotebook(notebookGuid, false);
5548 // Finalize the synchronization
5549 if (!syncRunner.error)
5550 setMessage(tr("Synchronization Complete"));
5552 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5553 logger.log(logger.MEDIUM, "Sync complete.");
5555 public void saveUploadAmount(long t) {
5556 Global.saveUploadAmount(t);
5558 public void saveUserInformation(User user) {
5559 Global.saveUserInformation(user);
5561 public void saveEvernoteUpdateCount(int i) {
5562 Global.saveEvernoteUpdateCount(i);
5564 public void refreshLists() {
5565 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5567 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5568 tagIndexUpdated(true);
5569 notebookIndexUpdated();
5570 savedSearchIndexUpdated();
5571 listManager.loadNotesIndex();
5573 noteTableView.selectionModel().blockSignals(true);
5574 noteIndexUpdated(true);
5575 noteTableView.selectionModel().blockSignals(false);
5576 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5580 @SuppressWarnings("unused")
5581 private void authTimer() {
5582 Calendar cal = Calendar.getInstance();
5584 // If we are not connected let's get out of here
5585 if (!Global.isConnected)
5588 // If this is the first time through, then we need to set this
5589 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5590 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5592 // long now = new Date().getTime();
5593 // if (now > Global.authRefreshTime && Global.isConnected) {
5594 syncRunner.authRefreshNeeded = true;
5598 @SuppressWarnings("unused")
5599 private void authRefreshComplete(boolean goodSync) {
5600 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5601 Global.isConnected = syncRunner.isConnected;
5603 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5604 authTimer.start(1000*60*15);
5605 logger.log(logger.LOW, "Authentication token has been renewed");
5606 // setMessage("Authentication token has been renewed.");
5608 authTimer.start(1000*60*5);
5609 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5610 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5612 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5616 @SuppressWarnings("unused")
5617 private synchronized void indexTimer() {
5618 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5621 if (!indexDisabled && indexRunner.idle) {
5622 thumbnailRunner.interrupt = true;
5623 indexRunner.addWork("SCAN");
5625 logger.log(logger.EXTREME, "Leaving NixNote index timer");
5628 @SuppressWarnings("unused")
5629 private void indexStarted() {
5630 setMessage(tr("Indexing notes"));
5632 @SuppressWarnings("unused")
5633 private void indexComplete() {
5634 setMessage(tr("Index complete"));
5636 @SuppressWarnings("unused")
5637 private synchronized void toggleNoteIndexing() {
5638 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5639 indexDisabled = !indexDisabled;
5641 setMessage(tr("Indexing is now enabled."));
5643 setMessage(tr("Indexing is now disabled."));
5644 menuBar.disableIndexing.setChecked(indexDisabled);
5645 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5648 @SuppressWarnings("unused")
5649 private void threadMonitorCheck() {
5654 alive = listManager.threadCheck(Global.tagCounterThreadId);
5657 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5658 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died. I recommend "+
5659 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5660 disableTagThreadCheck = true;
5665 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5667 notebookThreadDeadCount++;
5668 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5669 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died. I recommend "+
5670 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5671 disableNotebookThreadCheck=true;
5674 notebookThreadDeadCount=0;
5676 alive = listManager.threadCheck(Global.trashCounterThreadId);
5679 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5680 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died. I recommend "+
5681 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5682 disableTrashThreadCheck = true;
5687 alive = listManager.threadCheck(Global.saveThreadId);
5689 saveThreadDeadCount++;
5690 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5691 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died. I recommend "+
5692 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5693 disableSaveThreadCheck = true;
5696 saveThreadDeadCount=0;
5698 if (!syncThread.isAlive()) {
5699 syncThreadDeadCount++;
5700 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5701 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died. I recommend "+
5702 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5703 disableSyncThreadCheck = true;
5706 syncThreadDeadCount=0;
5708 if (!indexThread.isAlive()) {
5709 indexThreadDeadCount++;
5710 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5711 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died. I recommend "+
5712 "checking stopping NixNote, saving the logs for later viewing, and restarting. Sorry."));
5713 disableIndexThreadCheck = true;
5716 indexThreadDeadCount=0;
5721 private void thumbnailTimer() {
5722 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5723 thumbnailRunner.addWork("SCAN");
5727 //**************************************************
5728 //* Backup & Restore
5729 //**************************************************
5730 @SuppressWarnings("unused")
5731 private void databaseBackup() {
5732 QFileDialog fd = new QFileDialog(this);
5733 fd.setFileMode(FileMode.AnyFile);
5734 fd.setConfirmOverwrite(true);
5735 fd.setWindowTitle(tr("Backup Database"));
5736 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5737 fd.setAcceptMode(AcceptMode.AcceptSave);
5738 if (saveLastPath == null || saveLastPath.equals(""))
5739 fd.setDirectory(System.getProperty("user.home"));
5741 fd.setDirectory(saveLastPath);
5742 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5748 saveLastPath = fd.selectedFiles().get(0);
5749 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5750 setMessage(tr("Backing up database"));
5752 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5754 ExportData noteWriter = new ExportData(conn, true);
5755 String fileName = fd.selectedFiles().get(0);
5757 if (!fileName.endsWith(".nnex"))
5758 fileName = fileName +".nnex";
5759 noteWriter.exportData(fileName);
5760 setMessage(tr("Database backup completed."));
5765 @SuppressWarnings("unused")
5766 private void databaseRestore() {
5767 if (QMessageBox.question(this, tr("Confirmation"),
5768 tr("This is used to restore a database from backups.\n" +
5769 "It is HIGHLY recommened that this only be used to populate\n" +
5770 "an empty database. Restoring into a database that\n already has data" +
5771 " can cause problems.\n\nAre you sure you want to continue?"),
5772 QMessageBox.StandardButton.Yes,
5773 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5778 QFileDialog fd = new QFileDialog(this);
5779 fd.setFileMode(FileMode.ExistingFile);
5780 fd.setConfirmOverwrite(true);
5781 fd.setWindowTitle(tr("Restore Database"));
5782 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5783 fd.setAcceptMode(AcceptMode.AcceptOpen);
5784 if (saveLastPath == null || saveLastPath.equals(""))
5785 fd.setDirectory(System.getProperty("user.home"));
5787 fd.setDirectory(saveLastPath);
5788 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5794 saveLastPath = fd.selectedFiles().get(0);
5795 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5797 setMessage(tr("Restoring database"));
5798 ImportData noteReader = new ImportData(conn, true);
5799 noteReader.importData(fd.selectedFiles().get(0));
5801 if (noteReader.lastError != 0) {
5802 setMessage(noteReader.getErrorMessage());
5803 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5808 listManager.loadNoteTitleColors();
5810 refreshEvernoteNote(true);
5811 setMessage(tr("Database has been restored."));
5814 @SuppressWarnings("unused")
5815 private void exportNotes() {
5816 QFileDialog fd = new QFileDialog(this);
5817 fd.setFileMode(FileMode.AnyFile);
5818 fd.setConfirmOverwrite(true);
5819 fd.setWindowTitle(tr("Backup Database"));
5820 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5821 fd.setAcceptMode(AcceptMode.AcceptSave);
5822 fd.setDirectory(System.getProperty("user.home"));
5823 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5829 setMessage(tr("Exporting Notes"));
5832 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5833 selectedNoteGUIDs.add(currentNoteGuid);
5835 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5836 String fileName = fd.selectedFiles().get(0);
5838 if (!fileName.endsWith(".nnex"))
5839 fileName = fileName +".nnex";
5840 noteWriter.exportData(fileName);
5841 setMessage(tr("Export completed."));
5847 @SuppressWarnings("unused")
5848 private void importNotes() {
5849 QFileDialog fd = new QFileDialog(this);
5850 fd.setFileMode(FileMode.ExistingFile);
5851 fd.setConfirmOverwrite(true);
5852 fd.setWindowTitle(tr("Import Notes"));
5853 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5854 fd.setAcceptMode(AcceptMode.AcceptOpen);
5855 if (saveLastPath == null || saveLastPath.equals(""))
5856 fd.setDirectory(System.getProperty("user.home"));
5858 fd.setDirectory(saveLastPath);
5859 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5865 setMessage(tr("Importing Notes"));
5868 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5869 selectedNoteGUIDs.add(currentNoteGuid);
5871 ImportData noteReader = new ImportData(conn, false);
5872 String fileName = fd.selectedFiles().get(0);
5873 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5875 if (!fileName.endsWith(".nnex"))
5876 fileName = fileName +".nnex";
5877 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5878 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5880 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5882 noteReader.importData(fileName);
5884 if (noteReader.lastError != 0) {
5885 setMessage(noteReader.getErrorMessage());
5886 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5891 listManager.loadNoteTitleColors();
5893 refreshEvernoteNote(false);
5894 setMessage(tr("Notes have been imported."));
5897 setMessage(tr("Import completed."));
5904 //**************************************************
5905 //* Duplicate a note
5906 //**************************************************
5907 @SuppressWarnings("unused")
5908 private void duplicateNote() {
5910 duplicateNote(currentNoteGuid);
5913 //**************************************************
5914 //* Action from when a user clicks Copy As URL
5915 //**************************************************
5916 @SuppressWarnings("unused")
5917 private void copyAsUrlClicked() {
5918 QClipboard clipboard = QApplication.clipboard();
5919 QMimeData mime = new QMimeData();
5921 mime.setText(currentNoteGuid);
5922 List<QUrl> urls = new ArrayList<QUrl>();
5924 // Start building the URL
5925 User user = Global.getUserInformation();
5927 // Check that we have everything we need
5928 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
5929 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
5931 if (!warning.neverSynchronize())
5934 Global.setBypassSynchronizationWarning(true);
5935 user.setShardId("s0");
5941 // Start building a list of URLs based upon the selected notes
5942 noteTableView.showColumn(Global.noteTableGuidPosition);
5944 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
5945 if (!Global.isColumnVisible("guid"))
5946 noteTableView.hideColumn(Global.noteTableGuidPosition);
5948 // Check that the note is either synchronized, or in a local notebook
5949 for (int i=0; i<selections.size(); i++) {
5951 int row = selections.get(i).row();
5952 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5953 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5954 String selectedGuid = (String)ix.values().toArray()[0];
5956 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5957 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
5958 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
5959 "new notes to a local notebook."));
5964 // Start building the URLs
5965 for (int i=0; i<selections.size(); i++) {
5967 int row = selections.get(i).row();
5968 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5969 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5970 String selectedGuid = (String)ix.values().toArray()[0];
5971 mime.setText(selectedGuid);
5975 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5976 if (selectedNote.getUpdateSequenceNum() > 0) {
5980 gid = "00000000-0000-0000-0000-000000000000";
5983 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
5985 urls.add(new QUrl(url));
5988 clipboard.setMimeData(mime);
5992 //**************************************************
5994 //**************************************************
5995 public void setupFolderImports() {
5996 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5998 if (importKeepWatcher == null)
5999 importKeepWatcher = new QFileSystemWatcher();
6000 if (importDeleteWatcher == null) {
6001 importDeleteWatcher = new QFileSystemWatcher();
6002 for (int i=0; i<records.size(); i++) {
6003 if (!records.get(i).keep)
6004 folderImportDelete(records.get(i).folder);
6010 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
6011 for (int i=0; i<records.size(); i++) {
6012 if (records.get(i).keep)
6013 importKeepWatcher.addPath(records.get(i).folder);
6015 importDeleteWatcher.addPath(records.get(i).folder);
6018 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
6019 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
6021 // Look at the files already there so we don't import them again if a new file is created
6022 if (importedFiles == null) {
6023 importedFiles = new ArrayList<String>();
6024 for (int j=0; j<records.size(); j++) {
6025 QDir dir = new QDir(records.get(j).folder);
6026 List<QFileInfo> list = dir.entryInfoList();
6027 for (int k=0; k<list.size(); k++) {
6028 if (list.get(k).isFile())
6029 importedFiles.add(list.get(k).absoluteFilePath());
6034 public void folderImport() {
6035 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
6036 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
6038 if (!dialog.okClicked())
6041 // We have some sort of update.
6042 if (importKeepWatcher.directories().size() > 0)
6043 importKeepWatcher.removePaths(importKeepWatcher.directories());
6044 if (importDeleteWatcher.directories().size() > 0)
6045 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
6047 conn.getWatchFolderTable().expungeAll();
6048 // Start building from the table
6049 for (int i=0; i<dialog.table.rowCount(); i++) {
6050 QTableWidgetItem item = dialog.table.item(i, 0);
6051 String dir = item.text();
6052 item = dialog.table.item(i, 1);
6053 String notebook = item.text();
6054 item = dialog.table.item(i, 2);
6056 if (item.text().equalsIgnoreCase("Keep"))
6061 String guid = conn.getNotebookTable().findNotebookByName(notebook);
6062 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
6064 setupFolderImports();
6067 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
6069 String whichOS = System.getProperty("os.name");
6070 if (whichOS.contains("Windows"))
6071 dirName = dirName.replace('/','\\');
6073 FileImporter importer = new FileImporter(logger, conn);
6075 QDir dir = new QDir(dirName);
6076 List<QFileInfo> list = dir.entryInfoList();
6077 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6079 for (int i=0; i<list.size(); i++){
6081 boolean redundant = false;
6082 // Check if we've already imported this one or if it existed before
6083 for (int j=0; j<importedFiles.size(); j++) {
6084 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6089 importer.setFileInfo(list.get(i));
6090 importer.setFileName(list.get(i).absoluteFilePath());
6093 if (list.get(i).isFile() && importer.isValidType()) {
6095 if (!importer.importFile()) {
6096 // If we can't get to the file, it is probably locked. We'll try again later.
6097 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6098 importFilesKeep.add(list.get(i).absoluteFilePath());
6102 Note newNote = importer.getNote();
6103 newNote.setNotebookGuid(notebook);
6104 newNote.setTitle(dir.at(i));
6105 NoteMetadata metadata = new NoteMetadata();
6106 metadata.setDirty(true);
6107 metadata.setGuid(newNote.getGuid());
6108 listManager.addNote(newNote, metadata);
6109 conn.getNoteTable().addNote(newNote, true);
6110 noteTableView.insertRow(newNote, metadata, true, -1);
6111 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6112 listManager.countNotebookResults(listManager.getNoteIndex());
6113 importedFiles.add(list.get(i).absoluteFilePath());
6121 public void folderImportDelete(String dirName) {
6123 String whichOS = System.getProperty("os.name");
6124 if (whichOS.contains("Windows"))
6125 dirName = dirName.replace('/','\\');
6127 FileImporter importer = new FileImporter(logger, conn);
6128 QDir dir = new QDir(dirName);
6129 List<QFileInfo> list = dir.entryInfoList();
6130 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6132 for (int i=0; i<list.size(); i++){
6133 importer.setFileInfo(list.get(i));
6134 importer.setFileName(list.get(i).absoluteFilePath());
6136 if (list.get(i).isFile() && importer.isValidType()) {
6138 if (!importer.importFile()) {
6139 // If we can't get to the file, it is probably locked. We'll try again later.
6140 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6141 importFilesKeep.add(list.get(i).absoluteFilePath());
6145 Note newNote = importer.getNote();
6146 newNote.setNotebookGuid(notebook);
6147 newNote.setTitle(dir.at(i));
6148 NoteMetadata metadata = new NoteMetadata();
6149 metadata.setDirty(true);
6150 metadata.setGuid(newNote.getGuid());
6151 listManager.addNote(newNote, metadata);
6152 conn.getNoteTable().addNote(newNote, true);
6153 noteTableView.insertRow(newNote, metadata, true, -1);
6154 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6155 listManager.countNotebookResults(listManager.getNoteIndex());
6156 dir.remove(dir.at(i));
6162 //**************************************************
6164 //**************************************************
6165 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6166 logger.log(logger.HIGH, "Entering exernalFileEdited");
6168 // Strip URL prefix and base dir path
6169 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6170 String name = fileName.replace(dPath, "");
6171 int pos = name.lastIndexOf('.');
6174 guid = guid.substring(0,pos);
6176 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6178 guid = name.substring(0, pos);
6181 QFile file = new QFile(fileName);
6182 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
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);
6188 QByteArray binData = file.readAll();
6190 if (binData.size() == 0) {
6191 // If we can't get to the file, it is probably locked. We'll try again later.
6192 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6193 externalFiles.add(fileName);
6197 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6199 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6200 if (r == null || r.getData() == null || r.getData().getBody() == null)
6202 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6203 MessageDigest md = MessageDigest.getInstance("MD5");
6204 md.update(binData.toByteArray());
6205 byte[] hash = md.digest();
6206 String newHash = Global.byteArrayToHexString(hash);
6207 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6208 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6210 if (externalWindows.containsKey(r.getNoteGuid())) {
6211 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6212 r.getGuid(), oldHash, newHash);
6214 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6215 Data data = r.getData();
6216 data.setBody(binData.toByteArray());
6217 data.setBodyHash(hash);
6218 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6220 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6222 if (r.getNoteGuid().equals(currentNoteGuid)) {
6223 QWebSettings.setMaximumPagesInCache(0);
6224 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6225 refreshEvernoteNote(true);
6226 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6229 if (externalWindows.containsKey(r.getNoteGuid())) {
6230 QWebSettings.setMaximumPagesInCache(0);
6231 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6232 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6236 logger.log(logger.HIGH, "Exiting externalFielEdited");
6238 // This is a timer event that tries to save any external files that were edited. This
6239 // is only needed if we couldn't save a file earlier.
6240 public void externalFileEditedSaver() {
6241 for (int i=externalFiles.size()-1; i>=0; i--) {
6243 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6244 externalFileEdited(externalFiles.get(i));
6245 externalFiles.remove(i);
6246 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6248 for (int i=0; i<importFilesKeep.size(); i++) {
6250 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6251 folderImportKeep(importFilesKeep.get(i));
6252 importFilesKeep.remove(i);
6253 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6255 for (int i=0; i<importFilesDelete.size(); i++) {
6256 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6257 folderImportDelete(importFilesDelete.get(i));
6258 importFilesDelete.remove(i);
6265 // If an attachment on the current note was edited, we need to update the current notes's hash
6266 // Update a note content's hash. This happens if a resource is edited outside of NN
6267 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6268 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6270 for (;position>-1;) {
6271 endPos = browser.getContent().indexOf(">", position+1);
6272 String oldSegment = browser.getContent().substring(position,endPos);
6273 int hashPos = oldSegment.indexOf("hash=\"");
6274 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6275 String hash = oldSegment.substring(hashPos+6, hashEnd);
6276 if (hash.equalsIgnoreCase(oldHash)) {
6277 String newSegment = oldSegment.replace(oldHash, newHash);
6278 String content = browser.getContent().substring(0,position) +
6280 browser.getContent().substring(endPos);
6281 browser.setContent(new QByteArray(content));;
6284 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6289 //*************************************************
6290 //* Minimize to tray
6291 //*************************************************
6293 public void changeEvent(QEvent e) {
6294 if (e.type() == QEvent.Type.WindowStateChange) {
6295 if (isMinimized() && Global.showTrayIcon()) {
6297 QTimer.singleShot(10, this, "hide()");
6301 windowMaximized = true;
6303 windowMaximized = false;
6307 //*************************************************
6308 //* Check database userid & passwords
6309 //*************************************************
6310 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6311 Connection connection;
6314 Class.forName("org.h2.Driver");
6315 } catch (ClassNotFoundException e1) {
6316 e1.printStackTrace();
6321 String passwordString = null;
6322 if (cypherPassword==null || cypherPassword.trim().equals(""))
6323 passwordString = userPassword;
6325 passwordString = cypherPassword+" "+userPassword;
6326 connection = DriverManager.getConnection(url,userid,passwordString);
6327 } catch (SQLException e) {
6332 } catch (SQLException e) {
6333 e.printStackTrace();
6338 //*************************************************
6339 //* View / Hide source HTML for a note
6340 //*************************************************
6341 public void viewSource() {
6342 browserWindow.showSource(menuBar.viewSource.isChecked());
6344 //*************************************************
6345 // Block the program. This is used for things
6346 // like async web calls.
6347 //*************************************************
6348 @SuppressWarnings("unused")
6349 private void blockApplication(BrowserWindow b) {
6350 // Block all signals
6354 blockTimer = new QTimer();
6355 blockTimer.setSingleShot(true);
6356 blockTimer.setInterval(15000);
6357 blockTimer.timeout.connect(this, "unblockApplication()");
6362 @SuppressWarnings("unused")
6363 private void unblockApplication() {
6365 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6366 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6367 blockingWindow.unblockTime = -1;
6368 blockingWindow.awaitingHttpResponse = false;
6370 blockingWindow = null;
6371 blockSignals(false);