2 * This file is part of NixNote
3 * Copyright 2009 Randy Baumgarte
5 * This file may be licensed under the terms of of the
6 * GNU General Public License Version 2 (the ``GPL'').
8 * Software distributed under the License is distributed
9 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10 * express or implied. See the GPL for the specific language
11 * governing rights and limitations.
13 * You should have received a copy of the GPL along with this
14 * program. If not, go to http://www.gnu.org/licenses/gpl.html
15 * or write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 package cx.fbn.nevernote;
20 import java.awt.Desktop;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.net.Authenticator;
25 import java.net.PasswordAuthentication;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.SQLException;
31 import java.sql.Statement;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.SortedMap;
44 import java.util.Vector;
46 import org.apache.log4j.Level;
47 import org.apache.log4j.Logger;
48 import org.apache.thrift.TException;
49 import org.h2.tools.ChangeFileEncryption;
51 import com.evernote.edam.error.EDAMNotFoundException;
52 import com.evernote.edam.error.EDAMSystemException;
53 import com.evernote.edam.error.EDAMUserException;
54 import com.evernote.edam.notestore.NoteFilter;
55 import com.evernote.edam.notestore.NoteVersionId;
56 import com.evernote.edam.type.Data;
57 import com.evernote.edam.type.LinkedNotebook;
58 import com.evernote.edam.type.Note;
59 import com.evernote.edam.type.NoteAttributes;
60 import com.evernote.edam.type.Notebook;
61 import com.evernote.edam.type.Publishing;
62 import com.evernote.edam.type.QueryFormat;
63 import com.evernote.edam.type.Resource;
64 import com.evernote.edam.type.SavedSearch;
65 import com.evernote.edam.type.Tag;
66 import com.evernote.edam.type.User;
67 import com.trolltech.qt.QThread;
68 import com.trolltech.qt.core.QByteArray;
69 import com.trolltech.qt.core.QDateTime;
70 import com.trolltech.qt.core.QDir;
71 import com.trolltech.qt.core.QEvent;
72 import com.trolltech.qt.core.QFile;
73 import com.trolltech.qt.core.QFileInfo;
74 import com.trolltech.qt.core.QFileSystemWatcher;
75 import com.trolltech.qt.core.QIODevice;
76 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
77 import com.trolltech.qt.core.QLocale;
78 import com.trolltech.qt.core.QMimeData;
79 import com.trolltech.qt.core.QModelIndex;
80 import com.trolltech.qt.core.QSize;
81 import com.trolltech.qt.core.QTemporaryFile;
82 import com.trolltech.qt.core.QTextCodec;
83 import com.trolltech.qt.core.QThreadPool;
84 import com.trolltech.qt.core.QTimer;
85 import com.trolltech.qt.core.QTranslator;
86 import com.trolltech.qt.core.QUrl;
87 import com.trolltech.qt.core.Qt;
88 import com.trolltech.qt.core.Qt.BGMode;
89 import com.trolltech.qt.core.Qt.ItemDataRole;
90 import com.trolltech.qt.core.Qt.KeyboardModifier;
91 import com.trolltech.qt.core.Qt.MouseButton;
92 import com.trolltech.qt.core.Qt.SortOrder;
93 import com.trolltech.qt.core.Qt.WidgetAttribute;
94 import com.trolltech.qt.gui.QAbstractItemView;
95 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
96 import com.trolltech.qt.gui.QAction;
97 import com.trolltech.qt.gui.QApplication;
98 import com.trolltech.qt.gui.QClipboard;
99 import com.trolltech.qt.gui.QCloseEvent;
100 import com.trolltech.qt.gui.QColor;
101 import com.trolltech.qt.gui.QComboBox;
102 import com.trolltech.qt.gui.QCursor;
103 import com.trolltech.qt.gui.QDesktopServices;
104 import com.trolltech.qt.gui.QDialog;
105 import com.trolltech.qt.gui.QFileDialog;
106 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
107 import com.trolltech.qt.gui.QFileDialog.FileMode;
108 import com.trolltech.qt.gui.QGridLayout;
109 import com.trolltech.qt.gui.QHBoxLayout;
110 import com.trolltech.qt.gui.QIcon;
111 import com.trolltech.qt.gui.QImage;
112 import com.trolltech.qt.gui.QKeySequence;
113 import com.trolltech.qt.gui.QLabel;
114 import com.trolltech.qt.gui.QMainWindow;
115 import com.trolltech.qt.gui.QMenu;
116 import com.trolltech.qt.gui.QMessageBox;
117 import com.trolltech.qt.gui.QMessageBox.StandardButton;
118 import com.trolltech.qt.gui.QPainter;
119 import com.trolltech.qt.gui.QPalette.ColorRole;
120 import com.trolltech.qt.gui.QPixmap;
121 import com.trolltech.qt.gui.QPrintDialog;
122 import com.trolltech.qt.gui.QPrinter;
123 import com.trolltech.qt.gui.QShortcut;
124 import com.trolltech.qt.gui.QSizePolicy;
125 import com.trolltech.qt.gui.QSizePolicy.Policy;
126 import com.trolltech.qt.gui.QSpinBox;
127 import com.trolltech.qt.gui.QSplashScreen;
128 import com.trolltech.qt.gui.QSplitter;
129 import com.trolltech.qt.gui.QStatusBar;
130 import com.trolltech.qt.gui.QSystemTrayIcon;
131 import com.trolltech.qt.gui.QTableWidgetItem;
132 import com.trolltech.qt.gui.QTextEdit;
133 import com.trolltech.qt.gui.QToolBar;
134 import com.trolltech.qt.gui.QTreeWidgetItem;
135 import com.trolltech.qt.network.QNetworkAccessManager;
136 import com.trolltech.qt.network.QNetworkReply;
137 import com.trolltech.qt.network.QNetworkRequest;
138 import com.trolltech.qt.webkit.QWebPage.WebAction;
139 import com.trolltech.qt.webkit.QWebSettings;
141 import cx.fbn.nevernote.config.InitializationException;
142 import cx.fbn.nevernote.config.StartupConfig;
143 import cx.fbn.nevernote.dialog.AccountDialog;
144 import cx.fbn.nevernote.dialog.ConfigDialog;
145 import cx.fbn.nevernote.dialog.DBEncryptDialog;
146 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
147 import cx.fbn.nevernote.dialog.DatabaseStatus;
148 import cx.fbn.nevernote.dialog.FindDialog;
149 import cx.fbn.nevernote.dialog.IgnoreSync;
150 import cx.fbn.nevernote.dialog.LogFileDialog;
151 import cx.fbn.nevernote.dialog.LoginDialog;
152 import cx.fbn.nevernote.dialog.NotebookArchive;
153 import cx.fbn.nevernote.dialog.NotebookEdit;
154 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
155 import cx.fbn.nevernote.dialog.PublishNotebook;
156 import cx.fbn.nevernote.dialog.SavedSearchEdit;
157 import cx.fbn.nevernote.dialog.SetIcon;
158 import cx.fbn.nevernote.dialog.ShareNotebook;
159 import cx.fbn.nevernote.dialog.SharedNotebookSyncError;
160 import cx.fbn.nevernote.dialog.StackNotebook;
161 import cx.fbn.nevernote.dialog.SynchronizationRequiredWarning;
162 import cx.fbn.nevernote.dialog.TagEdit;
163 import cx.fbn.nevernote.dialog.TagMerge;
164 import cx.fbn.nevernote.dialog.ThumbnailViewer;
165 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
166 import cx.fbn.nevernote.dialog.WatchFolder;
167 import cx.fbn.nevernote.evernote.NoteMetadata;
168 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
169 import cx.fbn.nevernote.filters.FilterEditorTags;
170 import cx.fbn.nevernote.gui.AttributeTreeWidget;
171 import cx.fbn.nevernote.gui.BrowserWindow;
172 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
173 import cx.fbn.nevernote.gui.ExternalBrowse;
174 import cx.fbn.nevernote.gui.MainMenuBar;
175 import cx.fbn.nevernote.gui.NotebookTreeWidget;
176 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
177 import cx.fbn.nevernote.gui.SearchPanel;
178 import cx.fbn.nevernote.gui.TableView;
179 import cx.fbn.nevernote.gui.TagTreeWidget;
180 import cx.fbn.nevernote.gui.Thumbnailer;
181 import cx.fbn.nevernote.gui.TrashTreeWidget;
182 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
183 import cx.fbn.nevernote.sql.DatabaseConnection;
184 import cx.fbn.nevernote.sql.WatchFolderRecord;
185 import cx.fbn.nevernote.threads.IndexRunner;
186 import cx.fbn.nevernote.threads.SyncRunner;
187 import cx.fbn.nevernote.threads.ThumbnailRunner;
188 import cx.fbn.nevernote.utilities.AESEncrypter;
189 import cx.fbn.nevernote.utilities.ApplicationLogger;
190 import cx.fbn.nevernote.utilities.FileImporter;
191 import cx.fbn.nevernote.utilities.FileUtils;
192 import cx.fbn.nevernote.utilities.ListManager;
193 import cx.fbn.nevernote.utilities.SyncTimes;
194 import cx.fbn.nevernote.xml.ExportData;
195 import cx.fbn.nevernote.xml.ImportData;
196 import cx.fbn.nevernote.xml.ImportEnex;
197 import cx.fbn.nevernote.xml.NoteFormatter;
200 public class NeverNote extends QMainWindow{
202 QStatusBar statusBar; // Application status bar
204 DatabaseConnection conn;
206 MainMenuBar menuBar; // Main menu bar
207 FindDialog find; // Text search in note dialog
208 List<String> emitLog; // Messages displayed in the status bar;
209 QSystemTrayIcon trayIcon; // little tray icon
210 QMenu trayMenu; // System tray menu
211 QAction trayExitAction; // Exit the application
212 QAction trayShowAction; // toggle the show/hide action
213 QAction trayAddNoteAction; // Add a note from the system tray
214 QNetworkAccessManager versionChecker; // Used when checking for new versions
216 NotebookTreeWidget notebookTree; // List of notebooks
217 AttributeTreeWidget attributeTree; // List of note attributes
218 TagTreeWidget tagTree; // list of user created tags
219 SavedSearchTreeWidget savedSearchTree; // list of saved searches
220 TrashTreeWidget trashTree; // Trashcan
221 TableView noteTableView; // List of notes (the widget).
223 public BrowserWindow browserWindow; // Window containing browser & labels
224 public QToolBar toolBar; // The tool bar under the menu
225 QComboBox searchField; // search filter bar on the toolbar;
226 QShortcut searchShortcut; // Shortcut to search bar
227 boolean searchPerformed = false; // Search was done?
228 QuotaProgressBar quotaBar; // The current quota usage
230 ApplicationLogger logger;
231 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
232 List<String> selectedTagGUIDs; // List of selected tag GUIDs
233 List<String> selectedNoteGUIDs; // List of selected notes
234 String selectedSavedSearchGUID; // Currently selected saved searches
235 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
237 NoteFilter filter; // Note filter
238 String currentNoteGuid; // GUID of the current note
239 Note currentNote; // The currently viewed note
240 boolean noteDirty; // Has the note been changed?
241 boolean inkNote; // if this is an ink note, it is read only
242 boolean readOnly; // Is this note read-only?
245 ListManager listManager; // DB runnable task
247 List<QTemporaryFile> tempFiles; // Array of temporary files;
249 QTimer indexTimer; // timer to start the index thread
250 IndexRunner indexRunner; // thread to index notes
253 QTimer syncTimer; // Sync on an interval
254 QTimer syncDelayTimer; // Sync delay to free up database
255 SyncRunner syncRunner; // thread to do a sync.
256 QThread syncThread; // Thread which talks to evernote
257 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
258 QThread thumbnailThread; // Thread that generates pretty pictures
259 QTimer saveTimer; // Timer to save note contents
261 QTimer authTimer; // Refresh authentication
262 QTimer externalFileSaveTimer; // Save files altered externally
263 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
264 List<String> externalFiles; // External files to save later
265 List<String> importFilesKeep; // Auto-import files to save later
266 List<String> importFilesDelete; // Auto-import files to save later
268 int indexTime; // how often to try and index
269 boolean indexRunning; // Is indexing running?
270 boolean indexDisabled; // Is indexing disabled?
272 int syncThreadsReady; // number of sync threads that are free
273 int syncTime; // Sync interval
274 boolean syncRunning; // Is sync running?
275 boolean automaticSync; // do sync automatically?
276 QTreeWidgetItem attributeTreeSelected;
278 QAction prevButton; // Go to the previous item viewed
279 QAction nextButton; // Go to the next item in the history
280 QAction downButton; // Go to the next item in the list
281 QAction upButton; // Go to the prev. item in the list;
282 QAction synchronizeButton; // Synchronize with Evernote
283 QAction allNotesButton; // Reset & view all notes
284 QTimer synchronizeAnimationTimer; // Timer to change animation button
285 int synchronizeIconAngle; // Used to rotate sync icon
286 QAction printButton; // Print Button
287 QAction tagButton; // Tag edit button
288 QAction attributeButton; // Attribute information button
289 QAction emailButton; // Email button
290 QAction deleteButton; // Delete button
291 QAction newButton; // new Note Button;
292 QSpinBox zoomSpinner; // Zoom zoom
293 QAction searchClearButton; // Clear the search field
295 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
297 QSplitter mainLeftRightSplitter; // main splitter for left/right side
298 QSplitter leftSplitter1; // first left hand splitter
299 QSplitter browserIndexSplitter; // splitter between note index & note text
301 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
302 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
303 List<String> importedFiles; // History of imported files (so we don't import twice)
305 OnlineNoteHistory historyWindow; // online history window
306 List<NoteVersionId> versions; // history versions
308 QTimer threadMonitorTimer; // Timer to watch threads.
309 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
310 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
311 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
312 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
313 int tagDeadCount=0; // number of consecutive dead times for the tag thread
314 int trashDeadCount=0; // number of consecutive dead times for the trash thread
315 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
316 boolean disableTagThreadCheck=false;
317 boolean disableNotebookThreadCheck=false;
318 boolean disableTrashThreadCheck=false;
319 boolean disableSaveThreadCheck=false;
320 boolean disableSyncThreadCheck=false;
321 boolean disableIndexThreadCheck=false;
323 HashMap<String, String> noteCache; // Cash of note content
324 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
325 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
326 List<String> historyGuids; // GUIDs of previously viewed items
327 int historyPosition; // Position within the viewed items
328 boolean fromHistory; // Is this from the history queue?
329 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
330 List<Thumbnailer> thumbGenerators; // generate preview image
331 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
332 boolean encryptOnShutdown; // should I encrypt when I close?
333 boolean decryptOnShutdown; // should I decrypt on shutdown;
334 String encryptCipher; // What cipher should I use?
335 Signal0 minimizeToTray;
336 boolean windowMaximized = false; // Keep track of the window state for restores
337 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
338 List<QPixmap> syncIcons; // Array of icons used in sync animation
339 private boolean closeAction = false; // Used to say when to close or when to minimize
340 private static Logger log = Logger.getLogger(NeverNote.class);
341 private String saveLastPath; // last path we used
342 private final QTimer messageTimer; // Timer to clear the status message.
343 private QTimer blockTimer;
344 BrowserWindow blockingWindow;
346 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
349 //***************************************************************
350 //***************************************************************
351 //** Constructor & main entry point
352 //***************************************************************
353 //***************************************************************
354 // Application Constructor
355 @SuppressWarnings("static-access")
356 public NeverNote(DatabaseConnection dbConn) {
358 if (conn.getConnection() == null) {
359 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
360 "is accessing the database or NixNote is already running.\n\n" +
361 "Please end any other process or shutdown the other NixNote before starting.\n\nExiting program."));
363 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
366 setObjectName("mainWindow");
367 // thread().setPriority(Thread.MAX_PRIORITY);
369 logger = new ApplicationLogger("nevernote.log");
370 logger.log(logger.HIGH, "Starting Application");
372 decryptOnShutdown = false;
373 encryptOnShutdown = false;
374 conn.checkDatabaseVersion();
378 // Start building the invalid XML tables
379 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
380 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
382 for (int i=0; i<elements.size(); i++) {
383 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
386 logger.log(logger.EXTREME, "Starting GUI build");
388 QTranslator nevernoteTranslator = new QTranslator();
389 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
390 QApplication.instance().installTranslator(nevernoteTranslator);
392 Global.originalPalette = QApplication.palette();
393 QApplication.setStyle(Global.getStyle());
394 if (Global.useStandardPalette())
395 QApplication.setPalette(QApplication.style().standardPalette());
396 setWindowTitle(tr("NixNote"));
398 mainLeftRightSplitter = new QSplitter();
399 setCentralWidget(mainLeftRightSplitter);
400 leftSplitter1 = new QSplitter();
401 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
403 browserIndexSplitter = new QSplitter();
404 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
406 //* Setup threads & thread timers
407 // int indexRunnerCount = Global.getIndexThreads();
408 // indexRunnerCount = 1;
409 QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount); // increase max thread count
411 logger.log(logger.EXTREME, "Building list manager");
412 listManager = new ListManager(conn, logger);
414 logger.log(logger.EXTREME, "Building index runners & timers");
415 indexRunner = new IndexRunner("indexRunner.log",
416 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
417 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
418 indexThread = new QThread(indexRunner, "Index Thread");
419 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
420 indexRunner.indexImageRecognition = Global.indexImageRecognition();
421 indexRunner.indexNoteBody = Global.indexNoteBody();
422 indexRunner.indexNoteTitle = Global.indexNoteTitle();
423 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
426 synchronizeAnimationTimer = new QTimer();
427 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
429 indexTimer = new QTimer();
430 indexTime = 1000*Global.getIndexThreadSleepInterval();
431 indexTimer.start(indexTime); // Start indexing timer
432 indexTimer.timeout.connect(this, "indexTimer()");
433 indexDisabled = false;
434 indexRunning = false;
436 logger.log(logger.EXTREME, "Setting sync thread & timers");
438 syncRunner = new SyncRunner("syncRunner.log",
439 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
440 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
441 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
442 syncTimer = new QTimer();
443 syncTimer.timeout.connect(this, "syncTimer()");
444 syncRunner.status.message.connect(this, "setMessage(String)");
445 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
446 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
449 automaticSync = true;
450 syncTimer.start(syncTime*60*1000);
452 automaticSync = false;
455 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
456 syncThread = new QThread(syncRunner, "Synchronization Thread");
460 logger.log(logger.EXTREME, "Starting thumnail thread");
461 pdfReadyQueue = new ArrayList<String>();
462 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
463 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
464 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
465 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
466 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
467 thumbnailThread.start();
468 thumbGenerators = new ArrayList<Thumbnailer>();
469 thumbnailTimer = new QTimer();
470 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
472 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
473 thumbnailTimer.start();
475 logger.log(logger.EXTREME, "Starting authentication timer");
476 authTimer = new QTimer();
477 authTimer.timeout.connect(this, "authTimer()");
478 authTimer.start(1000*60*15);
479 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
481 logger.log(logger.EXTREME, "Setting save note timer");
482 saveTimer = new QTimer();
483 saveTimer.timeout.connect(this, "saveNote()");
484 if (Global.getAutoSaveInterval() > 0) {
485 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
488 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
490 logger.log(logger.EXTREME, "Starting external file monitor timer");
491 externalFileSaveTimer = new QTimer();
492 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
493 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
494 externalFiles = new ArrayList<String>();
495 importFilesDelete = new ArrayList<String>();
496 importFilesKeep = new ArrayList<String>();
497 externalFileSaveTimer.start();
499 notebookTree = new NotebookTreeWidget(conn);
500 attributeTree = new AttributeTreeWidget();
501 tagTree = new TagTreeWidget(conn);
502 savedSearchTree = new SavedSearchTreeWidget();
503 trashTree = new TrashTreeWidget();
504 noteTableView = new TableView(logger, listManager);
506 searchField = new QComboBox();
507 searchField.setObjectName("searchField");
508 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
509 searchField.setEditable(true);
510 searchField.activatedIndex.connect(this, "searchFieldChanged()");
511 searchField.setDuplicatesEnabled(false);
512 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
513 searchShortcut = new QShortcut(this);
514 setupShortcut(searchShortcut, "Focus_Search");
515 searchShortcut.activated.connect(this, "focusSearch()");
517 quotaBar = new QuotaProgressBar();
519 zoomSpinner = new QSpinBox();
520 zoomSpinner.setMinimum(10);
521 zoomSpinner.setMaximum(1000);
522 zoomSpinner.setAccelerated(true);
523 zoomSpinner.setSingleStep(10);
524 zoomSpinner.setValue(100);
525 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
527 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
530 QGridLayout leftGrid = new QGridLayout();
531 leftSplitter1.setContentsMargins(5, 0, 0, 7);
532 leftSplitter1.setLayout(leftGrid);
533 leftGrid.addWidget(searchLayout,1,1);
534 leftGrid.addWidget(tagTree,2,1);
535 leftGrid.addWidget(attributeTree,3,1);
536 leftGrid.addWidget(savedSearchTree,4,1);
537 leftGrid.addWidget(trashTree,5, 1);
539 // Setup the browser window
540 noteCache = new HashMap<String,String>();
541 readOnlyCache = new HashMap<String, Boolean>();
542 inkNoteCache = new HashMap<String, Boolean>();
543 browserWindow = new BrowserWindow(conn);
545 mainLeftRightSplitter.addWidget(leftSplitter1);
546 mainLeftRightSplitter.addWidget(browserIndexSplitter);
548 if (Global.getListView() == Global.View_List_Wide) {
549 browserIndexSplitter.addWidget(noteTableView);
550 browserIndexSplitter.addWidget(browserWindow);
552 mainLeftRightSplitter.addWidget(noteTableView);
553 mainLeftRightSplitter.addWidget(browserWindow);
556 // Setup the thumbnail viewer
557 thumbnailViewer = new ThumbnailViewer();
558 thumbnailViewer.upArrow.connect(this, "upAction()");
559 thumbnailViewer.downArrow.connect(this, "downAction()");
560 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
561 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
563 //Setup external browser manager
564 externalWindows = new HashMap<String, ExternalBrowse>();
566 listManager.loadNotesIndex();
567 initializeNotebookTree();
569 initializeSavedSearchTree();
570 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
571 attributeTreeSelected = null;
572 initializeNoteTable();
574 selectedNoteGUIDs = new ArrayList<String>();
575 statusBar = new QStatusBar();
576 setStatusBar(statusBar);
577 menuBar = new MainMenuBar(this);
578 emitLog = new ArrayList<String>();
580 tagTree.setDeleteAction(menuBar.tagDeleteAction);
581 tagTree.setMergeAction(menuBar.tagMergeAction);
582 tagTree.setEditAction(menuBar.tagEditAction);
583 tagTree.setAddAction(menuBar.tagAddAction);
584 tagTree.setIconAction(menuBar.tagIconAction);
585 tagTree.setVisible(Global.isWindowVisible("tagTree"));
586 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
587 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
588 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
589 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
591 if (!Global.isWindowVisible("zoom")) {
592 searchLayout.hideZoom();
593 menuBar.hideZoom.setChecked(false);
596 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
597 notebookTree.setEditAction(menuBar.notebookEditAction);
598 notebookTree.setAddAction(menuBar.notebookAddAction);
599 notebookTree.setIconAction(menuBar.notebookIconAction);
600 notebookTree.setStackAction(menuBar.notebookStackAction);
601 notebookTree.setPublishAction(menuBar.notebookPublishAction);
602 notebookTree.setShareAction(menuBar.notebookShareAction);
603 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
604 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
605 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
606 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
607 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
609 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
610 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
611 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
612 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
613 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
614 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
615 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
617 noteTableView.setAddAction(menuBar.noteAdd);
618 noteTableView.setDeleteAction(menuBar.noteDelete);
619 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
620 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
621 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
622 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
623 noteTableView.noteSignal.notePinned.connect(this, "notePinned()");
624 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
625 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
626 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
627 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
629 quotaBar.setMouseClickAction(menuBar.accountAction);
632 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
633 trashTree.setEmptyAction(menuBar.emptyTrashAction);
634 trashTree.setVisible(Global.isWindowVisible("trashTree"));
635 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
636 trashTree.updateCounts(listManager.getTrashCount());
637 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
638 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
640 noteTableView.setVisible(Global.isWindowVisible("noteList"));
641 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
643 if (!Global.isWindowVisible("editorButtonBar"))
644 toggleEditorButtonBar();
645 if (!Global.isWindowVisible("leftPanel"))
646 menuBar.hideLeftSide.setChecked(true);
647 if (Global.isWindowVisible("noteInformation"))
648 toggleNoteInformation();
649 quotaBar.setVisible(Global.isWindowVisible("quota"));
650 if (!quotaBar.isVisible())
651 menuBar.hideQuota.setChecked(false);
652 searchField.setVisible(Global.isWindowVisible("searchField"));
653 if (!searchField.isVisible())
654 menuBar.hideSearch.setChecked(false);
656 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
661 find = new FindDialog();
662 find.getOkButton().clicked.connect(this, "doFindText()");
664 // Setup the tray icon menu bar
665 trayShowAction = new QAction(tr("Show/Hide"), this);
666 trayExitAction = new QAction(tr("Exit"), this);
667 trayAddNoteAction = new QAction(tr("Add Note"), this);
669 trayExitAction.triggered.connect(this, "closeNeverNote()");
670 trayAddNoteAction.triggered.connect(this, "addNote()");
671 trayShowAction.triggered.connect(this, "trayToggleVisible()");
673 trayMenu = new QMenu(this);
674 trayMenu.addAction(trayAddNoteAction);
675 trayMenu.addAction(trayShowAction);
676 trayMenu.addAction(trayExitAction);
679 trayIcon = new QSystemTrayIcon(this);
680 trayIcon.setToolTip(tr("NixNote"));
681 trayIcon.setContextMenu(trayMenu);
682 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
685 currentNoteGuid = Global.getLastViewedNoteGuid();
686 historyGuids = new ArrayList<String>();
690 if (!currentNoteGuid.trim().equals("")) {
691 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
694 noteIndexUpdated(true);
696 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
697 if (menuBar.showEditorBar.isChecked())
698 showEditorButtons(browserWindow);
699 tagIndexUpdated(true);
700 savedSearchIndexUpdated();
701 notebookIndexUpdated();
703 setupSyncSignalListeners();
704 setupBrowserSignalListeners();
705 setupIndexListeners();
708 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
709 tagTree.showAllTags(true);
711 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
712 setWindowIcon(appIcon);
713 trayIcon.setIcon(appIcon);
714 if (Global.showTrayIcon())
719 scrollToGuid(currentNoteGuid);
720 if (Global.automaticLogin()) {
722 if (Global.isConnected)
725 setupFolderImports();
728 restoreWindowState(true);
730 if (Global.mimicEvernoteInterface) {
731 notebookTree.selectGuid("");
734 threadMonitorTimer = new QTimer();
735 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
736 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
738 historyGuids.add(currentNoteGuid);
741 menuBar.blockSignals(true);
742 menuBar.narrowListView.blockSignals(true);
743 menuBar.wideListView.blockSignals(true);
744 if (Global.getListView() == Global.View_List_Narrow) {
745 menuBar.narrowListView.setChecked(true);
748 menuBar.wideListView.setChecked(true);
750 menuBar.blockSignals(false);
751 menuBar.narrowListView.blockSignals(false);
752 menuBar.wideListView.blockSignals(false);
754 if (Global.getListView() == Global.View_List_Wide) {
755 browserIndexSplitter.addWidget(noteTableView);
756 browserIndexSplitter.addWidget(browserWindow);
758 mainLeftRightSplitter.addWidget(noteTableView);
759 mainLeftRightSplitter.addWidget(browserWindow);
762 messageTimer = new QTimer();
763 messageTimer.timeout.connect(this, "clearMessage()");
764 messageTimer.setInterval(1000*15);
767 int sortCol = Global.getSortColumn();
768 int sortOrder = Global.getSortOrder();
769 noteTableView.proxyModel.blocked = true;
770 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
771 noteTableView.proxyModel.blocked = false;
772 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
774 if (Global.checkVersionUpgrade())
779 public static void main(String[] args) {
780 log.setLevel(Level.FATAL);
781 QApplication.initialize(args);
782 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
783 QSplashScreen splash = new QSplashScreen(pixmap);
786 DatabaseConnection dbConn;
789 initializeGlobalSettings(args);
791 showSplash = Global.isWindowVisible("SplashScreen");
795 dbConn = setupDatabaseConnection();
797 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
798 Global.getFileManager().purgeResDirectory(true);
800 } catch (InitializationException e) {
803 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
807 NeverNote application = new NeverNote(dbConn);
809 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
810 if (Global.startMinimized())
811 application.showMinimized();
813 if (Global.wasWindowMaximized())
814 application.showMaximized();
820 splash.finish(application);
822 System.out.println("Goodbye.");
827 * Open the internal database, or create if not present
829 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
831 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
832 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
834 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
835 File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
836 File fi = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
838 Global.setDatabaseUrl("");
840 Global.setResourceDatabaseUrl("");
842 Global.setIndexDatabaseUrl("");
844 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
845 boolean goodCheck = false;
847 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
849 if (!dialog.okPressed())
851 Global.cipherPassword = dialog.getPassword();
852 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
853 Global.getDatabaseUserPassword(), Global.cipherPassword);
856 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
857 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
858 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
862 // Encrypt the database upon shutdown
863 private void encryptOnShutdown() {
864 String dbPath= Global.getFileManager().getDbDirPath("");
867 Statement st = conn.getConnection().createStatement();
868 st.execute("shutdown");
869 st = conn.getResourceConnection().createStatement();
870 st.execute("shutdown");
871 st = conn.getIndexConnection().createStatement();
872 st.execute("shutdown");
873 if (QMessageBox.question(this, tr("Are you sure"),
874 tr("Are you sure you wish to encrypt the database?"),
875 QMessageBox.StandardButton.Yes,
876 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
877 ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
878 ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
879 ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
880 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
881 Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
882 Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
884 QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
886 } catch (SQLException e) {
891 // Decrypt the database upon shutdown
892 private void decryptOnShutdown() {
893 String dbPath= Global.getFileManager().getDbDirPath("");
894 String dbName = "NeverNote";
896 Statement st = conn.getConnection().createStatement();
897 st.execute("shutdown");
898 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
899 encryptCipher = "AES";
901 encryptCipher = "XTEA";
902 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
903 "Are you sure you wish to decrypt the database?"),
904 QMessageBox.StandardButton.Yes,
905 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
907 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
908 Global.setDatabaseUrl("");
909 Global.setResourceDatabaseUrl("");
910 Global.setIndexDatabaseUrl("");
911 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
913 } catch (SQLException e) {
918 * Encrypt/Decrypt the local database
920 public void doDatabaseEncrypt() {
921 // The database is not currently encrypted
922 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
923 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
924 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
925 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
926 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
927 "Do you wish to proceed?"),
928 QMessageBox.StandardButton.Yes,
929 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
932 DBEncryptDialog dialog = new DBEncryptDialog();
934 if (dialog.okPressed()) {
935 Global.cipherPassword = dialog.getPassword();
936 encryptOnShutdown = true;
937 encryptCipher = dialog.getEncryptionMethod();
940 DBEncryptDialog dialog = new DBEncryptDialog();
941 dialog.setWindowTitle(tr("Database Decryption"));
942 dialog.hideEncryption();
944 if (dialog.okPressed()) {
945 if (!dialog.getPassword().equals(Global.cipherPassword)) {
946 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
949 decryptOnShutdown = true;
956 private static void initializeGlobalSettings(String[] args) throws InitializationException {
957 StartupConfig startupConfig = new StartupConfig();
959 for (String arg : args) {
960 String lower = arg.toLowerCase();
961 if (lower.startsWith("--name="))
962 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
963 if (lower.startsWith("--home="))
964 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
965 if (lower.startsWith("--disable-viewing"))
966 startupConfig.setDisableViewing(true);
968 Global.setup(startupConfig);
973 public void closeEvent(QCloseEvent event) {
974 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
979 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
982 if (currentNote!= null & browserWindow!=null) {
983 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
984 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
987 setMessage(tr("Beginning shutdown."));
989 // Close down external windows
990 Collection<ExternalBrowse> windows = externalWindows.values();
991 Iterator<ExternalBrowse> iterator = windows.iterator();
992 while (iterator.hasNext()) {
993 ExternalBrowse browser = iterator.next();
994 browser.windowClosing.disconnect();
999 externalFileEditedSaver();
1000 if (Global.isConnected && Global.synchronizeOnClose()) {
1001 setMessage(tr("Performing synchronization before closing."));
1002 syncRunner.syncNeeded = true;
1003 syncRunner.addWork("SYNC");
1005 syncRunner.keepRunning = false;
1007 syncRunner.addWork("STOP");
1008 setMessage("Closing Program.");
1009 threadMonitorTimer.stop();
1011 thumbnailRunner.addWork("STOP");
1012 indexRunner.addWork("STOP");
1017 if (tempFiles != null)
1020 browserWindow.noteSignal.tagsChanged.disconnect();
1021 browserWindow.noteSignal.titleChanged.disconnect();
1022 browserWindow.noteSignal.noteChanged.disconnect();
1023 browserWindow.noteSignal.notebookChanged.disconnect();
1024 browserWindow.noteSignal.createdDateChanged.disconnect();
1025 browserWindow.noteSignal.alteredDateChanged.disconnect();
1026 syncRunner.searchSignal.listChanged.disconnect();
1027 syncRunner.tagSignal.listChanged.disconnect();
1028 syncRunner.notebookSignal.listChanged.disconnect();
1029 syncRunner.noteIndexSignal.listChanged.disconnect();
1032 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1033 saveNoteColumnPositions();
1034 saveNoteIndexWidth();
1036 int width = notebookTree.columnWidth(0);
1037 Global.setColumnWidth("notebookTreeName", width);
1038 width = tagTree.columnWidth(0);
1039 Global.setColumnWidth("tagTreeName", width);
1041 Global.saveWindowMaximized(isMaximized());
1042 Global.saveCurrentNoteGuid(currentNoteGuid);
1044 int sortCol = noteTableView.proxyModel.sortColumn();
1045 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1046 Global.setSortColumn(sortCol);
1047 Global.setSortOrder(sortOrder);
1051 Global.keepRunning = false;
1053 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1054 if (indexRunner.thread().isAlive())
1055 indexRunner.thread().join(50);
1056 if (!indexRunner.thread().isAlive())
1057 logger.log(logger.MEDIUM, "Index thread has stopped");
1059 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1060 indexRunner.thread().interrupt();
1062 } catch (InterruptedException e1) {
1063 e1.printStackTrace();
1066 if (!syncRunner.thread().isAlive()) {
1067 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1068 if (syncRunner.thread().isAlive()) {
1069 System.out.println(tr("Synchronizing. Please be patient."));
1070 for(;syncRunner.thread().isAlive();) {
1073 } catch (InterruptedException e) {
1074 e.printStackTrace();
1078 logger.log(logger.MEDIUM, "Sync thread has stopped");
1081 if (encryptOnShutdown) {
1082 encryptOnShutdown();
1084 if (decryptOnShutdown) {
1085 decryptOnShutdown();
1088 Global.getFileManager().purgeResDirectory(false);
1089 } catch (InitializationException e) {
1090 System.out.println(tr("Empty res directory purge failed"));
1091 e.printStackTrace();
1093 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1096 @SuppressWarnings("unused")
1097 private void closeNeverNote() {
1101 public void setMessage(String s) {
1102 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1105 logger.log(logger.HIGH, "Message: " +s);
1106 statusBar.showMessage(s);
1110 messageTimer.stop();
1111 messageTimer.setSingleShot(true);
1112 messageTimer.start();
1115 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1118 private void clearMessage() {
1119 statusBar.clearMessage();
1123 private void waitCursor(boolean wait) {
1125 if (QApplication.overrideCursor() == null)
1126 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1129 while (QApplication.overrideCursor() != null)
1130 QApplication.restoreOverrideCursor();
1132 listManager.refreshCounters();
1135 private void setupIndexListeners() {
1136 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1137 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1138 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1139 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1141 private void setupSyncSignalListeners() {
1142 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1143 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1144 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1145 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1146 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1148 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1149 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1150 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1152 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1153 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1154 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1155 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1156 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1158 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1161 private void setupBrowserSignalListeners() {
1162 setupBrowserWindowListeners(browserWindow, true);
1165 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1166 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1167 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1168 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1169 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1170 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1171 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1172 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1173 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1174 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1175 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1176 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1177 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1178 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1179 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1180 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1181 browser.unblockApplication.connect(this, "unblockApplication()");
1182 if (master) browser.focusLost.connect(this, "saveNote()");
1183 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1184 browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1187 //**************************************************
1189 //**************************************************
1190 private void setupShortcut(QShortcut action, String text) {
1191 if (!Global.shortcutKeys.containsAction(text))
1193 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1196 //***************************************************************
1197 //***************************************************************
1198 //* Settings and look & feel
1199 //***************************************************************
1200 //***************************************************************
1201 @SuppressWarnings("unused")
1202 private void settings() {
1203 logger.log(logger.HIGH, "Entering NeverNote.settings");
1204 saveNoteColumnPositions();
1205 saveNoteIndexWidth();
1207 ConfigDialog settings = new ConfigDialog(this);
1208 String dateFormat = Global.getDateFormat();
1209 String timeFormat = Global.getTimeFormat();
1211 indexTime = 1000*Global.getIndexThreadSleepInterval();
1212 indexTimer.start(indexTime); // reset indexing timer
1215 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1216 indexRunner.indexNoteBody = Global.indexNoteBody();
1217 indexRunner.indexNoteTitle = Global.indexNoteTitle();
1218 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1219 indexRunner.indexImageRecognition = Global.indexImageRecognition();
1220 if (Global.showTrayIcon())
1225 if (menuBar.showEditorBar.isChecked())
1226 showEditorButtons(browserWindow);
1228 // Reset the save timer
1229 if (Global.getAutoSaveInterval() > 0)
1230 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1235 // Set special reloads
1236 if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1237 conn.executeSql("Delete from LinkedNotebook");
1238 conn.executeSql("delete from SharedNotebook");
1239 conn.executeSql("Delete from Notebook where linked=true");
1240 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1241 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1246 readOnlyCache.clear();
1247 inkNoteCache.clear();
1248 noteIndexUpdated(true);
1250 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1252 // Restore things to the way they were
1253 private void restoreWindowState(boolean mainWindow) {
1254 // We need to name things or this doesn't work.
1255 setObjectName("NeverNote");
1256 restoreState(Global.restoreState(objectName()));
1257 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1258 browserIndexSplitter.setObjectName("browserIndexSplitter");
1259 leftSplitter1.setObjectName("leftSplitter1");
1261 // Restore the actual positions.
1263 restoreGeometry(Global.restoreGeometry(objectName()));
1264 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1265 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1266 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1269 // Save window positions for the next start
1270 private void saveWindowState() {
1271 Global.saveGeometry(objectName(), saveGeometry());
1272 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1273 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1274 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1275 Global.saveState(objectName(), saveState());
1277 // Load the style sheet
1278 private void loadStyleSheet() {
1279 String styleSheetName = "default.qss";
1280 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1281 styleSheetName = "default-cleanlooks.qss";
1282 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1283 QFile file = new QFile(fileName);
1285 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1286 if (!file.exists()) {
1287 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1288 file = new QFile(fileName);
1290 file.open(OpenModeFlag.ReadOnly);
1291 String styleSheet = file.readAll().toString();
1293 setStyleSheet(styleSheet);
1295 // Save column positions for the next time
1296 private void saveNoteColumnPositions() {
1297 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1298 Global.setColumnPosition("noteTableCreationPosition", position);
1299 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1300 Global.setColumnPosition("noteTableTagPosition", position);
1301 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1302 Global.setColumnPosition("noteTableNotebookPosition", position);
1303 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1304 Global.setColumnPosition("noteTableChangedPosition", position);
1305 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1306 Global.setColumnPosition("noteTableAuthorPosition", position);
1307 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1308 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1309 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1310 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1311 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1312 Global.setColumnPosition("noteTableTitlePosition", position);
1313 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1314 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1315 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1316 Global.setColumnPosition("noteTableGuidPosition", position);
1317 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1318 Global.setColumnPosition("noteTableThumbnailPosition", position);
1319 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1320 Global.setColumnPosition("noteTablePinnedPosition", position);
1323 // Save column widths for the next time
1324 private void saveNoteIndexWidth() {
1326 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1327 Global.setColumnWidth("noteTableCreationPosition", width);
1328 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1329 Global.setColumnWidth("noteTableChangedPosition", width);
1330 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1331 Global.setColumnWidth("noteTableGuidPosition", width);
1332 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1333 Global.setColumnWidth("noteTableNotebookPosition", width);
1334 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1335 Global.setColumnWidth("noteTableTagPosition", width);
1336 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1337 Global.setColumnWidth("noteTableTitlePosition", width);
1338 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1339 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1340 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1341 Global.setColumnWidth("noteTableAuthorPosition", width);
1342 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1343 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1344 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1345 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1346 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1347 Global.setColumnWidth("noteTableThumbnailPosition", width);
1348 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1349 Global.setColumnWidth("noteTableGuidPosition", width);
1352 @SuppressWarnings("unused")
1353 private void toggleSearchWindow() {
1354 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1355 searchLayout.toggleSearchField();
1356 menuBar.hideSearch.setChecked(searchField.isVisible());
1357 Global.saveWindowVisible("searchField", searchField.isVisible());
1358 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1360 @SuppressWarnings("unused")
1361 private void toggleQuotaWindow() {
1362 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1363 searchLayout.toggleQuotaBar();
1364 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1365 Global.saveWindowVisible("quota", quotaBar.isVisible());
1366 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1368 @SuppressWarnings("unused")
1369 private void toggleZoomWindow() {
1370 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1371 searchLayout.toggleZoom();
1372 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1373 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1374 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1379 //***************************************************************
1380 //***************************************************************
1381 //** These functions deal with Notebook menu items
1382 //***************************************************************
1383 //***************************************************************
1384 // Setup the tree containing the user's notebooks.
1385 private void initializeNotebookTree() {
1386 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1387 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1388 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1389 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1390 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1392 // Listener when a notebook is selected
1393 private void notebookTreeSelection() {
1394 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1395 noteTableView.proxyModel.blocked = true;
1398 clearAttributeFilter();
1399 clearSavedSearchFilter();
1400 if (Global.mimicEvernoteInterface) {
1402 searchField.clear();
1404 menuBar.noteRestoreAction.setVisible(false);
1405 menuBar.notebookEditAction.setEnabled(true);
1406 menuBar.notebookDeleteAction.setEnabled(true);
1407 menuBar.notebookPublishAction.setEnabled(true);
1408 menuBar.notebookShareAction.setEnabled(true);
1409 menuBar.notebookIconAction.setEnabled(true);
1410 menuBar.notebookStackAction.setEnabled(true);
1411 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1412 selectedNotebookGUIDs.clear();
1414 String stackName = "";
1415 if (selections.size() > 0) {
1416 guid = (selections.get(0).text(2));
1417 stackName = selections.get(0).text(0);
1419 if (!Global.mimicEvernoteInterface) {
1420 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1421 if (selections.size()==0) {
1422 selectedNotebookGUIDs.clear();
1423 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1424 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1426 menuBar.notebookEditAction.setEnabled(false);
1427 menuBar.notebookDeleteAction.setEnabled(false);
1428 menuBar.notebookStackAction.setEnabled(false);
1429 menuBar.notebookIconAction.setEnabled(false);
1432 if (!guid.equals("") && !guid.equals("STACK")) {
1433 selectedNotebookGUIDs.add(guid);
1434 menuBar.notebookIconAction.setEnabled(true);
1436 menuBar.notebookIconAction.setEnabled(true);
1437 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1438 Notebook book = listManager.getNotebookIndex().get(j);
1439 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1440 selectedNotebookGUIDs.add(book.getGuid());
1443 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1444 listManager.loadNotesIndex();
1445 noteIndexUpdated(false);
1446 refreshEvernoteNote(true);
1447 listManager.refreshCounters = true;
1448 listManager.refreshCounters();
1449 if (selectedNotebookGUIDs.size() == 1) {
1450 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1451 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1453 noteTableView.proxyModel.blocked = true;
1455 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1457 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1460 noteTableView.proxyModel.blocked = false;
1461 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1464 private void clearNotebookFilter() {
1465 notebookTree.blockSignals(true);
1466 notebookTree.clearSelection();
1467 menuBar.noteRestoreAction.setVisible(false);
1468 menuBar.notebookEditAction.setEnabled(false);
1469 menuBar.notebookDeleteAction.setEnabled(false);
1470 selectedNotebookGUIDs.clear();
1471 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1472 notebookTree.blockSignals(false);
1474 // Triggered when the notebook DB has been updated
1475 private void notebookIndexUpdated() {
1476 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1478 // Get the possible icons
1479 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1480 notebookTree.setIcons(icons);
1482 if (selectedNotebookGUIDs == null)
1483 selectedNotebookGUIDs = new ArrayList<String>();
1484 List<Notebook> books = conn.getNotebookTable().getAll();
1485 for (int i=books.size()-1; i>=0; i--) {
1486 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1487 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1489 j=listManager.getArchiveNotebookIndex().size();
1495 listManager.countNotebookResults(listManager.getNoteIndex());
1496 notebookTree.blockSignals(true);
1497 notebookTree.load(books, listManager.getLocalNotebooks());
1498 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1499 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1501 selectedNotebookGUIDs.remove(i);
1503 listManager.refreshCounters = true;
1504 listManager.refreshCounters();
1505 notebookTree.blockSignals(false);
1507 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1509 // Show/Hide note information
1510 @SuppressWarnings("unused")
1511 private void toggleNotebookWindow() {
1512 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1513 searchLayout.toggleNotebook();
1514 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1515 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1516 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1518 // Add a new notebook
1519 @SuppressWarnings("unused")
1520 private void addNotebook() {
1521 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1522 NotebookEdit edit = new NotebookEdit();
1523 edit.setNotebooks(listManager.getNotebookIndex());
1526 if (!edit.okPressed())
1529 Calendar currentTime = new GregorianCalendar();
1530 Long l = new Long(currentTime.getTimeInMillis());
1531 String randint = new String(Long.toString(l));
1533 Notebook newBook = new Notebook();
1534 newBook.setUpdateSequenceNum(0);
1535 newBook.setGuid(randint);
1536 newBook.setName(edit.getNotebook());
1537 newBook.setServiceCreated(new Date().getTime());
1538 newBook.setServiceUpdated(new Date().getTime());
1539 newBook.setDefaultNotebook(false);
1540 newBook.setPublished(false);
1542 listManager.getNotebookIndex().add(newBook);
1544 listManager.getLocalNotebooks().add(newBook.getGuid());
1545 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1546 notebookIndexUpdated();
1547 listManager.countNotebookResults(listManager.getNoteIndex());
1548 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1549 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1551 // Edit an existing notebook
1552 @SuppressWarnings("unused")
1553 private void stackNotebook() {
1554 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1555 StackNotebook edit = new StackNotebook();
1557 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1558 QTreeWidgetItem currentSelection;
1559 for (int i=0; i<selections.size(); i++) {
1560 currentSelection = selections.get(0);
1561 String guid = currentSelection.text(2);
1562 if (guid.equalsIgnoreCase("")) {
1563 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1566 if (guid.equalsIgnoreCase("STACK")) {
1567 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1572 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1577 if (!edit.okPressed())
1580 String stack = edit.getStackName();
1582 for (int i=0; i<selections.size(); i++) {
1583 currentSelection = selections.get(i);
1584 String guid = currentSelection.text(2);
1585 listManager.updateNotebookStack(guid, stack);
1587 notebookIndexUpdated();
1588 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1590 // Edit an existing notebook
1591 @SuppressWarnings("unused")
1592 private void editNotebook() {
1593 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1594 NotebookEdit edit = new NotebookEdit();
1596 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1597 QTreeWidgetItem currentSelection;
1598 currentSelection = selections.get(0);
1599 edit.setNotebook(currentSelection.text(0));
1601 String guid = currentSelection.text(2);
1602 if (!guid.equalsIgnoreCase("STACK")) {
1603 edit.setTitle(tr("Edit Notebook"));
1604 edit.setNotebooks(listManager.getNotebookIndex());
1605 edit.setLocalCheckboxEnabled(false);
1606 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1607 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1608 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1609 i=listManager.getNotebookIndex().size();
1613 edit.setTitle(tr("Edit Stack"));
1614 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1615 edit.hideLocalCheckbox();
1616 edit.hideDefaultCheckbox();
1621 if (!edit.okPressed())
1625 if (guid.equalsIgnoreCase("STACK")) {
1626 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1627 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1628 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1629 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1630 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1632 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1633 currentSelection.setText(0, edit.getNotebook());
1637 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1638 currentSelection.setText(0, edit.getNotebook());
1640 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1641 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1642 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1643 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1644 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1645 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1646 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1647 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1649 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1650 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1651 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1652 linkedNotebook.setShareName(edit.getNotebook());
1653 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1655 i=listManager.getNotebookIndex().size();
1659 // Build a list of non-closed notebooks
1660 List<Notebook> nbooks = new ArrayList<Notebook>();
1661 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1662 boolean found=false;
1663 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1664 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1668 nbooks.add(listManager.getNotebookIndex().get(i));
1672 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1673 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1674 browserWindow.setNotebookList(filteredBooks);
1675 Iterator<String> set = externalWindows.keySet().iterator();
1676 while(set.hasNext())
1677 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1678 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1680 // Publish a notebook
1681 @SuppressWarnings("unused")
1682 private void publishNotebook() {
1683 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1684 QTreeWidgetItem currentSelection;
1685 currentSelection = selections.get(0);
1686 String guid = currentSelection.text(2);
1688 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1693 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1694 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1695 n = listManager.getNotebookIndex().get(i);
1697 i = listManager.getNotebookIndex().size();
1703 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1706 if (!publish.okClicked())
1709 Publishing p = publish.getPublishing();
1710 boolean isPublished = !publish.isStopPressed();
1711 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1712 n.setPublished(isPublished);
1714 listManager.getNotebookIndex().set(position, n);
1715 notebookIndexUpdated();
1717 // Publish a notebook
1718 @SuppressWarnings("unused")
1719 private void shareNotebook() {
1720 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1721 QTreeWidgetItem currentSelection;
1722 currentSelection = selections.get(0);
1723 String guid = currentSelection.text(2);
1725 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1729 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1730 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1731 n = listManager.getNotebookIndex().get(i);
1732 i = listManager.getNotebookIndex().size();
1736 String authToken = null;
1737 if (syncRunner.isConnected)
1738 authToken = syncRunner.authToken;
1739 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1744 // Delete an existing notebook
1745 @SuppressWarnings("unused")
1746 private void deleteNotebook() {
1747 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1748 boolean stacksFound = false;
1749 boolean notebooksFound = false;
1750 boolean assigned = false;
1751 // Check if any notes have this notebook
1752 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1753 for (int i=0; i<selections.size(); i++) {
1754 QTreeWidgetItem currentSelection;
1755 currentSelection = selections.get(i);
1756 String guid = currentSelection.text(2);
1757 if (!guid.equalsIgnoreCase("STACK")) {
1758 notebooksFound = true;
1759 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1760 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1761 if (noteGuid.equals(guid)) {
1763 j=listManager.getNoteIndex().size();
1764 i=selections.size();
1772 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1773 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1777 if (conn.getNotebookTable().getAll().size() == 1) {
1778 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1782 // If all notebooks are clear, verify the delete
1783 String msg1 = new String(tr("Delete selected notebooks?"));
1784 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1785 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1786 " not deleted unless selected?"));
1788 if (stacksFound && notebooksFound)
1790 if (!stacksFound && notebooksFound)
1792 if (stacksFound && !notebooksFound)
1794 if (QMessageBox.question(this, tr("Confirmation"), msg,
1795 QMessageBox.StandardButton.Yes,
1796 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1800 // If confirmed, delete the notebook
1801 for (int i=selections.size()-1; i>=0; i--) {
1802 QTreeWidgetItem currentSelection;
1803 currentSelection = selections.get(i);
1804 String guid = currentSelection.text(2);
1805 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1806 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1807 listManager.renameStack(currentSelection.text(0), "");
1809 conn.getNotebookTable().expungeNotebook(guid, true);
1810 listManager.deleteNotebook(guid);
1814 notebookIndexUpdated();
1815 // notebookTreeSelection();
1816 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1817 // listManager.countNotebookResults(listManager.getNoteIndex());
1818 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1820 // A note's notebook has been updated
1821 @SuppressWarnings("unused")
1822 private void updateNoteNotebook(String guid, String notebookGuid) {
1824 // Update the list manager
1825 listManager.updateNoteNotebook(guid, notebookGuid);
1826 listManager.countNotebookResults(listManager.getNoteIndex());
1827 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1829 // Find the name of the notebook
1830 String notebookName = null;
1831 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1832 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1833 notebookName = listManager.getNotebookIndex().get(i).getName();
1838 // If we found the name, update the browser window
1839 if (notebookName != null) {
1840 updateListNoteNotebook(guid, notebookName);
1841 if (guid.equals(currentNoteGuid)) {
1842 int pos = browserWindow.notebookBox.findText(notebookName);
1844 browserWindow.notebookBox.setCurrentIndex(pos);
1848 // If we're dealing with the current note, then we need to be sure and update the notebook there
1849 if (guid.equals(currentNoteGuid)) {
1850 if (currentNote != null) {
1851 currentNote.setNotebookGuid(notebookGuid);
1855 // Open/close notebooks
1856 @SuppressWarnings("unused")
1857 private void closeNotebooks() {
1858 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1860 if (!na.okClicked())
1864 listManager.getArchiveNotebookIndex().clear();
1866 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1867 String text = na.getClosedBookList().takeItem(i).text();
1868 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1869 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1870 Notebook n = listManager.getNotebookIndex().get(j);
1871 conn.getNotebookTable().setArchived(n.getGuid(),true);
1872 listManager.getArchiveNotebookIndex().add(n);
1873 j=listManager.getNotebookIndex().size();
1878 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1879 String text = na.getOpenBookList().takeItem(i).text();
1880 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1881 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1882 Notebook n = listManager.getNotebookIndex().get(j);
1883 conn.getNotebookTable().setArchived(n.getGuid(),false);
1884 j=listManager.getNotebookIndex().size();
1888 notebookTreeSelection();
1889 listManager.loadNotesIndex();
1890 notebookIndexUpdated();
1891 noteIndexUpdated(false);
1892 reloadTagTree(true);
1893 // noteIndexUpdated(false);
1895 // Build a list of non-closed notebooks
1896 List<Notebook> nbooks = new ArrayList<Notebook>();
1897 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1898 boolean found=false;
1899 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1900 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1904 nbooks.add(listManager.getNotebookIndex().get(i));
1907 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1908 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1909 browserWindow.setNotebookList(filteredBooks);
1911 // Update any external windows
1912 Iterator<String> set = externalWindows.keySet().iterator();
1913 while(set.hasNext())
1914 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1918 // Change the notebook's icon
1919 @SuppressWarnings("unused")
1920 private void setNotebookIcon() {
1921 boolean stackSelected = false;
1922 boolean allNotebookSelected = false;
1924 QTreeWidgetItem currentSelection;
1925 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1926 if (selections.size() == 0)
1929 currentSelection = selections.get(0);
1930 String guid = currentSelection.text(2);
1931 if (guid.equalsIgnoreCase(""))
1932 allNotebookSelected = true;
1933 if (guid.equalsIgnoreCase("STACK"))
1934 stackSelected = true;
1936 QIcon currentIcon = currentSelection.icon(0);
1940 if (!stackSelected && !allNotebookSelected) {
1941 icon = conn.getNotebookTable().getIcon(guid);
1943 dialog = new SetIcon(currentIcon, saveLastPath);
1944 dialog.setUseDefaultIcon(true);
1946 dialog = new SetIcon(icon, saveLastPath);
1947 dialog.setUseDefaultIcon(false);
1950 if (stackSelected) {
1951 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1953 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1956 dialog = new SetIcon(currentIcon, saveLastPath);
1957 dialog.setUseDefaultIcon(true);
1959 dialog = new SetIcon(icon, saveLastPath);
1960 dialog.setUseDefaultIcon(false);
1964 if (dialog.okPressed()) {
1965 saveLastPath = dialog.getPath();
1967 QIcon newIcon = dialog.getIcon();
1968 if (stackSelected) {
1969 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1970 if (newIcon == null) {
1971 newIcon = new QIcon(iconPath+"books2.png");
1973 currentSelection.setIcon(0,newIcon);
1976 if (allNotebookSelected) {
1977 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1978 if (newIcon == null) {
1979 newIcon = new QIcon(iconPath+"notebook-green.png");
1981 currentSelection.setIcon(0,newIcon);
1984 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1985 if (newIcon == null) {
1986 boolean isPublished = false;;
1987 boolean found = false;
1988 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1989 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1990 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1994 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1996 currentSelection.setIcon(0, newIcon);
2002 //***************************************************************
2003 //***************************************************************
2004 //** These functions deal with Tag menu items
2005 //***************************************************************
2006 //***************************************************************
2007 // Add a new notebook
2008 @SuppressWarnings("unused")
2009 private void addTag() {
2010 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2011 TagEdit edit = new TagEdit();
2012 edit.setTagList(listManager.getTagIndex());
2014 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2015 QTreeWidgetItem currentSelection = null;
2016 if (selections.size() > 0) {
2017 currentSelection = selections.get(0);
2018 edit.setParentTag(currentSelection.text(0));
2023 if (!edit.okPressed())
2026 Calendar currentTime = new GregorianCalendar();
2027 Long l = new Long(currentTime.getTimeInMillis());
2028 String randint = new String(Long.toString(l));
2030 Tag newTag = new Tag();
2031 newTag.setUpdateSequenceNum(0);
2032 newTag.setGuid(randint);
2033 newTag.setName(edit.getTag());
2034 if (edit.getParentTag().isChecked()) {
2035 newTag.setParentGuid(currentSelection.text(2));
2036 newTag.setParentGuidIsSet(true);
2037 currentSelection.setExpanded(true);
2039 conn.getTagTable().addTag(newTag, true);
2040 listManager.getTagIndex().add(newTag);
2041 reloadTagTree(true);
2043 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2045 @SuppressWarnings("unused")
2046 private void reloadTagTree() {
2047 reloadTagTree(false);
2049 private void reloadTagTree(boolean reload) {
2050 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2051 tagIndexUpdated(reload);
2052 boolean filter = false;
2054 listManager.countTagResults(listManager.getNoteIndex());
2055 if (notebookTree.selectedItems().size() > 0
2056 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2058 if (tagTree.selectedItems().size() > 0)
2060 tagTree.showAllTags(!filter);
2061 tagIndexUpdated(false);
2062 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2064 // Edit an existing tag
2065 @SuppressWarnings("unused")
2066 private void editTag() {
2067 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2068 TagEdit edit = new TagEdit();
2069 edit.setTitle("Edit Tag");
2070 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2071 QTreeWidgetItem currentSelection;
2072 currentSelection = selections.get(0);
2073 edit.setTag(currentSelection.text(0));
2074 edit.setTagList(listManager.getTagIndex());
2077 if (!edit.okPressed())
2080 String guid = currentSelection.text(2);
2081 currentSelection.setText(0,edit.getTag());
2083 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2084 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2085 listManager.getTagIndex().get(i).setName(edit.getTag());
2086 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2087 updateListTagName(guid);
2088 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2089 browserWindow.setTag(getTagNamesForNote(currentNote));
2090 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2094 browserWindow.setTag(getTagNamesForNote(currentNote));
2095 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2097 // Delete an existing tag
2098 @SuppressWarnings("unused")
2099 private void deleteTag() {
2100 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2102 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2103 QMessageBox.StandardButton.Yes,
2104 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2108 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2109 for (int i=selections.size()-1; i>=0; i--) {
2110 QTreeWidgetItem currentSelection;
2111 currentSelection = selections.get(i);
2112 removeTagItem(currentSelection.text(2));
2114 tagIndexUpdated(true);
2116 listManager.countTagResults(listManager.getNoteIndex());
2117 // tagTree.updateCounts(listManager.getTagCounter());
2118 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2120 // Remove a tag tree item. Go recursively down & remove the children too
2121 private void removeTagItem(String guid) {
2122 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2123 String parent = listManager.getTagIndex().get(j).getParentGuid();
2124 if (parent != null && parent.equals(guid)) {
2125 //Remove this tag's children
2126 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2129 //Now, remove this tag
2130 removeListTagName(guid);
2131 conn.getTagTable().expungeTag(guid, true);
2132 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2133 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2134 listManager.getTagIndex().remove(a);
2139 // Setup the tree containing the user's tags
2140 private void initializeTagTree() {
2141 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2142 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2143 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2144 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2145 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2146 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2148 // Listener when a tag is selected
2149 private void tagTreeSelection() {
2150 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2153 clearAttributeFilter();
2154 clearSavedSearchFilter();
2156 menuBar.noteRestoreAction.setVisible(false);
2158 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2159 QTreeWidgetItem currentSelection;
2160 selectedTagGUIDs.clear();
2161 for (int i=0; i<selections.size(); i++) {
2162 currentSelection = selections.get(i);
2163 selectedTagGUIDs.add(currentSelection.text(2));
2165 if (selections.size() > 0) {
2166 menuBar.tagEditAction.setEnabled(true);
2167 menuBar.tagDeleteAction.setEnabled(true);
2168 menuBar.tagIconAction.setEnabled(true);
2171 menuBar.tagEditAction.setEnabled(false);
2172 menuBar.tagDeleteAction.setEnabled(false);
2173 menuBar.tagIconAction.setEnabled(true);
2175 if (selections.size() > 1)
2176 menuBar.tagMergeAction.setEnabled(true);
2178 menuBar.tagMergeAction.setEnabled(false);
2179 listManager.setSelectedTags(selectedTagGUIDs);
2180 listManager.loadNotesIndex();
2181 noteIndexUpdated(false);
2182 refreshEvernoteNote(true);
2183 listManager.refreshCounters = true;
2184 listManager.refreshCounters();
2185 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2187 // trigger the tag index to be refreshed
2188 @SuppressWarnings("unused")
2189 private void tagIndexUpdated() {
2190 tagIndexUpdated(true);
2192 private void tagIndexUpdated(boolean reload) {
2193 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2194 if (selectedTagGUIDs == null)
2195 selectedTagGUIDs = new ArrayList<String>();
2197 listManager.reloadTagIndex();
2199 tagTree.blockSignals(true);
2201 tagTree.setIcons(conn.getTagTable().getAllIcons());
2202 tagTree.load(listManager.getTagIndex());
2205 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2206 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2208 selectedTagGUIDs.remove(i);
2210 tagTree.blockSignals(false);
2212 browserWindow.setTag(getTagNamesForNote(currentNote));
2213 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2215 // Show/Hide note information
2216 @SuppressWarnings("unused")
2217 private void toggleTagWindow() {
2218 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2219 if (tagTree.isVisible())
2223 menuBar.hideTags.setChecked(tagTree.isVisible());
2224 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2225 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2227 // A note's tags have been updated
2228 @SuppressWarnings("unused")
2229 private void updateNoteTags(String guid, List<String> tags) {
2230 // Save any new tags. We'll need them later.
2231 List<String> newTags = new ArrayList<String>();
2232 for (int i=0; i<tags.size(); i++) {
2233 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2234 newTags.add(tags.get(i));
2237 listManager.saveNoteTags(guid, tags);
2238 listManager.countTagResults(listManager.getNoteIndex());
2239 StringBuffer names = new StringBuffer("");
2240 for (int i=0; i<tags.size(); i++) {
2241 names = names.append(tags.get(i));
2242 if (i<tags.size()-1) {
2243 names.append(Global.tagDelimeter + " ");
2246 browserWindow.setTag(names.toString());
2249 // Now, we need to add any new tags to the tag tree
2250 for (int i=0; i<newTags.size(); i++)
2251 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2253 // Get a string containing all tag names for a note
2254 private String getTagNamesForNote(Note n) {
2255 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2256 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2258 StringBuffer buffer = new StringBuffer(100);
2259 Vector<String> v = new Vector<String>();
2260 List<String> guids = n.getTagGuids();
2265 for (int i=0; i<guids.size(); i++) {
2266 v.add(listManager.getTagNameByGuid(guids.get(i)));
2268 Comparator<String> comparator = Collections.reverseOrder();
2269 Collections.sort(v,comparator);
2270 Collections.reverse(v);
2272 for (int i = 0; i<v.size(); i++) {
2274 buffer.append(", ");
2275 buffer.append(v.get(i));
2278 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2279 return buffer.toString();
2281 // Tags were added via dropping notes from the note list
2282 @SuppressWarnings("unused")
2283 private void tagsAdded(String noteGuid, String tagGuid) {
2284 String tagName = null;
2285 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2286 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2287 tagName = listManager.getTagIndex().get(i).getName();
2288 i=listManager.getTagIndex().size();
2291 if (tagName == null)
2294 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2295 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2296 List<String> tagNames = new ArrayList<String>();
2297 tagNames.add(new String(tagName));
2298 Note n = listManager.getMasterNoteIndex().get(i);
2299 for (int j=0; j<n.getTagNames().size(); j++) {
2300 tagNames.add(new String(n.getTagNames().get(j)));
2302 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2303 if (n.getGuid().equals(currentNoteGuid)) {
2304 Collections.sort(tagNames);
2305 String display = "";
2306 for (int j=0; j<tagNames.size(); j++) {
2307 display = display+tagNames.get(j);
2308 if (j+2<tagNames.size())
2309 display = display+Global.tagDelimeter+" ";
2311 browserWindow.setTag(display);
2313 i=listManager.getMasterNoteIndex().size();
2318 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2320 private void clearTagFilter() {
2321 tagTree.blockSignals(true);
2322 tagTree.clearSelection();
2323 menuBar.noteRestoreAction.setVisible(false);
2324 menuBar.tagEditAction.setEnabled(false);
2325 menuBar.tagMergeAction.setEnabled(false);
2326 menuBar.tagDeleteAction.setEnabled(false);
2327 menuBar.tagIconAction.setEnabled(false);
2328 selectedTagGUIDs.clear();
2329 listManager.setSelectedTags(selectedTagGUIDs);
2330 tagTree.blockSignals(false);
2332 // Change the icon for a tag
2333 @SuppressWarnings("unused")
2334 private void setTagIcon() {
2335 QTreeWidgetItem currentSelection;
2336 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2337 if (selections.size() == 0)
2340 currentSelection = selections.get(0);
2341 String guid = currentSelection.text(2);
2343 QIcon currentIcon = currentSelection.icon(0);
2344 QIcon icon = conn.getTagTable().getIcon(guid);
2347 dialog = new SetIcon(currentIcon, saveLastPath);
2348 dialog.setUseDefaultIcon(true);
2350 dialog = new SetIcon(icon, saveLastPath);
2351 dialog.setUseDefaultIcon(false);
2354 if (dialog.okPressed()) {
2355 saveLastPath = dialog.getPath();
2356 QIcon newIcon = dialog.getIcon();
2357 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2358 if (newIcon == null)
2359 newIcon = new QIcon(iconPath+"tag.png");
2360 currentSelection.setIcon(0, newIcon);
2365 @SuppressWarnings("unused")
2366 private void mergeTags() {
2367 List<Tag> tags = new ArrayList<Tag>();
2368 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2369 for (int i=0; i<selections.size(); i++) {
2370 Tag record = new Tag();
2371 record.setGuid(selections.get(i).text(2));
2372 record.setName(selections.get(i).text(0));
2376 TagMerge mergeDialog = new TagMerge(tags);
2378 if (!mergeDialog.okClicked())
2380 String newGuid = mergeDialog.getNewTagGuid();
2382 for (int i=0; i<tags.size(); i++) {
2383 if (!tags.get(i).getGuid().equals(newGuid)) {
2384 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2385 for (int j=0; j<noteGuids.size(); j++) {
2386 String noteGuid = noteGuids.get(j);
2387 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2388 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2389 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2393 listManager.reloadIndexes();
2396 //***************************************************************
2397 //***************************************************************
2398 //** These functions deal with Saved Search menu items
2399 //***************************************************************
2400 //***************************************************************
2401 // Add a new notebook
2402 @SuppressWarnings("unused")
2403 private void addSavedSearch() {
2404 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2405 SavedSearchEdit edit = new SavedSearchEdit();
2406 edit.setSearchList(listManager.getSavedSearchIndex());
2409 if (!edit.okPressed())
2412 Calendar currentTime = new GregorianCalendar();
2413 Long l = new Long(currentTime.getTimeInMillis());
2414 String randint = new String(Long.toString(l));
2416 SavedSearch search = new SavedSearch();
2417 search.setUpdateSequenceNum(0);
2418 search.setGuid(randint);
2419 search.setName(edit.getName());
2420 search.setQuery(edit.getQuery());
2421 search.setFormat(QueryFormat.USER);
2422 listManager.getSavedSearchIndex().add(search);
2423 conn.getSavedSearchTable().addSavedSearch(search, true);
2424 savedSearchIndexUpdated();
2425 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2427 // Edit an existing tag
2428 @SuppressWarnings("unused")
2429 private void editSavedSearch() {
2430 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2431 SavedSearchEdit edit = new SavedSearchEdit();
2432 edit.setTitle(tr("Edit Search"));
2433 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2434 QTreeWidgetItem currentSelection;
2435 currentSelection = selections.get(0);
2436 String guid = currentSelection.text(1);
2437 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2438 edit.setName(currentSelection.text(0));
2439 edit.setQuery(s.getQuery());
2440 edit.setSearchList(listManager.getSavedSearchIndex());
2443 if (!edit.okPressed())
2446 List<SavedSearch> list = listManager.getSavedSearchIndex();
2447 SavedSearch search = null;
2448 boolean found = false;
2449 for (int i=0; i<list.size(); i++) {
2450 search = list.get(i);
2451 if (search.getGuid().equals(guid)) {
2458 search.setName(edit.getName());
2459 search.setQuery(edit.getQuery());
2460 conn.getSavedSearchTable().updateSavedSearch(search, true);
2461 savedSearchIndexUpdated();
2462 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2464 // Delete an existing tag
2465 @SuppressWarnings("unused")
2466 private void deleteSavedSearch() {
2467 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2469 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2470 QMessageBox.StandardButton.Yes,
2471 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2475 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2476 for (int i=selections.size()-1; i>=0; i--) {
2477 QTreeWidgetItem currentSelection;
2478 currentSelection = selections.get(i);
2479 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2480 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2481 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2482 listManager.getSavedSearchIndex().remove(j);
2483 j=listManager.getSavedSearchIndex().size()+1;
2486 selections.remove(i);
2488 savedSearchIndexUpdated();
2489 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2491 // Setup the tree containing the user's tags
2492 private void initializeSavedSearchTree() {
2493 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2494 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2495 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2497 // Listener when a tag is selected
2498 @SuppressWarnings("unused")
2499 private void savedSearchTreeSelection() {
2500 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2502 clearNotebookFilter();
2505 clearAttributeFilter();
2507 String currentGuid = selectedSavedSearchGUID;
2508 menuBar.savedSearchEditAction.setEnabled(true);
2509 menuBar.savedSearchDeleteAction.setEnabled(true);
2510 menuBar.savedSearchIconAction.setEnabled(true);
2511 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2512 QTreeWidgetItem currentSelection;
2513 selectedSavedSearchGUID = "";
2514 for (int i=0; i<selections.size(); i++) {
2515 currentSelection = selections.get(i);
2516 if (currentSelection.text(1).equals(currentGuid)) {
2517 currentSelection.setSelected(false);
2519 selectedSavedSearchGUID = currentSelection.text(1);
2521 // i = selections.size() +1;
2524 // There is the potential for no notebooks to be selected if this
2525 // happens then we make it look like all notebooks were selecetd.
2526 // If that happens, just select the "all notebooks"
2527 if (selections.size()==0) {
2528 clearSavedSearchFilter();
2530 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2532 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2534 private void clearSavedSearchFilter() {
2535 menuBar.savedSearchEditAction.setEnabled(false);
2536 menuBar.savedSearchDeleteAction.setEnabled(false);
2537 menuBar.savedSearchIconAction.setEnabled(false);
2538 savedSearchTree.blockSignals(true);
2539 savedSearchTree.clearSelection();
2540 savedSearchTree.blockSignals(false);
2541 selectedSavedSearchGUID = "";
2542 searchField.setEditText("");
2543 searchPerformed = false;
2544 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2546 // trigger the tag index to be refreshed
2547 private void savedSearchIndexUpdated() {
2548 if (selectedSavedSearchGUID == null)
2549 selectedSavedSearchGUID = new String();
2550 savedSearchTree.blockSignals(true);
2551 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2552 savedSearchTree.load(listManager.getSavedSearchIndex());
2553 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2554 savedSearchTree.blockSignals(false);
2556 // trigger when the saved search selection changes
2557 @SuppressWarnings("unused")
2558 private void updateSavedSearchSelection() {
2559 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2561 menuBar.savedSearchEditAction.setEnabled(true);
2562 menuBar.savedSearchDeleteAction.setEnabled(true);
2563 menuBar.savedSearchIconAction.setEnabled(true);
2564 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2566 if (selections.size() > 0) {
2567 menuBar.savedSearchEditAction.setEnabled(true);
2568 menuBar.savedSearchDeleteAction.setEnabled(true);
2569 menuBar.savedSearchIconAction.setEnabled(true);
2570 selectedSavedSearchGUID = selections.get(0).text(1);
2571 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2572 searchField.setEditText(s.getQuery());
2574 menuBar.savedSearchEditAction.setEnabled(false);
2575 menuBar.savedSearchDeleteAction.setEnabled(false);
2576 menuBar.savedSearchIconAction.setEnabled(false);
2577 selectedSavedSearchGUID = "";
2578 searchField.setEditText("");
2580 searchFieldChanged();
2582 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2586 // Show/Hide note information
2587 @SuppressWarnings("unused")
2588 private void toggleSavedSearchWindow() {
2589 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2590 if (savedSearchTree.isVisible())
2591 savedSearchTree.hide();
2593 savedSearchTree.show();
2594 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2596 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2597 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2599 // Change the icon for a saved search
2600 @SuppressWarnings("unused")
2601 private void setSavedSearchIcon() {
2602 QTreeWidgetItem currentSelection;
2603 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2604 if (selections.size() == 0)
2607 currentSelection = selections.get(0);
2608 String guid = currentSelection.text(1);
2610 QIcon currentIcon = currentSelection.icon(0);
2611 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2614 dialog = new SetIcon(currentIcon, saveLastPath);
2615 dialog.setUseDefaultIcon(true);
2617 dialog = new SetIcon(icon, saveLastPath);
2618 dialog.setUseDefaultIcon(false);
2621 if (dialog.okPressed()) {
2622 saveLastPath = dialog.getPath();
2623 QIcon newIcon = dialog.getIcon();
2624 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2625 if (newIcon == null)
2626 newIcon = new QIcon(iconPath+"search.png");
2627 currentSelection.setIcon(0, newIcon);
2635 //***************************************************************
2636 //***************************************************************
2637 //** These functions deal with Help menu & tool menu items
2638 //***************************************************************
2639 //***************************************************************
2640 // Show database status
2641 @SuppressWarnings("unused")
2642 private void databaseStatus() {
2644 indexRunner.interrupt = true;
2645 int dirty = conn.getNoteTable().getDirtyCount();
2646 int unindexed = conn.getNoteTable().getUnindexedCount();
2647 DatabaseStatus status = new DatabaseStatus();
2648 status.setUnsynchronized(dirty);
2649 status.setUnindexed(unindexed);
2650 status.setNoteCount(conn.getNoteTable().getNoteCount());
2651 status.setNotebookCount(listManager.getNotebookIndex().size());
2652 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2653 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2654 status.setTagCount(listManager.getTagIndex().size());
2655 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2656 status.setWordCount(conn.getWordsTable().getWordCount());
2660 // Compact the database
2661 @SuppressWarnings("unused")
2662 private void compactDatabase() {
2663 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2664 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2665 "but please be aware that depending upon the size of your database this can be time consuming " +
2666 "and NixNote will be unresponsive until it is complete. Do you wish to continue?"),
2667 QMessageBox.StandardButton.Yes,
2668 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2671 setMessage("Compacting database.");
2673 listManager.compactDatabase();
2675 setMessage("Database compact is complete.");
2676 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2678 @SuppressWarnings("unused")
2679 private void accountInformation() {
2680 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2681 AccountDialog dialog = new AccountDialog();
2683 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2685 @SuppressWarnings("unused")
2686 private void releaseNotes() {
2687 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2688 QDialog dialog = new QDialog(this);
2689 QHBoxLayout layout = new QHBoxLayout();
2690 QTextEdit textBox = new QTextEdit();
2691 layout.addWidget(textBox);
2692 textBox.setReadOnly(true);
2693 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2694 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2695 QIODevice.OpenModeFlag.Text)))
2697 textBox.setText(file.readAll().toString());
2699 dialog.setWindowTitle(tr("Release Notes"));
2700 dialog.setLayout(layout);
2702 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2704 // Called when user picks Log from the help menu
2705 @SuppressWarnings("unused")
2706 private void logger() {
2707 logger.log(logger.HIGH, "Entering NeverNote.logger");
2708 LogFileDialog dialog = new LogFileDialog(emitLog);
2710 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2712 // Menu option "help/about" was selected
2713 @SuppressWarnings("unused")
2714 private void about() {
2715 logger.log(logger.HIGH, "Entering NeverNote.about");
2716 QMessageBox.about(this,
2717 tr("About NixNote"),
2718 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2720 +tr("<hr></center>Evernote"
2721 +"An Open Source Evernote Client.<br><br>"
2722 +"Licensed under GPL v2. <br><hr><br>"
2723 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2724 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2725 +"PDFRenderer is licened under the LGPL<br>"
2726 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2727 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2728 +"Jazzy is licened under the LGPL<br>"
2729 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2730 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2731 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2732 logger.log(logger.HIGH, "Leaving NeverNote.about");
2734 // Hide the entire left hand side
2735 @SuppressWarnings("unused")
2736 private void toggleLeftSide() {
2739 hidden = !menuBar.hideLeftSide.isChecked();
2740 menuBar.hideLeftSide.setChecked(!hidden);
2743 leftSplitter1.setHidden(true);
2745 leftSplitter1.setHidden(false);
2747 Global.saveWindowVisible("leftPanel", hidden);
2750 public void checkForUpdates() {
2751 // Send off thread to check for a new version
2752 versionChecker = new QNetworkAccessManager(this);
2753 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2754 QNetworkRequest request = new QNetworkRequest();
2755 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2756 versionChecker.get(request);
2758 @SuppressWarnings("unused")
2759 private void upgradeFileRead(QNetworkReply reply) {
2760 if (!reply.isReadable())
2763 String winVersion = Global.version;
2764 String osxVersion = Global.version;
2765 String linuxVersion = Global.version;
2766 String linux64Version = Global.version;
2767 String version = Global.version;
2769 // Determine the versions available
2770 QByteArray data = reply.readLine();
2771 while (data != null && !reply.atEnd()) {
2772 String line = data.toString();
2774 if (line.contains(":"))
2775 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2778 if (line.toLowerCase().contains("windows"))
2779 winVersion = lineVersion;
2780 else if (line.toLowerCase().contains("os-x"))
2781 osxVersion = lineVersion;
2782 else if (line.toLowerCase().contains("linux amd64"))
2783 linux64Version = lineVersion;
2784 else if (line.toLowerCase().contains("linux i386"))
2785 linuxVersion = lineVersion;
2786 else if (line.toLowerCase().contains("default"))
2787 version = lineVersion;
2789 // Read the next line
2790 data = reply.readLine();
2793 // Now we need to determine what system we are on.
2794 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2795 version = winVersion;
2796 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2797 version = osxVersion;
2798 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2799 if (System.getProperty("os.arch").contains("amd64") ||
2800 System.getProperty("os.arch").contains("x86_64"))
2801 version = linux64Version;
2803 version = linuxVersion;
2807 for (String validVersion : Global.validVersions) {
2808 if (version.equals(validVersion))
2812 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2814 if (dialog.remindMe())
2815 Global.setCheckVersionUpgrade(true);
2817 Global.setCheckVersionUpgrade(false);
2821 //***************************************************************
2822 //***************************************************************
2823 //** These functions deal with the Toolbar
2824 //***************************************************************
2825 //***************************************************************
2826 @SuppressWarnings("unused")
2827 private void focusSearch() {
2828 searchField.setFocus();
2831 // Text in the search bar has been cleared
2832 private void searchFieldCleared() {
2835 // This is done because we want to force a reload of
2836 // images. Some images we may want to highlight the text.
2837 readOnlyCache.clear();
2838 inkNoteCache.clear();
2840 QWebSettings.setMaximumPagesInCache(0);
2841 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2843 searchField.setEditText("");
2844 saveNoteColumnPositions();
2845 saveNoteIndexWidth();
2846 noteIndexUpdated(true);
2847 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2848 currentNote = listManager.getNoteIndex().get(0);
2849 currentNoteGuid = currentNote.getGuid();
2851 refreshEvernoteNote(true);
2852 if (currentNote != null)
2853 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2855 // text in the search bar changed. We only use this to tell if it was cleared,
2856 // otherwise we trigger off searchFieldChanged.
2857 @SuppressWarnings("unused")
2858 private void searchFieldTextChanged(String text) {
2859 QWebSettings.setMaximumPagesInCache(0);
2860 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2862 if (text.trim().equals("")) {
2863 searchFieldCleared();
2864 if (searchPerformed) {
2866 // This is done because we want to force a reload of
2867 // images. Some images we may want to highlight the text.
2869 readOnlyCache.clear();
2870 inkNoteCache.clear();
2872 listManager.setEnSearch("");
2873 listManager.loadNotesIndex();
2874 refreshEvernoteNote(true);
2875 noteIndexUpdated(false);
2876 refreshEvernoteNote(true);
2878 searchPerformed = false;
2881 // Text in the toolbar has changed
2882 private void searchFieldChanged() {
2883 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2885 readOnlyCache.clear();
2886 inkNoteCache.clear();
2887 saveNoteColumnPositions();
2888 saveNoteIndexWidth();
2889 String text = searchField.currentText();
2890 listManager.setEnSearch(text.trim());
2891 listManager.loadNotesIndex();
2892 noteIndexUpdated(false);
2893 refreshEvernoteNote(true);
2894 searchPerformed = true;
2895 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2898 // Build the window tool bar
2899 private void setupToolBar() {
2900 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2901 toolBar = addToolBar(tr("Tool Bar"));
2902 toolBar.setObjectName("toolBar");
2903 menuBar.setupToolBarVisible();
2904 if (!Global.isWindowVisible("toolBar"))
2905 toolBar.setVisible(false);
2907 toolBar.setVisible(true);
2909 // toolBar.addWidget(menuBar);
2910 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2911 // toolBar.addSeparator();
2912 prevButton = toolBar.addAction(tr("Previous"));
2913 QIcon prevIcon = new QIcon(iconPath+"back.png");
2914 prevButton.setIcon(prevIcon);
2915 prevButton.triggered.connect(this, "previousViewedAction()");
2916 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2918 nextButton = toolBar.addAction(tr("Next"));
2919 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2920 nextButton.setIcon(nextIcon);
2921 nextButton.triggered.connect(this, "nextViewedAction()");
2922 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2924 upButton = toolBar.addAction(tr("Up"));
2925 QIcon upIcon = new QIcon(iconPath+"up.png");
2926 upButton.setIcon(upIcon);
2927 upButton.triggered.connect(this, "upAction()");
2928 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2931 downButton = toolBar.addAction(tr("Down"));
2932 QIcon downIcon = new QIcon(iconPath+"down.png");
2933 downButton.setIcon(downIcon);
2934 downButton.triggered.connect(this, "downAction()");
2935 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2937 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2938 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2939 synchronizeIconAngle = 0;
2940 synchronizeButton.triggered.connect(this, "evernoteSync()");
2941 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2943 printButton = toolBar.addAction(tr("Print"));
2944 QIcon printIcon = new QIcon(iconPath+"print.png");
2945 printButton.setIcon(printIcon);
2946 printButton.triggered.connect(this, "printNote()");
2947 togglePrintButton(Global.isToolbarButtonVisible("print"));
2949 tagButton = toolBar.addAction(tr("Tag"));
2950 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2951 tagButton.setIcon(tagIcon);
2952 tagButton.triggered.connect(browserWindow, "modifyTags()");
2953 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2955 attributeButton = toolBar.addAction(tr("Attributes"));
2956 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2957 attributeButton.setIcon(attributeIcon);
2958 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2959 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2961 emailButton = toolBar.addAction(tr("Email"));
2962 QIcon emailIcon = new QIcon(iconPath+"email.png");
2963 emailButton.setIcon(emailIcon);
2964 emailButton.triggered.connect(this, "emailNote()");
2965 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2967 deleteButton = toolBar.addAction(tr("Delete"));
2968 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2969 deleteButton.setIcon(deleteIcon);
2970 deleteButton.triggered.connect(this, "deleteNote()");
2971 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2973 newButton = toolBar.addAction(tr("New"));
2974 QIcon newIcon = new QIcon(iconPath+"new.png");
2975 newButton.triggered.connect(this, "addNote()");
2976 newButton.setIcon(newIcon);
2977 toggleNewButton(Global.isToolbarButtonVisible("new"));
2979 allNotesButton = toolBar.addAction(tr("All Notes"));
2980 QIcon allIcon = new QIcon(iconPath+"books.png");
2981 allNotesButton.triggered.connect(this, "allNotes()");
2982 allNotesButton.setIcon(allIcon);
2983 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2985 //toolBar.addSeparator();
2986 //toolBar.addWidget(new QLabel(tr("Quota:")));
2987 //toolBar.addWidget(quotaBar);
2988 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2990 //toolBar.addSeparator();
2992 //toolBar.addWidget(new QLabel(tr("Zoom")));
2993 //toolBar.addWidget(zoomSpinner);
2995 //toolBar.addWidget(new QLabel(" "));
2996 //toolBar.addSeparator();
2997 //toolBar.addWidget(new QLabel(tr(" Search:")));
2998 //toolBar.addWidget(searchField);
2999 QSizePolicy sizePolicy = new QSizePolicy();
3000 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
3001 QLabel spacer = new QLabel("");
3002 spacer.setSizePolicy(sizePolicy);
3003 toolBar.addWidget(spacer);
3004 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3006 //searchClearButton = toolBar.addAction("Search Clear");
3007 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3008 //searchClearButton.setIcon(searchClearIcon);
3009 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3010 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3012 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3014 // Update the sychronize button picture
3016 public QMenu createPopupMenu() {
3017 QMenu contextMenu = super.createPopupMenu();
3019 contextMenu.addSeparator();
3020 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3021 contextMenu.addAction(prevAction);
3022 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3024 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3025 contextMenu.addAction(nextAction);
3026 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3028 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3029 contextMenu.addAction(upAction);
3030 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3032 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3033 contextMenu.addAction(downAction);
3034 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3036 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3037 contextMenu.addAction(synchronizeAction);
3038 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3040 QAction printAction = addContextAction("print", tr("Print"));
3041 contextMenu.addAction(printAction);
3042 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3044 QAction tagAction = addContextAction("tag", tr("Tag"));
3045 contextMenu.addAction(tagAction);
3046 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3048 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3049 contextMenu.addAction(attributeAction);
3050 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3052 QAction emailAction = addContextAction("email", tr("Email"));
3053 contextMenu.addAction(emailAction);
3054 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3056 QAction deleteAction = addContextAction("delete", tr("Delete"));
3057 contextMenu.addAction(deleteAction);
3058 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3060 QAction newAction = addContextAction("new", tr("Add"));
3061 contextMenu.addAction(newAction);
3062 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3064 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3065 contextMenu.addAction(allNotesAction);
3066 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3068 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3069 contextMenu.addAction(searchClearAction);
3070 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3075 private QAction addContextAction(String config, String name) {
3076 QAction newAction = new QAction(this);
3077 newAction.setText(name);
3078 newAction.setCheckable(true);
3079 newAction.setChecked(Global.isToolbarButtonVisible(config));
3082 private void togglePrevArrowButton(Boolean toggle) {
3083 prevButton.setVisible(toggle);
3084 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3086 private void toggleNextArrowButton(Boolean toggle) {
3087 nextButton.setVisible(toggle);
3088 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3090 private void toggleUpArrowButton(Boolean toggle) {
3091 upButton.setVisible(toggle);
3092 Global.saveToolbarButtonsVisible("upArrow", toggle);
3094 private void toggleDownArrowButton(Boolean toggle) {
3095 downButton.setVisible(toggle);
3096 Global.saveToolbarButtonsVisible("downArrow", toggle);
3098 private void toggleSynchronizeButton(Boolean toggle) {
3099 synchronizeButton.setVisible(toggle);
3100 Global.saveToolbarButtonsVisible("synchronize", toggle);
3102 private void togglePrintButton(Boolean toggle) {
3103 printButton.setVisible(toggle);
3104 Global.saveToolbarButtonsVisible("print", toggle);
3106 private void toggleTagButton(Boolean toggle) {
3107 tagButton.setVisible(toggle);
3108 Global.saveToolbarButtonsVisible("tag", toggle);
3110 private void toggleAttributeButton(Boolean toggle) {
3111 attributeButton.setVisible(toggle);
3112 Global.saveToolbarButtonsVisible("attribute", toggle);
3114 private void toggleEmailButton(Boolean toggle) {
3115 emailButton.setVisible(toggle);
3116 Global.saveToolbarButtonsVisible("email", toggle);
3118 private void toggleDeleteButton(Boolean toggle) {
3119 deleteButton.setVisible(toggle);
3120 Global.saveToolbarButtonsVisible("delete", toggle);
3122 private void toggleNewButton(Boolean toggle) {
3123 newButton.setVisible(toggle);
3124 Global.saveToolbarButtonsVisible("new", toggle);
3126 private void toggleAllNotesButton(Boolean toggle) {
3127 allNotesButton.setVisible(toggle);
3128 Global.saveToolbarButtonsVisible("allNotes", toggle);
3130 @SuppressWarnings("unused")
3131 private void toggleSearchClearButton(Boolean toggle) {
3132 searchClearButton.setVisible(toggle);
3133 Global.saveToolbarButtonsVisible("searchClear", toggle);
3140 @SuppressWarnings("unused")
3141 private void updateSyncButton() {
3143 if (syncIcons == null) {
3144 syncIcons = new ArrayList<QPixmap>();
3146 synchronizeIconAngle = 0;
3147 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3149 for (int i=0; i<=360; i++) {
3150 QPixmap rotatedPix = new QPixmap(pix.size());
3151 QPainter p = new QPainter(rotatedPix);
3152 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3153 QSize size = pix.size();
3154 p.translate(size.width()/2, size.height()/2);
3157 p.setBackgroundMode(BGMode.OpaqueMode);
3158 p.translate(-size.width()/2, -size.height()/2);
3159 p.drawPixmap(0,0, pix);
3161 syncIcons.add(rotatedPix);
3165 synchronizeIconAngle++;
3166 if (synchronizeIconAngle > 359)
3167 synchronizeIconAngle=0;
3168 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3171 // Synchronize with Evernote
3173 private void evernoteSync() {
3174 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3175 if (!Global.isConnected)
3177 if (Global.isConnected)
3178 synchronizeAnimationTimer.start(5);
3179 // synchronizeAnimationTimer.start(200);
3181 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3183 private void updateQuotaBar() {
3184 long limit = Global.getUploadLimit();
3185 long amount = Global.getUploadAmount();
3186 if (amount>0 && limit>0) {
3187 int percent =(int)(amount*100/limit);
3188 quotaBar.setValue(percent);
3190 quotaBar.setValue(0);
3193 @SuppressWarnings("unused")
3194 private void zoomChanged() {
3195 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3198 //****************************************************************
3199 //****************************************************************
3200 //* System Tray functions
3201 //****************************************************************
3202 //****************************************************************
3203 private void trayToggleVisible() {
3208 if (windowMaximized)
3215 @SuppressWarnings("unused")
3216 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3217 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3218 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3219 trayToggleVisible();
3224 //***************************************************************
3225 //***************************************************************
3226 //** These functions deal with the trash tree
3227 //***************************************************************
3228 //***************************************************************
3229 // Setup the tree containing the trash.
3230 @SuppressWarnings("unused")
3231 private void trashTreeSelection() {
3232 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3234 clearNotebookFilter();
3236 clearAttributeFilter();
3237 clearSavedSearchFilter();
3239 String tempGuid = currentNoteGuid;
3241 // currentNoteGuid = "";
3242 currentNote = new Note();
3243 selectedNoteGUIDs.clear();
3244 listManager.getSelectedNotebooks().clear();
3245 listManager.getSelectedTags().clear();
3246 listManager.setSelectedSavedSearch("");
3247 browserWindow.clear();
3249 // toggle the add buttons
3250 newButton.setEnabled(!newButton.isEnabled());
3251 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3252 menuBar.noteAdd.setVisible(true);
3254 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3255 if (selections.size() == 0) {
3256 currentNoteGuid = trashNoteGuid;
3257 trashNoteGuid = tempGuid;
3258 Global.showDeleted = false;
3259 menuBar.noteRestoreAction.setEnabled(false);
3260 menuBar.noteRestoreAction.setVisible(false);
3263 currentNoteGuid = trashNoteGuid;
3264 trashNoteGuid = tempGuid;
3265 menuBar.noteRestoreAction.setEnabled(true);
3266 menuBar.noteRestoreAction.setVisible(true);
3267 Global.showDeleted = true;
3269 listManager.loadNotesIndex();
3270 noteIndexUpdated(false);
3271 //// browserWindow.setEnabled(newButton.isEnabled());
3272 browserWindow.setReadOnly(!newButton.isEnabled());
3273 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3275 // Empty the trash file
3276 @SuppressWarnings("unused")
3277 private void emptyTrash() {
3278 // browserWindow.clear();
3279 logger.log(logger.EXTREME, "Emptying Trash");
3280 listManager.emptyTrash();
3281 logger.log(logger.EXTREME, "Resetting view after trash empty");
3282 if (trashTree.selectedItems().size() > 0) {
3283 listManager.getSelectedNotebooks().clear();
3284 listManager.getSelectedTags().clear();
3285 listManager.setSelectedSavedSearch("");
3286 newButton.setEnabled(!newButton.isEnabled());
3287 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3288 menuBar.noteAdd.setVisible(true);
3289 browserWindow.clear();
3292 clearNotebookFilter();
3293 clearSavedSearchFilter();
3294 clearAttributeFilter();
3296 Global.showDeleted = false;
3297 menuBar.noteRestoreAction.setEnabled(false);
3298 menuBar.noteRestoreAction.setVisible(false);
3300 listManager.loadNotesIndex();
3301 noteIndexUpdated(false);
3304 // Show/Hide trash window
3305 @SuppressWarnings("unused")
3306 private void toggleTrashWindow() {
3307 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3308 if (trashTree.isVisible())
3312 menuBar.hideTrash.setChecked(trashTree.isVisible());
3314 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3315 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3317 private void clearTrashFilter() {
3318 Global.showDeleted = false;
3319 newButton.setEnabled(true);
3320 menuBar.noteAdd.setEnabled(true);
3321 menuBar.noteAdd.setVisible(true);
3322 trashTree.blockSignals(true);
3323 trashTree.clearSelection();
3324 trashTree.blockSignals(false);
3329 //***************************************************************
3330 //***************************************************************
3331 //** These functions deal with connection settings
3332 //***************************************************************
3333 //***************************************************************
3334 // SyncRunner had a problem and things are disconnected
3335 @SuppressWarnings("unused")
3336 private void remoteErrorDisconnect() {
3337 menuBar.connectAction.setText(tr("Connect"));
3338 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3339 menuBar.synchronizeAction.setEnabled(false);
3340 Global.isConnected = false;
3341 synchronizeAnimationTimer.stop();
3344 // Do a manual connect/disconnect
3345 private void remoteConnect() {
3346 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3348 if (Global.isConnected) {
3349 Global.isConnected = false;
3350 syncRunner.enDisconnect();
3351 setupConnectMenuOptions();
3356 AESEncrypter aes = new AESEncrypter();
3358 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3359 } catch (FileNotFoundException e) {
3360 // File not found, so we'll just get empty strings anyway.
3363 if (Global.getProxyValue("url").equals("")) {
3364 System.setProperty("http.proxyHost","") ;
3365 System.setProperty("http.proxyPort", "") ;
3366 System.setProperty("https.proxyHost","") ;
3367 System.setProperty("https.proxyPort", "") ;
3370 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3371 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3372 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3373 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3375 if (Global.getProxyValue("userid").equals("")) {
3376 Authenticator.setDefault(new Authenticator() {
3378 protected PasswordAuthentication getPasswordAuthentication() {
3380 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3386 syncRunner.userStoreUrl = Global.userStoreUrl;
3387 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3388 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3390 String userid = aes.getUserid();
3391 String password = aes.getPassword();
3392 if (!userid.equals("") && !password.equals("")) {
3393 Global.username = userid;
3394 Global.password = password;
3395 syncRunner.username = Global.username;
3396 syncRunner.password = Global.password;
3397 syncRunner.enConnect();
3400 Global.isConnected = syncRunner.isConnected;
3402 if (!Global.isConnected) {
3403 // Show the login dialog box
3404 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3405 LoginDialog login = new LoginDialog();
3408 if (!login.okPressed()) {
3412 Global.username = login.getUserid();
3413 Global.password = login.getPassword();
3415 syncRunner.username = Global.username;
3416 syncRunner.password = Global.password;
3417 syncRunner.enConnect();
3418 Global.isConnected = syncRunner.isConnected;
3421 if (!Global.isConnected)
3424 setupConnectMenuOptions();
3425 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3427 private void setupConnectMenuOptions() {
3428 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3429 if (!Global.isConnected) {
3430 menuBar.connectAction.setText(tr("Connect"));
3431 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3432 menuBar.synchronizeAction.setEnabled(false);
3434 menuBar.connectAction.setText(tr("Disconnect"));
3435 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3436 menuBar.synchronizeAction.setEnabled(true);
3438 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3443 //***************************************************************
3444 //***************************************************************
3445 //** These functions deal with the GUI Attribute tree
3446 //***************************************************************
3447 //***************************************************************
3448 @SuppressWarnings("unused")
3449 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3451 // clearTagFilter();
3452 // clearNotebookFilter();
3454 // clearSavedSearchFilter();
3456 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3457 if (item.childCount() > 0) {
3458 item.setSelected(false);
3460 Global.createdBeforeFilter.reset();
3461 Global.createdSinceFilter.reset();
3462 Global.changedBeforeFilter.reset();
3463 Global.changedSinceFilter.reset();
3464 Global.containsFilter.reset();
3465 attributeTreeSelected = item;
3466 DateAttributeFilterTable f = null;
3467 f = findDateAttributeFilterTable(item.parent());
3469 f.select(item.parent().indexOfChild(item));
3471 Global.containsFilter.select(item.parent().indexOfChild(item));
3474 listManager.loadNotesIndex();
3475 noteIndexUpdated(false);
3478 attributeTreeSelected = null;
3479 item.setSelected(false);
3480 Global.createdBeforeFilter.reset();
3481 Global.createdSinceFilter.reset();
3482 Global.changedBeforeFilter.reset();
3483 Global.changedSinceFilter.reset();
3484 Global.containsFilter.reset();
3485 listManager.loadNotesIndex();
3486 noteIndexUpdated(false);
3488 // This determines what attribute filter we need, depending upon the selection
3489 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3490 if (w.parent() != null && w.childCount() > 0) {
3491 QTreeWidgetItem parent = w.parent();
3492 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3493 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3494 return Global.createdSinceFilter;
3495 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3496 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3497 return Global.createdBeforeFilter;
3498 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3499 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3500 return Global.changedSinceFilter;
3501 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3502 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3503 return Global.changedBeforeFilter;
3508 // Show/Hide attribute search window
3509 @SuppressWarnings("unused")
3510 private void toggleAttributesWindow() {
3511 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3512 if (attributeTree.isVisible())
3513 attributeTree.hide();
3515 attributeTree.show();
3516 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3518 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3519 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3521 private void clearAttributeFilter() {
3522 Global.createdBeforeFilter.reset();
3523 Global.createdSinceFilter.reset();
3524 Global.changedBeforeFilter.reset();
3525 Global.changedSinceFilter.reset();
3526 Global.containsFilter.reset();
3527 attributeTreeSelected = null;
3528 attributeTree.blockSignals(true);
3529 attributeTree.clearSelection();
3530 attributeTree.blockSignals(false);
3534 //***************************************************************
3535 //***************************************************************
3536 //** These functions deal with the GUI Note index table
3537 //***************************************************************
3538 //***************************************************************
3539 // Initialize the note list table
3540 private void initializeNoteTable() {
3541 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3542 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3543 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3544 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3546 // Show/Hide trash window
3547 @SuppressWarnings("unused")
3548 private void toggleNoteListWindow() {
3549 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3550 if (noteTableView.isVisible())
3551 noteTableView.hide();
3553 noteTableView.show();
3554 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3556 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3557 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3559 // Handle the event that a user selects a note from the table
3560 @SuppressWarnings("unused")
3561 private void noteTableSelection() {
3562 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3566 // If we have more than one selection, then set the merge note action to true.
3567 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3568 if (selections.size() > 1)
3569 menuBar.noteMergeAction.setEnabled(true);
3571 menuBar.noteMergeAction.setEnabled(false);
3573 // If the ctrl key is pressed, then they are selecting multiple
3574 // entries and we don't want to change the currently viewed note.
3575 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3576 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3579 if (historyGuids.size() == 0) {
3580 historyGuids.add(currentNoteGuid);
3581 historyPosition = 1;
3583 noteTableView.showColumn(Global.noteTableGuidPosition);
3585 if (!Global.isColumnVisible("guid"))
3586 noteTableView.hideColumn(Global.noteTableGuidPosition);
3588 if (selections.size() > 0) {
3590 menuBar.noteDuplicateAction.setEnabled(true);
3591 menuBar.noteOnlineHistoryAction.setEnabled(true);
3592 menuBar.noteMergeAction.setEnabled(true);
3593 selectedNoteGUIDs.clear();
3594 if (selections.size() != 1 || Global.showDeleted) {
3595 menuBar.noteDuplicateAction.setEnabled(false);
3597 if (selections.size() != 1 || !Global.isConnected) {
3598 menuBar.noteOnlineHistoryAction.setEnabled(false);
3600 if (selections.size() == 1) {
3601 menuBar.noteMergeAction.setEnabled(false);
3603 for (int i=0; i<selections.size(); i++) {
3604 int row = selections.get(i).row();
3606 upButton.setEnabled(false);
3608 upButton.setEnabled(true);
3609 if (row < listManager.getNoteTableModel().rowCount()-1)
3610 downButton.setEnabled(true);
3612 downButton.setEnabled(false);
3613 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3614 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3615 currentNoteGuid = (String)ix.values().toArray()[0];
3616 selectedNoteGUIDs.add(currentNoteGuid);
3620 nextButton.setEnabled(true);
3621 prevButton.setEnabled(true);
3623 int endPosition = historyGuids.size()-1;
3624 for (int j=historyPosition; j<=endPosition; j++) {
3625 historyGuids.remove(historyGuids.size()-1);
3627 historyGuids.add(currentNoteGuid);
3628 historyPosition = historyGuids.size();
3630 if (historyPosition <= 1)
3631 prevButton.setEnabled(false);
3632 if (historyPosition == historyGuids.size())
3633 nextButton.setEnabled(false);
3635 fromHistory = false;
3636 scrollToGuid(currentNoteGuid);
3637 refreshEvernoteNote(true);
3638 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3640 // Trigger a refresh when the note db has been updated
3641 private void noteIndexUpdated(boolean reload) {
3642 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3644 refreshEvernoteNoteList();
3645 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3646 noteTableView.load(reload);
3647 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3649 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3650 pos = noteTableView.proxyModel.rowCount();
3653 if (noteTableView.proxyModel.rowCount() == 0)
3656 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3658 currentNoteGuid = (String)i.data();
3662 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3664 scrollToGuid(currentNoteGuid);
3665 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3667 // Called when the list of notes is updated
3668 private void refreshEvernoteNoteList() {
3669 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3670 browserWindow.setDisabled(false);
3671 if (selectedNoteGUIDs == null)
3672 selectedNoteGUIDs = new ArrayList<String>();
3673 selectedNoteGUIDs.clear(); // clear out old entries
3675 String saveCurrentNoteGuid = new String();
3676 String tempNoteGuid = new String();
3678 historyGuids.clear();
3679 historyPosition = 0;
3680 prevButton.setEnabled(false);
3681 nextButton.setEnabled(false);
3683 if (currentNoteGuid == null)
3684 currentNoteGuid = new String();
3686 //determine current note guid
3687 for (Note note : listManager.getNoteIndex()) {
3688 tempNoteGuid = note.getGuid();
3689 if (currentNoteGuid.equals(tempNoteGuid)) {
3690 saveCurrentNoteGuid = tempNoteGuid;
3694 if (listManager.getNoteIndex().size() == 0) {
3695 currentNoteGuid = "";
3697 browserWindow.clear();
3698 browserWindow.setDisabled(true);
3701 if (!saveCurrentNoteGuid.equals("")) {
3702 refreshEvernoteNote(false);
3704 currentNoteGuid = "";
3706 reloadTagTree(false);
3708 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3710 // Called when the previous arrow button is clicked
3711 @SuppressWarnings("unused")
3712 private void previousViewedAction() {
3713 if (!prevButton.isEnabled())
3715 if (historyPosition == 0)
3718 if (historyPosition <= 0)
3720 String historyGuid = historyGuids.get(historyPosition-1);
3722 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3723 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3724 if (modelIndex != null) {
3725 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3726 String tableGuid = (String)ix.values().toArray()[0];
3727 if (tableGuid.equals(historyGuid)) {
3728 noteTableView.selectRow(i);
3734 @SuppressWarnings("unused")
3735 private void nextViewedAction() {
3736 if (!nextButton.isEnabled())
3738 String historyGuid = historyGuids.get(historyPosition);
3741 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3742 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3743 if (modelIndex != null) {
3744 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3745 String tableGuid = (String)ix.values().toArray()[0];
3746 if (tableGuid.equals(historyGuid)) {
3747 noteTableView.selectRow(i);
3753 // Called when the up arrow is clicked
3754 @SuppressWarnings("unused")
3755 private void upAction() {
3756 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3757 int row = selections.get(0).row();
3759 noteTableView.selectRow(row-1);
3762 // Called when the down arrow is clicked
3763 @SuppressWarnings("unused")
3764 private void downAction() {
3765 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3766 int row = selections.get(0).row();
3767 int max = listManager.getNoteTableModel().rowCount();
3769 noteTableView.selectRow(row+1);
3772 // Update a tag string for a specific note in the list
3773 @SuppressWarnings("unused")
3774 private void updateListTags(String guid, List<String> tags) {
3775 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3776 StringBuffer tagBuffer = new StringBuffer();
3777 for (int i=0; i<tags.size(); i++) {
3778 tagBuffer.append(tags.get(i));
3779 if (i<tags.size()-1)
3780 tagBuffer.append(", ");
3783 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3784 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3785 if (modelIndex != null) {
3786 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3787 String tableGuid = (String)ix.values().toArray()[0];
3788 if (tableGuid.equals(guid)) {
3789 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3790 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3791 noteTableView.proxyModel.invalidate();
3796 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3798 // Update a title for a specific note in the list
3799 @SuppressWarnings("unused")
3800 private void updateListAuthor(String guid, String author) {
3801 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3803 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3804 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3805 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3806 if (modelIndex != null) {
3807 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3808 String tableGuid = (String)ix.values().toArray()[0];
3809 if (tableGuid.equals(guid)) {
3810 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3811 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3812 noteTableView.proxyModel.invalidate();
3818 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3820 private void updateListNoteNotebook(String guid, String notebook) {
3821 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3822 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3823 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3825 // Update a title for a specific note in the list
3826 @SuppressWarnings("unused")
3827 private void updateListSourceUrl(String guid, String url) {
3828 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3830 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3831 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3832 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3833 if (modelIndex != null) {
3834 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3835 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3836 String tableGuid = (String)ix.values().toArray()[0];
3837 if (tableGuid.equals(guid)) {
3838 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3839 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3840 noteTableView.proxyModel.invalidate();
3845 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3847 @SuppressWarnings("unused")
3848 private void updateListGuid(String oldGuid, String newGuid) {
3849 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3851 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3852 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3853 if (modelIndex != null) {
3854 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3855 String tableGuid = (String)ix.values().toArray()[0];
3856 if (tableGuid.equals(oldGuid)) {
3857 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3858 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3863 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3865 private void updateListTagName(String guid) {
3866 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3868 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3869 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3870 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3872 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3873 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3874 if (modelIndex != null) {
3875 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3876 String noteGuid = (String)ix.values().toArray()[0];
3877 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3878 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3879 i=listManager.getNoteTableModel().rowCount();
3885 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3887 private void removeListTagName(String guid) {
3888 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3890 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3891 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3892 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3893 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3894 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3897 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3898 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3899 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3900 if (modelIndex != null) {
3901 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3902 String noteGuid = (String)ix.values().toArray()[0];
3903 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3904 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3905 i=listManager.getNoteTableModel().rowCount();
3911 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3913 private void updateListNotebookName(String oldName, String newName) {
3914 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3916 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3917 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3918 if (modelIndex != null) {
3919 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3920 String tableName = (String)ix.values().toArray()[0];
3921 if (tableName.equalsIgnoreCase(oldName)) {
3922 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3926 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3928 @SuppressWarnings("unused")
3929 private void updateListDateCreated(String guid, QDateTime date) {
3930 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3932 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3933 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3934 if (modelIndex != null) {
3935 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3936 String tableGuid = (String)ix.values().toArray()[0];
3937 if (tableGuid.equals(guid)) {
3938 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3939 noteTableView.proxyModel.invalidate();
3944 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3946 @SuppressWarnings("unused")
3947 private void updateListDateSubject(String guid, QDateTime date) {
3948 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3950 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3951 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3952 if (modelIndex != null) {
3953 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3954 String tableGuid = (String)ix.values().toArray()[0];
3955 if (tableGuid.equals(guid)) {
3956 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3957 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3958 noteTableView.proxyModel.invalidate();
3963 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3965 private void updateListDateChanged(String guid, QDateTime date) {
3966 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3968 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3969 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3970 if (modelIndex != null) {
3971 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3972 String tableGuid = (String)ix.values().toArray()[0];
3973 if (tableGuid.equals(guid)) {
3974 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3975 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3980 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3982 private void updateListDateChanged() {
3983 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3984 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3985 updateListDateChanged(currentNoteGuid, date);
3986 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3989 private void scrollToCurrentGuid() {
3990 //scrollToGuid(currentNoteGuid);
3991 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3992 if (selections.size() == 0)
3994 QModelIndex index = selections.get(0);
3995 int row = selections.get(0).row();
3996 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3999 // Scroll to the current GUID in tthe list.
4000 // Scroll to a particular index item
4001 private void scrollToGuid(String guid) {
4002 if (currentNote == null || guid == null)
4004 if (currentNote.isActive() && Global.showDeleted) {
4005 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4006 if (!listManager.getNoteIndex().get(i).isActive()) {
4007 currentNote = listManager.getNoteIndex().get(i);
4008 currentNoteGuid = currentNote.getGuid();
4009 i = listManager.getNoteIndex().size();
4013 if (!currentNote.isActive() && !Global.showDeleted) {
4014 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4015 if (listManager.getNoteIndex().get(i).isActive()) {
4016 currentNote = listManager.getNoteIndex().get(i);
4017 currentNoteGuid = currentNote.getGuid();
4018 i = listManager.getNoteIndex().size();
4023 for (int i=0; i<noteTableView.model().rowCount(); i++) {
4024 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4025 if (currentNoteGuid.equals(index.data())) {
4026 // noteTableView.selectionModel().blockSignals(true);
4027 noteTableView.selectRow(i);
4028 // noteTableView.selectionModel().blockSignals(false);
4029 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
4030 i=listManager.getNoteTableModel().rowCount();
4033 noteTableView.repaint();
4035 // Show/Hide columns
4036 private void showColumns() {
4037 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4038 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4039 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4040 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4041 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4042 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4043 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4044 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4045 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4046 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4047 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4049 // Title color has changed
4050 @SuppressWarnings("unused")
4051 private void titleColorChanged(Integer color) {
4052 logger.log(logger.HIGH, "Entering NeverNote.titleColorChanged");
4055 QColor backgroundColor = new QColor();
4056 QColor foregroundColor = new QColor(QColor.black);
4057 backgroundColor.setRgb(color);
4059 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4060 foregroundColor.setRgb(QColor.white.rgb());
4062 if (selectedNoteGUIDs.size() == 0)
4063 selectedNoteGUIDs.add(currentNoteGuid);
4065 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4066 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4067 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4068 if (modelIndex != null) {
4069 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4070 String tableGuid = (String)ix.values().toArray()[0];
4071 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4072 for (int k=0; k<Global.noteTableColumnCount; k++) {
4073 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4074 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4075 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4077 i=listManager.getNoteTableModel().rowCount();
4082 logger.log(logger.HIGH, "Leaving NeverNote.titleColorChanged");
4084 // A note has been pinned or unpinned
4085 @SuppressWarnings("unused")
4086 private void notePinned() {
4087 logger.log(logger.EXTREME, "Entering NeverNote.notePinned()");
4090 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4091 NoteMetadata meta = listManager.getNoteMetadata().get(selectedNoteGUIDs.get(j));
4092 boolean pinned = !meta.isPinned();
4093 meta.setPinned(pinned); // Toggle the pinned/unpinned
4095 // Update the list & table
4096 listManager.updateNoteMetadata(meta);
4097 noteTableView.proxyModel.addGuid(selectedNoteGUIDs.get(j), meta);
4100 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4102 // Wide list was chosen
4103 public void narrowListView() {
4104 saveNoteColumnPositions();
4105 saveNoteIndexWidth();
4107 int sortCol = noteTableView.proxyModel.sortColumn();
4108 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4109 Global.setSortColumn(sortCol);
4110 Global.setSortOrder(sortOrder);
4112 Global.setListView(Global.View_List_Narrow);
4114 menuBar.wideListView.blockSignals(true);
4115 menuBar.narrowListView.blockSignals(true);
4117 menuBar.wideListView.setChecked(false);
4118 menuBar.narrowListView.setChecked(true);
4120 menuBar.wideListView.blockSignals(false);
4121 menuBar.narrowListView.blockSignals(false);
4123 mainLeftRightSplitter.addWidget(noteTableView);
4124 mainLeftRightSplitter.addWidget(browserWindow);
4125 restoreWindowState(false);
4126 noteTableView.repositionColumns();
4127 noteTableView.resizeColumnWidths();
4128 noteTableView.resizeRowHeights();
4130 sortCol = Global.getSortColumn();
4131 sortOrder = Global.getSortOrder();
4132 noteTableView.proxyModel.blocked = true;
4133 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4134 noteTableView.proxyModel.blocked = false;
4138 noteTableView.load(false);
4139 refreshEvernoteNote(true);
4140 scrollToCurrentGuid();
4142 public void wideListView() {
4143 int sortCol = noteTableView.proxyModel.sortColumn();
4144 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4145 Global.setSortColumn(sortCol);
4146 Global.setSortOrder(sortOrder);
4149 saveNoteColumnPositions();
4150 saveNoteIndexWidth();
4151 Global.setListView(Global.View_List_Wide);
4153 menuBar.wideListView.blockSignals(true);
4154 menuBar.narrowListView.blockSignals(true);
4156 menuBar.wideListView.setChecked(true);
4157 menuBar.narrowListView.setChecked(false);
4159 menuBar.wideListView.blockSignals(false);
4160 menuBar.narrowListView.blockSignals(false);
4161 browserIndexSplitter.setVisible(true);
4162 browserIndexSplitter.addWidget(noteTableView);
4163 browserIndexSplitter.addWidget(browserWindow);
4164 restoreWindowState(false);
4165 noteTableView.repositionColumns();
4166 noteTableView.resizeColumnWidths();
4167 noteTableView.resizeRowHeights();
4169 sortCol = Global.getSortColumn();
4170 sortOrder = Global.getSortOrder();
4171 noteTableView.proxyModel.blocked = true;
4172 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4173 noteTableView.proxyModel.blocked = false;
4176 noteTableView.load(false);
4177 scrollToCurrentGuid();
4179 // Sort order for the notebook has changed
4180 public void tableSortOrderChanged(Integer column, Integer order) {
4182 // Find what notebook (if any) is selected. We ignore stacks & the "All Notebooks".
4183 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4184 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4185 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4187 notebook = currentSelectedNotebook.text(2);
4188 conn.getNotebookTable().setSortOrder(notebook, column, order);
4192 //***************************************************************
4193 @SuppressWarnings("unused")
4194 private void evernoteLinkClick(String syncGuid, String locGuid) {
4196 if (conn.getNoteTable().guidExists(syncGuid)) {
4199 // If we didn't find it via the synchronized guid, look under the local guid
4200 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4201 // later synchronized (that causes the guid to change so we need to find the new one).
4202 if (conn.getNoteTable().guidExists(locGuid))
4205 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4208 openExternalEditor(guid);
4212 //If we've gotten this far, we can't find the note
4213 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4214 " seem to find that note."));
4216 //***************************************************************
4217 //***************************************************************
4218 //** External editor window functions
4219 //***************************************************************
4220 //***************************************************************
4221 private void listDoubleClick() {
4223 openExternalEditor(currentNoteGuid);
4225 private void openExternalEditor(String guid) {
4227 if (externalWindows.containsKey(guid)) {
4228 externalWindows.get(guid).raise();
4231 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4232 // We have a new external editor to create
4233 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4234 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4235 newBrowser.setWindowIcon(appIcon);
4236 externalWindows.put(guid, newBrowser);
4237 showEditorButtons(newBrowser.getBrowserWindow());
4238 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4239 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4240 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4241 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4242 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4243 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4244 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4245 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4247 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4248 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4249 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4253 @SuppressWarnings("unused")
4254 private void externalWindowTitleEdited(String guid, String text) {
4255 if (guid.equals(currentNoteGuid)) {
4256 browserWindow.setTitle(text);
4259 @SuppressWarnings({ "rawtypes", "unused" })
4260 private void externalWindowTagsEdited(String guid, List values) {
4261 StringBuffer line = new StringBuffer(100);
4262 for (int i=0; i<values.size(); i++) {
4264 line.append(Global.tagDelimeter+" ");
4265 line.append(values.get(i));
4267 if (guid.equals(currentNoteGuid)) {
4268 browserWindow.setTag(line.toString());
4271 @SuppressWarnings("unused")
4272 private void externalWindowClosing(String guid) {
4273 externalWindows.remove(guid);
4278 //***************************************************************
4279 //***************************************************************
4280 //** These functions deal with Note specific things
4281 //***************************************************************
4282 //***************************************************************
4283 private void setNoteDirty() {
4284 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4286 // Find if the note is being edited externally. If it is, update it.
4287 if (externalWindows.containsKey(currentNoteGuid)) {
4288 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4289 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4290 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4291 window.getBrowserWindow().setContent(unicode);
4294 // If the note is dirty, then it is unsynchronized by default.
4298 // Set the note as dirty and check if its status is synchronized in the display table
4300 if (listManager.getNoteMetadata().containsKey(currentNoteGuid) &&
4301 listManager.getNoteMetadata().get(currentNoteGuid).isDirty()) {
4305 // If this wasn't already marked as unsynchronized, then we need to update the table
4306 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4307 // listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4308 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4309 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4310 if (modelIndex != null) {
4311 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4312 String tableGuid = (String)ix.values().toArray()[0];
4313 if (tableGuid.equals(currentNoteGuid)) {
4314 listManager.getNoteTableModel().proxyModel.setData(i, Global.noteTableSynchronizedPosition, "false");
4320 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4322 @SuppressWarnings("unused")
4323 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4324 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4325 QByteArray unicode = codec.fromUnicode(content);
4326 noteCache.remove(guid);
4327 noteCache.put(guid, unicode.toString());
4328 if (guid.equals(currentNoteGuid)) {
4330 browserWindow.setContent(unicode);
4333 thumbnailRunner.addWork("GENERATE "+ guid);
4334 saveNote(guid, browser);
4338 private void saveNote() {
4340 saveNote(currentNoteGuid, browserWindow);
4341 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4345 private void saveNote(String guid, BrowserWindow window) {
4346 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4349 logger.log(logger.EXTREME, "Saving to cache");
4350 QTextCodec codec = QTextCodec.codecForLocale();
4351 // QTextDecoder decoder = codec.makeDecoder();
4352 codec = QTextCodec.codecForName("UTF-8");
4353 QByteArray unicode = codec.fromUnicode(window.getContent());
4354 noteCache.put(guid, unicode.toString());
4356 logger.log(logger.EXTREME, "updating list manager");
4357 listManager.updateNoteContent(guid, window.getContent());
4358 logger.log(logger.EXTREME, "Updating title");
4359 listManager.updateNoteTitle(guid, window.getTitle());
4360 updateListDateChanged();
4362 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4363 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4364 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4365 currentNote = listManager.getNoteIndex().get(i);
4366 i = listManager.getNoteIndex().size();
4371 // Get a note from Evernote (and put it in the browser)
4372 private void refreshEvernoteNote(boolean reload) {
4373 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4375 if (Global.disableViewing) {
4376 browserWindow.setEnabled(false);
4381 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4383 Global.cryptCounter =0;
4385 browserWindow.setReadOnly(true);
4393 browserWindow.loadingData(true);
4395 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4396 if (currentNote == null)
4398 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4401 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4402 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4403 formatter.setNote(note, Global.pdfPreview());
4404 formatter.setHighlight(listManager.getEnSearch());
4406 if (!noteCache.containsKey(guid)) {
4407 js = new QByteArray();
4408 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4409 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4410 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>");
4411 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4412 js.append("<style> img { max-width:100%; }</style>");
4413 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4414 js.append("</head>");
4415 formatter.setNote(note, Global.pdfPreview());
4416 js.append(formatter.rebuildNoteHTML());
4417 js.append("</HTML>");
4418 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4419 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4420 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4421 // if (Global.enableHTMLEntitiesFix) {
4422 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4424 browser.setContent(js);
4425 noteCache.put(guid, js.toString());
4427 if (formatter.resourceError)
4428 resourceErrorMessage();
4429 if (formatter.formatError) {
4431 QMessageBox.information(this, tr("Error"),
4432 tr("NixNote had issues formatting this note." +
4433 " To protect your data this note is being marked as read-only."));
4436 readOnly = formatter.readOnly;
4437 inkNote = formatter.inkNote;
4439 readOnlyCache.put(guid, true);
4441 inkNoteCache.put(guid, true);
4443 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4444 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4445 js = new QByteArray(cachedContent);
4446 browser.setContent(js);
4447 if (readOnlyCache.containsKey(guid))
4449 if (inkNoteCache.containsKey(guid))
4452 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4453 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4455 if (readOnly || inkNote)
4456 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4458 browser.getBrowser().page().setContentEditable(true);
4459 browser.setReadOnly(readOnly);
4460 deleteButton.setEnabled(!readOnly);
4461 tagButton.setEnabled(!readOnly);
4462 menuBar.noteDelete.setEnabled(!readOnly);
4463 menuBar.noteTags.setEnabled(!readOnly);
4464 browser.setNote(note);
4466 if (note != null && note.getNotebookGuid() != null &&
4467 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4468 deleteButton.setEnabled(false);
4469 menuBar.notebookDeleteAction.setEnabled(false);
4471 deleteButton.setEnabled(true);
4472 menuBar.notebookDeleteAction.setEnabled(true);
4475 // Build a list of non-closed notebooks
4476 List<Notebook> nbooks = new ArrayList<Notebook>();
4477 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4478 boolean found=false;
4479 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4480 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4484 nbooks.add(listManager.getNotebookIndex().get(i));
4487 browser.setTitle(note.getTitle());
4488 browser.setTag(getTagNamesForNote(note));
4489 browser.setAuthor(note.getAttributes().getAuthor());
4491 browser.setAltered(note.getUpdated());
4492 browser.setCreation(note.getCreated());
4493 if (note.getAttributes().getSubjectDate() > 0)
4494 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4496 browser.setSubjectDate(note.getCreated());
4497 browser.setUrl(note.getAttributes().getSourceURL());
4499 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4500 List<Tag> tagList = tagFilter.getValidTags(note);
4501 browser.setAllTags(tagList);
4503 browser.setCurrentTags(note.getTagNames());
4507 browser.loadingData(false);
4508 if (thumbnailViewer.isActiveWindow())
4511 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4512 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4515 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4517 // Save a generated thumbnail
4518 private void toggleNoteInformation() {
4519 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4520 browserWindow.toggleInformation();
4521 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4522 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4523 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4525 // Listener triggered when a print button is pressed
4526 @SuppressWarnings("unused")
4527 private void printNote() {
4528 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4530 QPrintDialog dialog = new QPrintDialog();
4531 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4532 QPrinter printer = dialog.printer();
4533 browserWindow.getBrowser().print(printer);
4535 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4538 // Listener triggered when the email button is pressed
4539 @SuppressWarnings("unused")
4540 private void emailNote() {
4541 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4543 if (Desktop.isDesktopSupported()) {
4544 Desktop desktop = Desktop.getDesktop();
4546 String text2 = browserWindow.getContentsToEmail();
4547 QUrl url = new QUrl("mailto:");
4548 url.addQueryItem("subject", currentNote.getTitle());
4549 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4550 url.addQueryItem("body", text2);
4551 QDesktopServices.openUrl(url);
4555 if (desktop.isSupported(Desktop.Action.MAIL)) {
4556 URI uriMailTo = null;
4558 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4559 String text = browserWindow.getContentsToEmail();
4560 //text = "<b>" +text +"</b>";
4561 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4562 +"&BODY=" +text, null);
4563 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4564 +"&ATTACHMENT=d:/test.pdf", null);
4565 desktop.mail(uriMailTo);
4566 } catch (URISyntaxException e) {
4567 e.printStackTrace();
4568 } catch (IOException e) {
4569 e.printStackTrace();
4576 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4578 // Reindex all notes
4579 @SuppressWarnings("unused")
4580 private void fullReindex() {
4581 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4582 indexRunner.addWork("REINDEXALL");
4583 setMessage(tr("Database will be reindexed."));
4584 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4586 // Listener when a user wants to reindex a specific note
4587 @SuppressWarnings("unused")
4588 private void reindexNote() {
4589 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4590 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4591 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4593 if (selectedNotebookGUIDs.size() > 1)
4594 setMessage(tr("Notes will be reindexed."));
4596 setMessage(tr("Note will be reindexed."));
4597 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4600 @SuppressWarnings("unused")
4601 private void deleteNote() {
4602 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4603 if (currentNote == null)
4605 if (currentNoteGuid.equals(""))
4607 String title = null;
4608 if (selectedNoteGUIDs.size() == 1)
4609 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4611 // If we are deleting non-trash notes
4612 if (currentNote.isActive()) {
4613 if (Global.verifyDelete()) {
4615 if (selectedNoteGUIDs.size() > 1) {
4616 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4619 msg = new String(tr("Delete note \"") +title +"\"?");
4621 msg = new String(tr("Delete note selected note?"));
4623 if (QMessageBox.question(this, tr("Confirmation"), msg,
4624 QMessageBox.StandardButton.Yes,
4625 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4629 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4630 selectedNoteGUIDs.add(currentNoteGuid);
4631 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4632 listManager.deleteNote(selectedNoteGUIDs.get(i));
4635 // If we are deleting from the trash.
4636 if (Global.verifyDelete()) {
4638 if (selectedNoteGUIDs.size() > 1) {
4639 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4642 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4644 msg = new String(tr("Permanently delete note selected note?"));
4646 if (QMessageBox.question(this, "Confirmation", msg,
4647 QMessageBox.StandardButton.Yes,
4648 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4652 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4653 selectedNoteGUIDs.add(currentNoteGuid);
4654 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4655 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4656 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4657 if (modelIndex != null) {
4658 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4659 String tableGuid = (String)ix.values().toArray()[0];
4660 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4661 listManager.getNoteTableModel().removeRow(j);
4666 listManager.expungeNote(selectedNoteGUIDs.get(i));
4669 currentNoteGuid = "";
4670 listManager.loadNotesIndex();
4671 noteIndexUpdated(false);
4672 refreshEvernoteNote(true);
4673 scrollToGuid(currentNoteGuid);
4674 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4677 @SuppressWarnings("unused")
4678 private void addNote() {
4679 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4680 // browserWindow.setEnabled(true);
4681 browserWindow.setReadOnly(false);
4683 Calendar currentTime = new GregorianCalendar();
4684 StringBuffer noteString = new StringBuffer(100);
4685 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4686 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4689 if (Global.overrideDefaultFont()) {
4690 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4691 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4692 noteString.append("<br clear=\"none\" />\n");
4693 noteString.append("</span>\n</font>\n");
4695 noteString.append("<br clear=\"none\" />\n");
4696 noteString.append("</en-note>");
4698 Long l = new Long(currentTime.getTimeInMillis());
4699 String randint = new String(Long.toString(l));
4701 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4703 // for the first non-archived notebook. Finally, if nothing else we
4704 // pick the first notebook in the list.
4705 String notebook = null;
4706 listManager.getNotebookIndex().get(0).getGuid();
4707 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4708 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4709 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4710 notebook = currentSelectedNotebook.text(2);
4712 boolean found = false;
4713 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4714 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4715 boolean match = false;
4716 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4717 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4719 j = listManager.getArchiveNotebookIndex().size();
4723 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4724 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4726 // Now we have a list of good notebooks, so we can look for the default
4728 for (int i=0; i<goodNotebooks.size(); i++) {
4729 if (goodNotebooks.get(i).isDefaultNotebook()) {
4730 notebook = goodNotebooks.get(i).getGuid();
4732 i = goodNotebooks.size();
4736 if (goodNotebooks.size() > 0 && !found)
4737 notebook = goodNotebooks.get(0).getGuid();
4740 notebook = listManager.getNotebookIndex().get(0).getGuid();
4743 Note newNote = new Note();
4744 newNote.setUpdateSequenceNum(0);
4745 newNote.setGuid(randint);
4746 newNote.setNotebookGuid(notebook);
4747 newNote.setTitle("Untitled Note");
4748 newNote.setContent(noteString.toString());
4749 newNote.setDeleted(0);
4750 newNote.setCreated(System.currentTimeMillis());
4751 newNote.setUpdated(System.currentTimeMillis());
4752 newNote.setActive(true);
4753 NoteAttributes na = new NoteAttributes();
4754 na.setLatitude(0.0);
4755 na.setLongitude(0.0);
4756 na.setAltitude(0.0);
4757 newNote.setAttributes(new NoteAttributes());
4758 newNote.setTagGuids(new ArrayList<String>());
4759 newNote.setTagNames(new ArrayList<String>());
4761 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4762 if (Global.newNoteWithSelectedTags()) {
4763 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4764 QTreeWidgetItem currentSelection;
4765 for (int i=0; i<selections.size(); i++) {
4766 currentSelection = selections.get(i);
4767 newNote.getTagGuids().add(currentSelection.text(2));
4768 newNote.getTagNames().add(currentSelection.text(0));
4772 conn.getNoteTable().addNote(newNote, true);
4773 NoteMetadata metadata = new NoteMetadata();
4774 metadata.setGuid(newNote.getGuid());
4775 metadata.setDirty(true);
4776 listManager.addNote(newNote, metadata);
4777 // noteTableView.insertRow(newNote, true, -1);
4779 currentNote = newNote;
4780 currentNoteGuid = currentNote.getGuid();
4781 noteTableView.clearSelection();
4782 refreshEvernoteNote(true);
4783 listManager.countNotebookResults(listManager.getNoteIndex());
4784 browserWindow.titleLabel.setFocus();
4785 browserWindow.titleLabel.selectAll();
4786 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4788 // If the window is hidden, then we want to popup this in an external window &
4792 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4794 // Restore a note from the trash;
4795 @SuppressWarnings("unused")
4796 private void restoreNote() {
4798 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4799 selectedNoteGUIDs.add(currentNoteGuid);
4800 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4801 listManager.restoreNote(selectedNoteGUIDs.get(i));
4803 currentNoteGuid = "";
4804 listManager.loadNotesIndex();
4805 noteIndexUpdated(false);
4808 // Search a note for specific txt
4809 @SuppressWarnings("unused")
4810 private void findText() {
4812 find.setFocusOnTextField();
4814 @SuppressWarnings("unused")
4815 private void doFindText() {
4816 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4819 @SuppressWarnings("unused")
4820 private void updateNoteTitle(String guid, String title) {
4821 listManager.setNoteSynchronized(guid, false);
4823 // Signal received that note content has changed. Normally we just need the guid to remove
4824 // it from the cache.
4825 @SuppressWarnings("unused")
4826 private void invalidateNoteCache(String guid, String content) {
4827 noteCache.remove(guid);
4828 refreshEvernoteNote(true);
4830 // Signal received that a note guid has changed
4831 @SuppressWarnings("unused")
4832 private void noteGuidChanged(String oldGuid, String newGuid) {
4833 if (noteCache.containsKey(oldGuid)) {
4834 if (!oldGuid.equals(currentNoteGuid)) {
4835 String cache = noteCache.get(oldGuid);
4836 noteCache.put(newGuid, cache);
4837 noteCache.remove(oldGuid);
4839 noteCache.remove(oldGuid);
4840 noteCache.put(newGuid, browserWindow.getContent());
4844 listManager.updateNoteGuid(oldGuid, newGuid, false);
4845 if (currentNoteGuid.equals(oldGuid)) {
4846 if (currentNote != null)
4847 currentNote.setGuid(newGuid);
4848 currentNoteGuid = newGuid;
4851 if (externalWindows.containsKey(oldGuid)) {
4852 ExternalBrowse b = externalWindows.get(oldGuid);
4853 externalWindows.remove(oldGuid);
4854 b.getBrowserWindow().getNote().setGuid(newGuid);
4855 externalWindows.put(newGuid, b);
4858 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4859 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4860 noteTableView.proxyModel.addGuid(newGuid, listManager.getNoteMetadata().get(newGuid));
4861 i=listManager.getNoteIndex().size();
4865 if (listManager.getNoteTableModel().metaData.containsKey(oldGuid)) {
4866 NoteMetadata meta = listManager.getNoteTableModel().metaData.get(oldGuid);
4867 listManager.getNoteTableModel().metaData.put(newGuid, meta);
4868 listManager.getNoteTableModel().metaData.remove(oldGuid);
4872 // Toggle the note editor button bar
4873 private void toggleEditorButtonBar() {
4874 if (browserWindow.buttonsVisible) {
4875 browserWindow.hideButtons();
4876 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4877 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4879 browserWindow.buttonsVisible = true;
4880 showEditorButtons(browserWindow);
4882 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4884 // Show editor buttons
4885 private void showEditorButtons(BrowserWindow browser) {
4886 browser.buttonLayout.setVisible(true);
4887 browser.undoAction.setVisible(false);
4889 browser.undoButton.setVisible(false);
4891 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4892 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4893 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4894 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4895 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4896 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4897 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4898 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4899 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4900 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4901 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4902 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4903 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4904 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4905 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4906 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4907 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4908 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4909 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4910 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4911 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4912 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4913 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4915 private void duplicateNote(String guid) {
4917 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4918 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4919 oldNote.setContent(conn.getNoteTable().getNoteContentNoUTFConversion(guid));
4920 oldNote.setResources(resList);
4921 duplicateNote(oldNote);
4923 private void duplicateNote(Note oldNote) {
4925 // Now that we have a good notebook guid, we need to move the conflicting note
4926 // to the local notebook
4927 Calendar currentTime = new GregorianCalendar();
4928 Long l = new Long(currentTime.getTimeInMillis());
4929 String newGuid = new String(Long.toString(l));
4931 // Note newNote = oldNote.deepCopy();
4932 Note newNote = (Note)Global.deepCopy(oldNote);
4933 newNote.setUpdateSequenceNum(0);
4934 newNote.setGuid(newGuid);
4935 newNote.setDeleted(0);
4936 newNote.setActive(true);
4939 List<String> tagNames = new ArrayList<String>();
4940 List<String> tagGuids = new ArrayList<String>();;
4941 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4942 tagNames.add(oldNote.getTagNames().get(i));
4943 tagGuids.add(oldNote.getTagGuids().get(i));
4946 // Sort note Tags to make them look nice
4947 for (int i=0; i<tagNames.size()-1; i++) {
4948 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4949 String n1 = tagNames.get(i);
4950 String n2 = tagNames.get(i+1);
4951 tagNames.set(i, n2);
4952 tagNames.set(i+1, n1);
4955 newNote.setTagGuids(tagGuids);
4956 newNote.setTagNames(tagNames);
4958 // Add tag guids to note
4961 // Duplicate resources
4962 List<Resource> resList = oldNote.getResources();
4963 if (resList == null)
4964 resList = new ArrayList<Resource>();
4966 for (int i=0; i<resList.size(); i++) {
4968 while (l == prevGuid) {
4969 currentTime = new GregorianCalendar();
4970 l = new Long(currentTime.getTimeInMillis());
4973 String newResGuid = new String(Long.toString(l));
4974 resList.get(i).setNoteGuid(newGuid);
4975 resList.get(i).setGuid(newResGuid);
4976 resList.get(i).setUpdateSequenceNum(0);
4977 resList.get(i).setActive(true);
4978 conn.getNoteTable().noteResourceTable.saveNoteResource(
4979 (Resource)Global.deepCopy(resList.get(i)), true);
4981 newNote.setResources(resList);
4983 // Add note to the database
4984 conn.getNoteTable().addNote(newNote, true);
4985 NoteMetadata metaData = new NoteMetadata();
4986 NoteMetadata oldMeta = listManager.getNoteMetadata().get(oldNote.getGuid());
4987 metaData.copy(oldMeta);
4988 metaData.setGuid(newNote.getGuid());
4989 listManager.addNote(newNote, metaData);
4990 noteTableView.insertRow(newNote, metaData, true, -1);
4991 currentNoteGuid = newNote.getGuid();
4992 currentNote = newNote;
4993 refreshEvernoteNote(true);
4994 listManager.countNotebookResults(listManager.getNoteIndex());
4998 @SuppressWarnings("unused")
4999 private void allNotes() {
5000 clearAttributeFilter();
5001 clearNotebookFilter();
5002 clearSavedSearchFilter();
5005 searchField.clear();
5006 if (Global.mimicEvernoteInterface) {
5007 notebookTree.selectGuid("");
5009 notebookTreeSelection();
5010 refreshEvernoteNote(true);
5013 @SuppressWarnings("unused")
5014 private void mergeNotes() {
5015 logger.log(logger.HIGH, "Merging notes");
5018 String masterGuid = null;
5019 List<String> sources = new ArrayList<String>();
5021 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
5022 int r = noteTableView.selectionModel().selectedRows().get(i).row();
5023 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
5024 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5026 masterGuid = (String)ix.values().toArray()[0];
5028 sources.add((String)ix.values().toArray()[0]);
5031 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
5032 logger.log(logger.EXTREME, "Children count: "+sources.size());
5033 mergeNoteContents(masterGuid, sources);
5034 currentNoteGuid = masterGuid;
5035 noteIndexUpdated(false);
5036 refreshEvernoteNote(true);
5039 private void mergeNoteContents(String targetGuid, List<String> sources) {
5040 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
5041 String newContent = target.getContent();
5042 newContent = newContent.replace("</en-note>", "<br></br>");
5044 for (int i=0; i<sources.size(); i++) {
5045 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
5046 if (source.isSetTitle()) {
5047 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
5049 String sourceContent = source.getContent();
5050 logger.log(logger.EXTREME, "Merging contents into note");
5051 logger.log(logger.EXTREME, sourceContent);
5052 logger.log(logger.EXTREME, "End of content");
5053 int startOfNote = sourceContent.indexOf("<en-note>");
5054 sourceContent = sourceContent.substring(startOfNote+9);
5055 int endOfNote = sourceContent.indexOf("</en-note>");
5056 sourceContent = sourceContent.substring(0,endOfNote);
5057 newContent = newContent + sourceContent;
5058 logger.log(logger.EXTREME, "New note content");
5059 logger.log(logger.EXTREME, newContent);
5060 logger.log(logger.EXTREME, "End of content");
5061 for (int j=0; j<source.getResourcesSize(); j++) {
5062 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
5063 Resource r = source.getResources().get(j);
5064 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
5066 Calendar currentTime = new GregorianCalendar();
5067 Long l = new Long(currentTime.getTimeInMillis());
5071 while (l == prevGuid) {
5072 currentTime = new GregorianCalendar();
5073 l = new Long(currentTime.getTimeInMillis());
5075 String newResGuid = new String(Long.toString(l));
5076 newRes.setNoteGuid(targetGuid);
5077 newRes.setGuid(newResGuid);
5078 newRes.setUpdateSequenceNum(0);
5079 newRes.setActive(true);
5080 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5083 logger.log(logger.EXTREME, "Updating note");
5084 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5085 for (int i=0; i<sources.size(); i++) {
5086 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5087 listManager.deleteNote(sources.get(i));
5089 logger.log(logger.EXTREME, "Exiting merge note");
5091 // A resource within a note has had a guid change
5092 @SuppressWarnings("unused")
5093 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5094 if (oldGuid != null && !oldGuid.equals(newGuid))
5095 Global.resourceMap.put(oldGuid, newGuid);
5097 // View a thumbnail of the note
5098 public void thumbnailView() {
5100 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5101 QFile thumbnail = new QFile(thumbnailName);
5102 if (!thumbnail.exists()) {
5104 QImage img = new QImage();
5105 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5106 thumbnailViewer.setThumbnail(img);
5108 thumbnailViewer.setThumbnail(thumbnailName);
5109 if (!thumbnailViewer.isVisible())
5110 thumbnailViewer.showFullScreen();
5112 // An error happened while saving a note. Inform the user
5113 @SuppressWarnings("unused")
5114 private void saveRunnerError(String guid, String msg) {
5116 String title = "*Unknown*";
5117 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5118 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5119 title = listManager.getMasterNoteIndex().get(i).getTitle();
5120 i=listManager.getMasterNoteIndex().size();
5123 msg = tr("An error has happened while saving the note \"") +title+
5124 tr("\".\n\nThis is probably due to a document that is too complex for NixNote to process. "+
5125 "As a result, changes to the note may not be saved properly in the database."+
5126 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5127 "\nbe lost. Please review the note to recover any critical data before restarting.");
5129 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5132 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5133 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5134 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5135 // Find an idle preview object
5136 for (int i=0; i<thumbGenerators.size(); i++) {
5137 if (thumbGenerators.get(i).mutex.tryLock()) {
5138 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5139 thumbGenerators.get(i).loadContent(guid, html, zoom);
5143 if (thumbGenerators.size() >= 1) {
5144 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5148 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5149 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5150 thumbGenerators.add(preview);
5152 if (preview.mutex.tryLock()) {
5153 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5154 preview.loadContent(guid, html, zoom);
5156 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5161 //**********************************************************
5162 //**********************************************************
5163 //* Online user actions
5164 //**********************************************************
5165 //**********************************************************
5166 private void setupOnlineMenu() {
5167 if (!Global.isConnected) {
5168 menuBar.noteOnlineHistoryAction.setEnabled(false);
5169 menuBar.selectiveSyncAction.setEnabled(false);
5172 menuBar.noteOnlineHistoryAction.setEnabled(true);
5173 menuBar.selectiveSyncAction.setEnabled(true);
5176 @SuppressWarnings("unused")
5177 private void viewNoteHistory() {
5178 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5180 if (currentNote.getUpdateSequenceNum() == 0) {
5181 setMessage(tr("Note has never been synchronized."));
5182 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5186 setMessage(tr("Getting Note History"));
5188 Note currentOnlineNote = null;
5191 if (Global.isPremium())
5192 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5194 versions = new ArrayList<NoteVersionId>();
5195 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5196 } catch (EDAMUserException e) {
5197 setMessage("EDAMUserException: " +e.getMessage());
5199 } catch (EDAMSystemException e) {
5200 setMessage("EDAMSystemException: " +e.getMessage());
5202 } catch (EDAMNotFoundException e) {
5203 setMessage(tr("Note not found on server."));
5204 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5206 } catch (TException e) {
5207 setMessage("EDAMTransactionException: " +e.getMessage());
5211 // If we've gotten this far, we have a good note.
5212 if (historyWindow == null) {
5213 historyWindow = new OnlineNoteHistory(logger, conn);
5214 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5215 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5216 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5218 historyWindow.historyCombo.clear();
5220 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5221 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5223 historyWindow.setCurrent(isDirty);
5225 loadHistoryWindowContent(currentOnlineNote);
5226 historyWindow.load(versions);
5227 setMessage(tr("History retrieved"));
5229 historyWindow.exec();
5231 private Note reloadHistoryWindow(String selection) {
5233 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5234 String dateTimeFormat = new String(fmt);
5235 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5239 for (int i=0; i<versions.size(); i++) {
5240 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5241 if (versionDate.toString().equals(selection))
5245 if (index > -1 || selection.indexOf("Current") > -1) {
5246 Note historyNote = null;
5249 usn = versions.get(index).getUpdateSequenceNum();
5250 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5252 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5253 } catch (EDAMUserException e) {
5254 setMessage("EDAMUserException: " +e.getMessage());
5257 } catch (EDAMSystemException e) {
5258 setMessage("EDAMSystemException: " +e.getMessage());
5261 } catch (EDAMNotFoundException e) {
5262 setMessage("EDAMNotFoundException: " +e.getMessage());
5265 } catch (TException e) {
5266 setMessage("EDAMTransactionException: " +e.getMessage());
5272 if (historyNote != null)
5273 historyWindow.setContent(historyNote);
5279 private void loadHistoryWindowContent(Note note) {
5280 note.setUpdateSequenceNum(0);
5281 historyWindow.setContent(note);
5283 @SuppressWarnings("unused")
5284 private void restoreHistoryNoteAsNew() {
5285 setMessage(tr("Restoring as new note."));
5286 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5287 setMessage(tr("Note has been restored as a new note."));
5289 @SuppressWarnings("unused")
5290 private void restoreHistoryNote() {
5291 setMessage(tr("Restoring note."));
5292 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5293 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5296 for (int i=0; i<n.getResourcesSize(); i++) {
5297 n.getResources().get(i).setActive(true);
5298 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5300 NoteMetadata metadata = new NoteMetadata();
5301 metadata.setGuid(n.getGuid());
5302 listManager.addNote(n, metadata);
5303 conn.getNoteTable().addNote(n, true);
5304 refreshEvernoteNote(true);
5305 setMessage(tr("Note has been restored."));
5307 @SuppressWarnings("unused")
5308 private void setupSelectiveSync() {
5310 // Get a list of valid notebooks
5311 List<Notebook> notebooks = null;
5312 List<Tag> tags = null;
5313 List<LinkedNotebook> linkedNotebooks = null;
5315 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5316 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5317 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5318 } catch (EDAMUserException e) {
5319 setMessage("EDAMUserException: " +e.getMessage());
5321 } catch (EDAMSystemException e) {
5322 setMessage("EDAMSystemException: " +e.getMessage());
5324 } catch (TException e) {
5325 setMessage("EDAMTransactionException: " +e.getMessage());
5327 } catch (EDAMNotFoundException e) {
5328 setMessage("EDAMNotFoundException: " +e.getMessage());
5332 // Split up notebooks into synchronized & non-synchronized
5333 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5334 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5336 for (int i=notebooks.size()-1; i>=0; i--) {
5337 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5338 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5339 ignoredBooks.add(notebooks.get(i));
5340 j=dbIgnoredNotebooks.size();
5345 // split up tags into synchronized & non-synchronized
5346 List<Tag> ignoredTags = new ArrayList<Tag>();
5347 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5349 for (int i=tags.size()-1; i>=0; i--) {
5350 for (int j=0; j<dbIgnoredTags.size(); j++) {
5351 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5352 ignoredTags.add(tags.get(i));
5353 j=dbIgnoredTags.size();
5358 // split up linked notebooks into synchronized & non-synchronized
5359 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5360 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5361 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5362 String notebookGuid = linkedNotebooks.get(i).getGuid();
5363 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5364 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5365 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5366 j=dbIgnoredLinkedNotebooks.size();
5371 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5373 if (!ignore.okClicked())
5378 // Clear out old notebooks & add the new ones
5379 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5380 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5381 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5384 List<String> newNotebooks = new ArrayList<String>();
5385 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5386 String text = ignore.getIgnoredBookList().takeItem(i).text();
5387 for (int j=0; j<notebooks.size(); j++) {
5388 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5389 Notebook n = notebooks.get(j);
5390 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5392 newNotebooks.add(n.getGuid());
5397 // Clear out old tags & add new ones
5398 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5399 for (int i=0; i<oldIgnoreTags.size(); i++) {
5400 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5403 List<String> newTags = new ArrayList<String>();
5404 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5405 String text = ignore.getIgnoredTagList().takeItem(i).text();
5406 for (int j=0; j<tags.size(); j++) {
5407 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5408 Tag t = tags.get(j);
5409 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5410 newTags.add(t.getGuid());
5416 // Clear out old tags & add new ones
5417 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5418 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5419 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5422 List<String> newLinked = new ArrayList<String>();
5423 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5424 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5425 for (int j=0; j<linkedNotebooks.size(); j++) {
5426 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5427 LinkedNotebook t = linkedNotebooks.get(j);
5428 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5429 newLinked.add(t.getGuid());
5430 j=linkedNotebooks.size();
5435 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5441 //**********************************************************
5442 //**********************************************************
5443 //* XML Modifying methods
5444 //**********************************************************
5445 //**********************************************************
5446 // An error has happended fetching a resource. let the user know
5447 private void resourceErrorMessage() {
5451 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5452 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5453 "In a perfect world this wouldn't happen, but it has.\n" +
5454 "It is embarasing when a program like me, designed to save all your\n"+
5455 "precious data, has a problem finding data.\n\n" +
5456 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5457 "In the mean time, I'm not going to let you make changes to this note.\n" +
5458 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5459 "this note on the Evernote servers. Sorry."+
5460 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5462 browserWindow.setReadOnly(true);
5469 //**********************************************************
5470 //**********************************************************
5472 //**********************************************************
5473 //**********************************************************
5474 // We should now do a sync with Evernote
5475 private void syncTimer() {
5476 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5477 syncRunner.syncNeeded = true;
5478 syncRunner.disableUploads = Global.disableUploads;
5480 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5482 private void syncStart() {
5483 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5485 if (!syncRunning && Global.isConnected) {
5486 syncRunner.setConnected(true);
5487 syncRunner.setKeepRunning(Global.keepRunning);
5488 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5490 if (syncThreadsReady > 0) {
5491 thumbnailRunner.interrupt = true;
5492 saveNoteIndexWidth();
5493 saveNoteColumnPositions();
5494 if (syncRunner.addWork("SYNC")) {
5496 syncRunner.syncNeeded = true;
5501 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5503 @SuppressWarnings("unused")
5504 private void syncThreadComplete(Boolean refreshNeeded) {
5505 setMessage(tr("Finalizing Synchronization"));
5507 syncRunning = false;
5508 syncRunner.syncNeeded = false;
5509 synchronizeAnimationTimer.stop();
5510 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5512 if (currentNote == null) {
5513 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5515 listManager.refreshNoteMetadata();
5516 noteIndexUpdated(true);
5517 noteTableView.selectionModel().blockSignals(true);
5518 scrollToGuid(currentNoteGuid);
5519 noteTableView.selectionModel().blockSignals(false);
5520 refreshEvernoteNote(false);
5521 scrollToGuid(currentNoteGuid);
5524 // Check to see if there were any shared notebook errors
5525 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5526 String guid = syncRunner.errorSharedNotebooks.get(0);
5527 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5528 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5529 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5531 if (syncDialog.okPressed()) {
5532 if (syncDialog.doNothing.isChecked()) {
5533 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5536 if (syncDialog.deleteNotebook.isChecked()) {
5537 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5538 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5539 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5540 conn.getLinkedNotebookTable().expungeNotebook(guid, 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);;Evernote Export (*.enex);;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 String fileName = fd.selectedFiles().get(0);
5872 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5874 if (fileName.endsWith(".nnex")) {
5875 ImportData noteReader = new ImportData(conn, false);
5876 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5877 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5879 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5881 noteReader.importData(fileName);
5883 if (noteReader.lastError != 0) {
5884 setMessage(noteReader.getErrorMessage());
5885 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5890 if (fileName.endsWith(".enex")) {
5891 ImportEnex noteReader = new ImportEnex(conn, false);
5892 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5893 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5895 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5897 noteReader.importData(fileName);
5899 if (noteReader.lastError != 0) {
5900 setMessage(noteReader.getErrorMessage());
5901 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5908 listManager.loadNoteTitleColors();
5910 refreshEvernoteNote(false);
5911 setMessage(tr("Notes have been imported."));
5914 setMessage(tr("Import completed."));
5921 //**************************************************
5922 //* Duplicate a note
5923 //**************************************************
5924 @SuppressWarnings("unused")
5925 private void duplicateNote() {
5927 duplicateNote(currentNoteGuid);
5930 //**************************************************
5931 //* Action from when a user clicks Copy As URL
5932 //**************************************************
5933 @SuppressWarnings("unused")
5934 private void copyAsUrlClicked() {
5935 QClipboard clipboard = QApplication.clipboard();
5936 QMimeData mime = new QMimeData();
5938 mime.setText(currentNoteGuid);
5939 List<QUrl> urls = new ArrayList<QUrl>();
5941 // Start building the URL
5942 User user = Global.getUserInformation();
5944 // Check that we have everything we need
5945 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
5946 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
5948 if (!warning.neverSynchronize())
5951 Global.setBypassSynchronizationWarning(true);
5952 user.setShardId("s0");
5958 // Start building a list of URLs based upon the selected notes
5959 noteTableView.showColumn(Global.noteTableGuidPosition);
5961 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
5962 if (!Global.isColumnVisible("guid"))
5963 noteTableView.hideColumn(Global.noteTableGuidPosition);
5965 // Check that the note is either synchronized, or in a local notebook
5966 for (int i=0; i<selections.size(); i++) {
5968 int row = selections.get(i).row();
5969 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5970 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5971 String selectedGuid = (String)ix.values().toArray()[0];
5973 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5974 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
5975 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
5976 "new notes to a local notebook."));
5981 // Start building the URLs
5982 for (int i=0; i<selections.size(); i++) {
5984 int row = selections.get(i).row();
5985 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5986 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5987 String selectedGuid = (String)ix.values().toArray()[0];
5988 mime.setText(selectedGuid);
5992 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5993 if (selectedNote.getUpdateSequenceNum() > 0) {
5997 gid = "00000000-0000-0000-0000-000000000000";
6000 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
6002 urls.add(new QUrl(url));
6005 clipboard.setMimeData(mime);
6009 //**************************************************
6011 //**************************************************
6012 public void setupFolderImports() {
6013 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
6015 if (importKeepWatcher == null)
6016 importKeepWatcher = new QFileSystemWatcher();
6017 if (importDeleteWatcher == null) {
6018 importDeleteWatcher = new QFileSystemWatcher();
6019 for (int i=0; i<records.size(); i++) {
6020 if (!records.get(i).keep)
6021 folderImportDelete(records.get(i).folder);
6027 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
6028 for (int i=0; i<records.size(); i++) {
6029 if (records.get(i).keep)
6030 importKeepWatcher.addPath(records.get(i).folder);
6032 importDeleteWatcher.addPath(records.get(i).folder);
6035 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
6036 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
6038 // Look at the files already there so we don't import them again if a new file is created
6039 if (importedFiles == null) {
6040 importedFiles = new ArrayList<String>();
6041 for (int j=0; j<records.size(); j++) {
6042 QDir dir = new QDir(records.get(j).folder);
6043 List<QFileInfo> list = dir.entryInfoList();
6044 for (int k=0; k<list.size(); k++) {
6045 if (list.get(k).isFile())
6046 importedFiles.add(list.get(k).absoluteFilePath());
6051 public void folderImport() {
6052 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
6053 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
6055 if (!dialog.okClicked())
6058 // We have some sort of update.
6059 if (importKeepWatcher.directories().size() > 0)
6060 importKeepWatcher.removePaths(importKeepWatcher.directories());
6061 if (importDeleteWatcher.directories().size() > 0)
6062 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
6064 conn.getWatchFolderTable().expungeAll();
6065 // Start building from the table
6066 for (int i=0; i<dialog.table.rowCount(); i++) {
6067 QTableWidgetItem item = dialog.table.item(i, 0);
6068 String dir = item.text();
6069 item = dialog.table.item(i, 1);
6070 String notebook = item.text();
6071 item = dialog.table.item(i, 2);
6073 if (item.text().equalsIgnoreCase("Keep"))
6078 String guid = conn.getNotebookTable().findNotebookByName(notebook);
6079 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
6081 setupFolderImports();
6084 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
6086 String whichOS = System.getProperty("os.name");
6087 if (whichOS.contains("Windows"))
6088 dirName = dirName.replace('/','\\');
6090 FileImporter importer = new FileImporter(logger, conn);
6092 QDir dir = new QDir(dirName);
6093 List<QFileInfo> list = dir.entryInfoList();
6094 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6096 for (int i=0; i<list.size(); i++){
6098 boolean redundant = false;
6099 // Check if we've already imported this one or if it existed before
6100 for (int j=0; j<importedFiles.size(); j++) {
6101 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6106 importer.setFileInfo(list.get(i));
6107 importer.setFileName(list.get(i).absoluteFilePath());
6110 if (list.get(i).isFile() && importer.isValidType()) {
6112 if (!importer.importFile()) {
6113 // If we can't get to the file, it is probably locked. We'll try again later.
6114 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6115 importFilesKeep.add(list.get(i).absoluteFilePath());
6119 Note newNote = importer.getNote();
6120 newNote.setNotebookGuid(notebook);
6121 newNote.setTitle(dir.at(i));
6122 NoteMetadata metadata = new NoteMetadata();
6123 metadata.setDirty(true);
6124 metadata.setGuid(newNote.getGuid());
6125 listManager.addNote(newNote, metadata);
6126 conn.getNoteTable().addNote(newNote, true);
6127 noteTableView.insertRow(newNote, metadata, true, -1);
6128 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6129 listManager.countNotebookResults(listManager.getNoteIndex());
6130 importedFiles.add(list.get(i).absoluteFilePath());
6138 public void folderImportDelete(String dirName) {
6140 String whichOS = System.getProperty("os.name");
6141 if (whichOS.contains("Windows"))
6142 dirName = dirName.replace('/','\\');
6144 FileImporter importer = new FileImporter(logger, conn);
6145 QDir dir = new QDir(dirName);
6146 List<QFileInfo> list = dir.entryInfoList();
6147 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6149 for (int i=0; i<list.size(); i++){
6150 importer.setFileInfo(list.get(i));
6151 importer.setFileName(list.get(i).absoluteFilePath());
6153 if (list.get(i).isFile() && importer.isValidType()) {
6155 if (!importer.importFile()) {
6156 // If we can't get to the file, it is probably locked. We'll try again later.
6157 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6158 importFilesKeep.add(list.get(i).absoluteFilePath());
6162 Note newNote = importer.getNote();
6163 newNote.setNotebookGuid(notebook);
6164 newNote.setTitle(dir.at(i));
6165 NoteMetadata metadata = new NoteMetadata();
6166 metadata.setDirty(true);
6167 metadata.setGuid(newNote.getGuid());
6168 listManager.addNote(newNote, metadata);
6169 conn.getNoteTable().addNote(newNote, true);
6170 noteTableView.insertRow(newNote, metadata, true, -1);
6171 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6172 listManager.countNotebookResults(listManager.getNoteIndex());
6173 dir.remove(dir.at(i));
6179 //**************************************************
6181 //**************************************************
6182 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6183 logger.log(logger.HIGH, "Entering exernalFileEdited");
6185 // Strip URL prefix and base dir path
6186 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6187 String name = fileName.replace(dPath, "");
6188 int pos = name.lastIndexOf('.');
6191 guid = guid.substring(0,pos);
6193 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6195 guid = name.substring(0, pos);
6198 QFile file = new QFile(fileName);
6199 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6200 // If we can't get to the file, it is probably locked. We'll try again later.
6201 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6202 externalFiles.add(fileName);
6205 QByteArray binData = file.readAll();
6207 if (binData.size() == 0) {
6208 // If we can't get to the file, it is probably locked. We'll try again later.
6209 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6210 externalFiles.add(fileName);
6214 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6216 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6217 if (r == null || r.getData() == null || r.getData().getBody() == null)
6219 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6220 MessageDigest md = MessageDigest.getInstance("MD5");
6221 md.update(binData.toByteArray());
6222 byte[] hash = md.digest();
6223 String newHash = Global.byteArrayToHexString(hash);
6224 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6225 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6227 if (externalWindows.containsKey(r.getNoteGuid())) {
6228 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6229 r.getGuid(), oldHash, newHash);
6231 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6232 Data data = r.getData();
6233 data.setBody(binData.toByteArray());
6234 data.setBodyHash(hash);
6235 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6237 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6239 if (r.getNoteGuid().equals(currentNoteGuid)) {
6240 QWebSettings.setMaximumPagesInCache(0);
6241 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6242 refreshEvernoteNote(true);
6243 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6246 if (externalWindows.containsKey(r.getNoteGuid())) {
6247 QWebSettings.setMaximumPagesInCache(0);
6248 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6249 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6253 logger.log(logger.HIGH, "Exiting externalFielEdited");
6255 // This is a timer event that tries to save any external files that were edited. This
6256 // is only needed if we couldn't save a file earlier.
6257 public void externalFileEditedSaver() {
6258 for (int i=externalFiles.size()-1; i>=0; i--) {
6260 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6261 externalFileEdited(externalFiles.get(i));
6262 externalFiles.remove(i);
6263 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6265 for (int i=0; i<importFilesKeep.size(); i++) {
6267 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6268 folderImportKeep(importFilesKeep.get(i));
6269 importFilesKeep.remove(i);
6270 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6272 for (int i=0; i<importFilesDelete.size(); i++) {
6273 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6274 folderImportDelete(importFilesDelete.get(i));
6275 importFilesDelete.remove(i);
6282 // If an attachment on the current note was edited, we need to update the current notes's hash
6283 // Update a note content's hash. This happens if a resource is edited outside of NN
6284 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6285 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6287 for (;position>-1;) {
6288 endPos = browser.getContent().indexOf(">", position+1);
6289 String oldSegment = browser.getContent().substring(position,endPos);
6290 int hashPos = oldSegment.indexOf("hash=\"");
6291 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6292 String hash = oldSegment.substring(hashPos+6, hashEnd);
6293 if (hash.equalsIgnoreCase(oldHash)) {
6294 String newSegment = oldSegment.replace(oldHash, newHash);
6295 String content = browser.getContent().substring(0,position) +
6297 browser.getContent().substring(endPos);
6298 browser.setContent(new QByteArray(content));;
6301 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6306 //*************************************************
6307 //* Minimize to tray
6308 //*************************************************
6310 public void changeEvent(QEvent e) {
6311 if (e.type() == QEvent.Type.WindowStateChange) {
6312 if (isMinimized() && Global.showTrayIcon()) {
6314 QTimer.singleShot(10, this, "hide()");
6318 windowMaximized = true;
6320 windowMaximized = false;
6324 //*************************************************
6325 //* Check database userid & passwords
6326 //*************************************************
6327 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6328 Connection connection;
6331 Class.forName("org.h2.Driver");
6332 } catch (ClassNotFoundException e1) {
6333 e1.printStackTrace();
6338 String passwordString = null;
6339 if (cypherPassword==null || cypherPassword.trim().equals(""))
6340 passwordString = userPassword;
6342 passwordString = cypherPassword+" "+userPassword;
6343 connection = DriverManager.getConnection(url,userid,passwordString);
6344 } catch (SQLException e) {
6349 } catch (SQLException e) {
6350 e.printStackTrace();
6355 //*************************************************
6356 //* View / Hide source HTML for a note
6357 //*************************************************
6358 public void viewSource() {
6359 browserWindow.showSource(menuBar.viewSource.isChecked());
6361 //*************************************************
6362 // Block the program. This is used for things
6363 // like async web calls.
6364 //*************************************************
6365 @SuppressWarnings("unused")
6366 private void blockApplication(BrowserWindow b) {
6367 // Block all signals
6371 blockTimer = new QTimer();
6372 blockTimer.setSingleShot(true);
6373 blockTimer.setInterval(15000);
6374 blockTimer.timeout.connect(this, "unblockApplication()");
6379 @SuppressWarnings("unused")
6380 private void unblockApplication() {
6382 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6383 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6384 blockingWindow.unblockTime = -1;
6385 blockingWindow.awaitingHttpResponse = false;
6387 blockingWindow = null;
6388 blockSignals(false);