OSDN Git Service

7728f11443ac922b8d86d2ee407e2eeaf207e485
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / NeverNote.java
1 /*
2   * This file is part of NixNote/NeighborNote 
3  * Copyright 2009 Randy Baumgarte
4  * Copyright 2013 Yuki Takahashi
5  * 
6  * This file may be licensed under the terms of of the
7  * GNU General Public License Version 2 (the ``GPL'').
8  *
9  * Software distributed under the License is distributed
10  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
11  * express or implied. See the GPL for the specific language
12  * governing rights and limitations.
13  *
14  * You should have received a copy of the GPL along with this
15  * program. If not, go to http://www.gnu.org/licenses/gpl.html
16  * or write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19 */
20 package cx.fbn.nevernote;
21 import java.awt.Desktop;
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.FileNotFoundException;
25 import java.io.FileOutputStream;
26 import java.net.Authenticator;
27 import java.net.PasswordAuthentication;
28 import java.security.MessageDigest;
29 import java.security.NoSuchAlgorithmException;
30 import java.sql.Connection;
31 import java.sql.DriverManager;
32 import java.sql.SQLException;
33 import java.sql.Statement;
34 import java.text.SimpleDateFormat;
35 import java.util.ArrayList;
36 import java.util.Calendar;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.Date;
41 import java.util.GregorianCalendar;
42 import java.util.HashMap;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.SortedMap;
46 import java.util.Vector;
47
48 import org.apache.log4j.Level;
49 import org.apache.log4j.Logger;
50 import org.h2.tools.ChangeFileEncryption;
51
52 import com.evernote.edam.error.EDAMErrorCode;
53 import com.evernote.edam.error.EDAMNotFoundException;
54 import com.evernote.edam.error.EDAMSystemException;
55 import com.evernote.edam.error.EDAMUserException;
56 import com.evernote.edam.notestore.NoteFilter;
57 import com.evernote.edam.notestore.NoteVersionId;
58 import com.evernote.edam.type.Data;
59 import com.evernote.edam.type.LinkedNotebook;
60 import com.evernote.edam.type.Note;
61 import com.evernote.edam.type.NoteAttributes;
62 import com.evernote.edam.type.Notebook;
63 import com.evernote.edam.type.Publishing;
64 import com.evernote.edam.type.QueryFormat;
65 import com.evernote.edam.type.Resource;
66 import com.evernote.edam.type.SavedSearch;
67 import com.evernote.edam.type.Tag;
68 import com.evernote.edam.type.User;
69 import com.evernote.thrift.TException;
70 import com.trolltech.qt.QThread;
71 import com.trolltech.qt.core.QByteArray;
72 import com.trolltech.qt.core.QDateTime;
73 import com.trolltech.qt.core.QDir;
74 import com.trolltech.qt.core.QEvent;
75 import com.trolltech.qt.core.QFile;
76 import com.trolltech.qt.core.QFileInfo;
77 import com.trolltech.qt.core.QFileSystemWatcher;
78 import com.trolltech.qt.core.QIODevice;
79 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
80 import com.trolltech.qt.core.QLocale;
81 import com.trolltech.qt.core.QMimeData;
82 import com.trolltech.qt.core.QModelIndex;
83 import com.trolltech.qt.core.QSize;
84 import com.trolltech.qt.core.QTemporaryFile;
85 import com.trolltech.qt.core.QTextCodec;
86 import com.trolltech.qt.core.QTextStream;
87 import com.trolltech.qt.core.QThreadPool;
88 import com.trolltech.qt.core.QTimer;
89 import com.trolltech.qt.core.QTranslator;
90 import com.trolltech.qt.core.QUrl;
91 import com.trolltech.qt.core.Qt;
92 import com.trolltech.qt.core.Qt.BGMode;
93 import com.trolltech.qt.core.Qt.DockWidgetArea;
94 import com.trolltech.qt.core.Qt.ItemDataRole;
95 import com.trolltech.qt.core.Qt.KeyboardModifier;
96 import com.trolltech.qt.core.Qt.MouseButton;
97 import com.trolltech.qt.core.Qt.SortOrder;
98 import com.trolltech.qt.core.Qt.WidgetAttribute;
99 import com.trolltech.qt.gui.QAbstractItemView;
100 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
101 import com.trolltech.qt.gui.QAction;
102 import com.trolltech.qt.gui.QApplication;
103 import com.trolltech.qt.gui.QClipboard;
104 import com.trolltech.qt.gui.QCloseEvent;
105 import com.trolltech.qt.gui.QColor;
106 import com.trolltech.qt.gui.QComboBox;
107 import com.trolltech.qt.gui.QCursor;
108 import com.trolltech.qt.gui.QDesktopServices;
109 import com.trolltech.qt.gui.QDialog;
110 import com.trolltech.qt.gui.QFileDialog;
111 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
112 import com.trolltech.qt.gui.QFileDialog.FileMode;
113 import com.trolltech.qt.gui.QGridLayout;
114 import com.trolltech.qt.gui.QHBoxLayout;
115 import com.trolltech.qt.gui.QIcon;
116 import com.trolltech.qt.gui.QImage;
117 import com.trolltech.qt.gui.QKeySequence;
118 import com.trolltech.qt.gui.QLabel;
119 import com.trolltech.qt.gui.QListWidgetItem;
120 import com.trolltech.qt.gui.QMainWindow;
121 import com.trolltech.qt.gui.QMenu;
122 import com.trolltech.qt.gui.QMessageBox;
123 import com.trolltech.qt.gui.QMessageBox.StandardButton;
124 import com.trolltech.qt.gui.QPainter;
125 import com.trolltech.qt.gui.QPalette.ColorRole;
126 import com.trolltech.qt.gui.QPixmap;
127 import com.trolltech.qt.gui.QPrintDialog;
128 import com.trolltech.qt.gui.QPrinter;
129 import com.trolltech.qt.gui.QShortcut;
130 import com.trolltech.qt.gui.QSizePolicy;
131 import com.trolltech.qt.gui.QSizePolicy.Policy;
132 import com.trolltech.qt.gui.QSpinBox;
133 import com.trolltech.qt.gui.QSplashScreen;
134 import com.trolltech.qt.gui.QSplitter;
135 import com.trolltech.qt.gui.QStatusBar;
136 import com.trolltech.qt.gui.QSystemTrayIcon;
137 import com.trolltech.qt.gui.QTableWidgetItem;
138 import com.trolltech.qt.gui.QTextEdit;
139 import com.trolltech.qt.gui.QToolBar;
140 import com.trolltech.qt.gui.QTreeWidgetItem;
141 import com.trolltech.qt.network.QNetworkAccessManager;
142 import com.trolltech.qt.network.QNetworkProxy;
143 import com.trolltech.qt.network.QNetworkProxy.ProxyType;
144 import com.trolltech.qt.network.QNetworkReply;
145 import com.trolltech.qt.network.QNetworkRequest;
146 import com.trolltech.qt.webkit.QWebPage.WebAction;
147 import com.trolltech.qt.webkit.QWebSettings;
148
149 import cx.fbn.nevernote.clipboard.ClipBoardObserver;
150 import cx.fbn.nevernote.config.InitializationException;
151 import cx.fbn.nevernote.config.StartupConfig;
152 import cx.fbn.nevernote.dialog.AccountDialog;
153 import cx.fbn.nevernote.dialog.ConfigDialog;
154 import cx.fbn.nevernote.dialog.DBEncryptDialog;
155 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
156 import cx.fbn.nevernote.dialog.DatabaseStatus;
157 import cx.fbn.nevernote.dialog.FindDialog;
158 import cx.fbn.nevernote.dialog.IgnoreSync;
159 import cx.fbn.nevernote.dialog.LogFileDialog;
160 import cx.fbn.nevernote.dialog.NotebookArchive;
161 import cx.fbn.nevernote.dialog.NotebookEdit;
162 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
163 import cx.fbn.nevernote.dialog.PublishNotebook;
164 import cx.fbn.nevernote.dialog.SavedSearchEdit;
165 import cx.fbn.nevernote.dialog.SetIcon;
166 import cx.fbn.nevernote.dialog.ShareNotebook;
167 import cx.fbn.nevernote.dialog.SharedNotebookSyncError;
168 import cx.fbn.nevernote.dialog.StackNotebook;
169 import cx.fbn.nevernote.dialog.SynchronizationRequiredWarning;
170 import cx.fbn.nevernote.dialog.TagEdit;
171 import cx.fbn.nevernote.dialog.TagMerge;
172 import cx.fbn.nevernote.dialog.ThumbnailViewer;
173 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
174 import cx.fbn.nevernote.dialog.WatchFolder;
175 import cx.fbn.nevernote.evernote.NoteMetadata;
176 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
177 import cx.fbn.nevernote.filters.FilterEditorTags;
178 import cx.fbn.nevernote.gui.AttributeTreeWidget;
179 import cx.fbn.nevernote.gui.BrowserWindow;
180 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
181 import cx.fbn.nevernote.gui.ExternalBrowse;
182 import cx.fbn.nevernote.gui.MainMenuBar;
183 import cx.fbn.nevernote.gui.NotebookTreeWidget;
184 import cx.fbn.nevernote.gui.RensoNoteList;
185 import cx.fbn.nevernote.gui.RensoNoteListDock;
186 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
187 import cx.fbn.nevernote.gui.SearchPanel;
188 import cx.fbn.nevernote.gui.TabBrowse;
189 import cx.fbn.nevernote.gui.TabBrowserWidget;
190 import cx.fbn.nevernote.gui.TableView;
191 import cx.fbn.nevernote.gui.TagTreeWidget;
192 import cx.fbn.nevernote.gui.Thumbnailer;
193 import cx.fbn.nevernote.gui.TrashTreeWidget;
194 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
195 import cx.fbn.nevernote.oauth.OAuthTokenizer;
196 import cx.fbn.nevernote.oauth.OAuthWindow;
197 import cx.fbn.nevernote.sql.DatabaseConnection;
198 import cx.fbn.nevernote.sql.WatchFolderRecord;
199 import cx.fbn.nevernote.threads.IndexRunner;
200 import cx.fbn.nevernote.threads.SyncRunner;
201 import cx.fbn.nevernote.threads.ThumbnailRunner;
202 import cx.fbn.nevernote.utilities.AESEncrypter;
203 import cx.fbn.nevernote.utilities.ApplicationLogger;
204 import cx.fbn.nevernote.utilities.FileImporter;
205 import cx.fbn.nevernote.utilities.FileUtils;
206 import cx.fbn.nevernote.utilities.ListManager;
207 import cx.fbn.nevernote.utilities.SyncTimes;
208 import cx.fbn.nevernote.xml.ExportData;
209 import cx.fbn.nevernote.xml.ImportData;
210 import cx.fbn.nevernote.xml.ImportEnex;
211 import cx.fbn.nevernote.xml.NoteFormatter;
212
213
214 public class NeverNote extends QMainWindow{
215         
216         QStatusBar                              statusBar;                                      // Application status bar
217         
218         DatabaseConnection              conn;
219         
220         MainMenuBar                             menuBar;                                        // Main menu bar
221         FindDialog                              find;                                           // Text search in note dialog
222         List<String>                    emitLog;                                        // Messages displayed in the status bar;
223         QSystemTrayIcon                 trayIcon;                                       // little tray icon
224         QMenu                                   trayMenu;                                       // System tray menu
225         QAction                                 trayExitAction;                         // Exit the application
226         QAction                                 trayShowAction;                         // toggle the show/hide action          
227         QAction                                 trayAddNoteAction;                      // Add a note from the system tray
228         QNetworkAccessManager   versionChecker;                         // Used when checking for new versions
229         
230     NotebookTreeWidget          notebookTree;                           // List of notebooks
231     AttributeTreeWidget         attributeTree;                          // List of note attributes
232     TagTreeWidget                       tagTree;                                        // list of user created tags
233     SavedSearchTreeWidget       savedSearchTree;                        // list of saved searches
234     TrashTreeWidget                     trashTree;                                      // Trashcan
235     TableView                           noteTableView;                          //      List of notes (the widget).
236
237     public BrowserWindow        browserWindow;                          // Window containing browser & labels
238     public QToolBar             toolBar;                                        // The tool bar under the menu
239     QComboBox                           searchField;                            // search filter bar on the toolbar;
240     QShortcut                           searchShortcut;                         // Shortcut to search bar
241     boolean                                     searchPerformed = false;        // Search was done?
242     QuotaProgressBar            quotaBar;                                       // The current quota usage
243     
244     ApplicationLogger           logger;
245     List<String>                        selectedNotebookGUIDs;          // List of notebook GUIDs
246     List<String>                        selectedTagGUIDs;                       // List of selected tag GUIDs
247     List<String>                        selectedNoteGUIDs;                      // List of selected notes
248     String                                      selectedSavedSearchGUID;        // Currently selected saved searches
249     private final HashMap<String, ExternalBrowse>       externalWindows;        // Notes being edited by an external window;
250     
251     NoteFilter                          filter;                                         // Note filter
252     String                                      currentNoteGuid;                        // GUID of the current note 
253     Note                                        currentNote;                            // The currently viewed note
254     HashMap<Integer, Boolean>   noteDirty;                              // Has the note been changed?
255     HashMap<Integer, Boolean>   inkNote;                // if this is an ink note, it is read only
256     HashMap<Integer, Boolean>   readOnly;                               // Is this note read-only?
257         
258   
259     ListManager                         listManager;                                    // DB runnable task
260     
261     List<QTemporaryFile>        tempFiles;                                      // Array of temporary files;
262     
263     QTimer                                      indexTimer;                                     // timer to start the index thread
264     IndexRunner                         indexRunner;                            // thread to index notes
265     QThread                                     indexThread;
266     
267     QTimer                                      syncTimer;                                      // Sync on an interval
268     QTimer                                      syncDelayTimer;                         // Sync delay to free up database
269     SyncRunner                          syncRunner;                                     // thread to do a sync.
270     QThread                                     syncThread;                                     // Thread which talks to evernote
271     ThumbnailRunner                     thumbnailRunner;                        // Runner for thumbnail thread
272     QThread                                     thumbnailThread;                        // Thread that generates pretty pictures
273     QTimer                                      saveTimer;                                      // Timer to save note contents
274     
275     QTimer                                      authTimer;                                      // Refresh authentication
276     QTimer                                      externalFileSaveTimer;          // Save files altered externally
277     QTimer                                      thumbnailTimer;                         // Wakeup & scan for thumbnails
278     QTimer                                      debugTimer;
279     List<String>                        externalFiles;                          // External files to save later
280     List<String>                        importFilesKeep;                        // Auto-import files to save later
281     List<String>                        importFilesDelete;                      // Auto-import files to save later
282     
283     int                                         indexTime;                                      // how often to try and index
284     boolean                                     indexRunning;                           // Is indexing running?
285     boolean                                     indexDisabled;                          // Is indexing disabled?
286     
287     int                                         syncThreadsReady;                       // number of sync threads that are free
288     int                                         syncTime;                                       // Sync interval
289     boolean                                     syncRunning;                            // Is sync running?
290     boolean                                     automaticSync;                          // do sync automatically?
291     QTreeWidgetItem                     attributeTreeSelected;
292
293     QAction                             prevButton;                                     // Go to the previous item viewed
294     QAction                             nextButton;                                     // Go to the next item in the history
295     QAction                             downButton;                                     // Go to the next item in the list
296     QAction                             upButton;                                       // Go to the prev. item in the list;
297     QAction                             synchronizeButton;                      // Synchronize with Evernote
298     QAction                             allNotesButton;                         // Reset & view all notes
299     QTimer                              synchronizeAnimationTimer;      // Timer to change animation button
300     int                                 synchronizeIconAngle;           // Used to rotate sync icon
301     QAction                     printButton;                            // Print Button
302     QAction                             tagButton;                                      // Tag edit button
303     QAction                             attributeButton;                        // Attribute information button
304     QAction                     emailButton;                            // Email button
305     QAction                     deleteButton;                           // Delete button
306     QAction                             newButton;                                      // new Note Button;
307     QSpinBox                    zoomSpinner;                            // Zoom zoom
308     QAction                             searchClearButton;                      // Clear the search field
309     
310     SearchPanel                 searchLayout;                           // Widget to hold search field, zoom, & quota
311     
312     QSplitter                   mainLeftRightSplitter;          // main splitter for left/right side
313     QSplitter                   leftSplitter1;                          // first left hand splitter
314     QSplitter                   browserIndexSplitter;           // splitter between note index & note text
315     
316     QFileSystemWatcher  importKeepWatcher;                      // Watch & keep auto-import
317     QFileSystemWatcher  importDeleteWatcher;            // Watch & Delete auto-import
318     List<String>                importedFiles;                          // History of imported files (so we don't import twice)
319     
320     OnlineNoteHistory   historyWindow;                          // online history window 
321     List<NoteVersionId> versions;                                       // history versions
322     
323     QTimer                              threadMonitorTimer;                     // Timer to watch threads.
324     int                                 dbThreadDeadCount=0;            // number of consecutive dead times for the db thread
325     int                                 syncThreadDeadCount=0;          // number of consecutive dead times for the sync thread
326     int                                 indexThreadDeadCount=0;         // number of consecutive dead times for the index thread
327     int                                 notebookThreadDeadCount=0;      // number of consecutive dead times for the notebook thread
328     int                                 tagDeadCount=0;                         // number of consecutive dead times for the tag thread
329     int                                 trashDeadCount=0;                       // number of consecutive dead times for the trash thread
330     int                                 saveThreadDeadCount=0;          // number of consecutive dead times for the save thread
331     int                                 enRelatedNotesThreadDeadCount=0;        // number of consecutive dead times for the EvernoteRelatedNotes Thread
332     boolean                             disableTagThreadCheck=false;
333     boolean                             disableNotebookThreadCheck=false;
334     boolean                             disableTrashThreadCheck=false;
335     boolean                             disableSaveThreadCheck=false;
336     boolean                             disableSyncThreadCheck=false;
337     boolean                             disableIndexThreadCheck=false;
338     boolean                             disableENRelatedNotesThreadCheck=false;
339     
340     HashMap<String, String>             noteCache;                      // Cash of note content 
341     HashMap<String, Boolean>    readOnlyCache;          // List of cashe notes that are read-only
342     HashMap<String, Boolean>    inkNoteCache;           // List of cache notes that are ink notes 
343         HashMap<Integer, ArrayList<String>> historyGuids;  // タブごとの以前見たノートのGUID
344         HashMap<Integer, Integer> historyPosition; // Position within the viewed items
345         HashMap<Integer, Boolean> fromHistory; // Is this from the history queue?
346         
347     String                              trashNoteGuid;                          // Guid to restore / set into or out of trash to save position
348     List<Thumbnailer>   thumbGenerators;                                // generate preview image
349     ThumbnailViewer             thumbnailViewer;                        // View preview thumbnail; 
350     boolean                             encryptOnShutdown;                      // should I encrypt when I close?
351     boolean                             decryptOnShutdown;                      // should I decrypt on shutdown;
352     String                              encryptCipher;                          // What cipher should I use?
353     //Signal0                   minimizeToTray;
354     boolean                             windowMaximized = false;        // Keep track of the window state for restores
355     List<String>                pdfReadyQueue;                          // Queue of PDFs that are ready to be rendered.
356     List<QPixmap>               syncIcons;                                      // Array of icons used in sync animation
357     private boolean             closeAction = false;            // Used to say when to close or when to minimize
358     private static Logger log = Logger.getLogger(NeverNote.class); 
359     private String              saveLastPath;                           // last path we used
360     private final QTimer                messageTimer;                           // Timer to clear the status message.
361     private QTimer              blockTimer;
362     BrowserWindow               blockingWindow;
363     
364         private final TabBrowserWidget tabBrowser;                              // ブラウザウィンドウをタブ化
365         private final HashMap<Integer, TabBrowse> tabWindows;   // タブウィンドウ
366         private final RensoNoteListDock rensoNoteListDock;              // 連想ノートリストドックウィジェット
367         ClipBoardObserver cbObserver;
368         String rensoNotePressedItemGuid;
369         
370     String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
371         
372         
373     //***************************************************************
374     //***************************************************************
375     //** Constructor & main entry point
376     //***************************************************************
377     //***************************************************************
378     // Application Constructor  
379         @SuppressWarnings("static-access")
380         public NeverNote(DatabaseConnection dbConn)  {
381                 cbObserver = new ClipBoardObserver();
382                 
383                 conn = dbConn;          
384                 if (conn.getConnection() == null) {
385                         String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
386                                 "is accessing the database or NeighborNote is already running.\n\n" +
387                                 "Please end any other process or shutdown the other NeighborNote before starting.\n\nExiting program."));
388                         
389             QMessageBox.critical(null, tr("Database Connection Error") ,msg);
390                         System.exit(16);
391                 }
392                 setObjectName("mainWindow");
393 //              thread().setPriority(Thread.MAX_PRIORITY);
394                 
395                 logger = new ApplicationLogger("nevernote.log");
396                 logger.log(logger.HIGH, "Starting Application");
397                 
398                 decryptOnShutdown = false;
399                 encryptOnShutdown = false;
400                 conn.checkDatabaseVersion();
401                 
402                 
403                 
404                 // Start building the invalid XML tables
405                 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
406                 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
407                 
408                 for (int i=0; i<elements.size(); i++) {
409                         Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
410                 }
411                 
412                 logger.log(logger.EXTREME, "Starting GUI build");
413
414                 QTranslator nevernoteTranslator = new QTranslator();
415                 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("neighbornote_" + QLocale.system().name() + ".qm"));
416                 QApplication.instance().installTranslator(nevernoteTranslator);
417
418                 Global.originalPalette = QApplication.palette();
419                 QApplication.setStyle(Global.getStyle());
420                 if (Global.useStandardPalette())
421                         QApplication.setPalette(QApplication.style().standardPalette());
422         setWindowTitle(tr("NeighborNote"));
423
424         mainLeftRightSplitter = new QSplitter();
425                 mainLeftRightSplitter.setOrientation(Qt.Orientation.Horizontal);
426                 
427         setCentralWidget(mainLeftRightSplitter);
428         leftSplitter1 = new QSplitter();
429         leftSplitter1.setOrientation(Qt.Orientation.Vertical);
430                 
431         browserIndexSplitter = new QSplitter();
432         browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
433         
434         //* Setup threads & thread timers
435 //        int indexRunnerCount = Global.getIndexThreads();
436 //       indexRunnerCount = 1;
437         QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount);     // increase max thread count
438
439                 logger.log(logger.EXTREME, "Building list manager");
440         listManager = new ListManager(conn, logger);
441         
442                 logger.log(logger.EXTREME, "Building index runners & timers");
443                 indexRunner = new IndexRunner("indexRunner.log",
444                                 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(),
445                                 Global.getResourceDatabaseUrl(),
446                                 Global.getBehaviorDatabaseUrl(), Global.getDatabaseUserid(),
447                                 Global.getDatabaseUserPassword(), Global.cipherPassword);
448                 
449                 indexThread = new QThread(indexRunner, "Index Thread");
450         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
451         indexRunner.indexImageRecognition = Global.indexImageRecognition();
452 //        indexRunner.indexNoteBody = Global.indexNoteBody();
453 //        indexRunner.indexNoteTitle = Global.indexNoteTitle();
454 //        indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
455                 indexThread.start();
456                 
457         synchronizeAnimationTimer = new QTimer();
458         synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
459         
460                 indexTimer = new QTimer();
461                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
462                 indexTimer.start(indexTime);  // Start indexing timer
463                 indexTimer.timeout.connect(this, "indexTimer()");
464                 indexDisabled = false;
465                 indexRunning = false;
466                                 
467                 logger.log(logger.EXTREME, "Setting sync thread & timers");
468                 syncThreadsReady=1;
469                 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(),
470                                 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
471                                 Global.getBehaviorDatabaseUrl(), Global.getDatabaseUserid(),
472                                 Global.getDatabaseUserPassword(), Global.cipherPassword);
473                 
474                 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
475                 syncTimer = new QTimer();
476                 syncTimer.timeout.connect(this, "syncTimer()");
477         syncRunner.status.message.connect(this, "setMessage(String)");
478         syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
479         syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
480         syncRunner.limitSignal.rateLimitReached.connect(this, "informRateLimit(Integer)");
481         syncRunning = false;    
482                 if (syncTime > 0) {
483                         automaticSync = true;
484                         syncTimer.start(syncTime*60*1000);
485                 } else {
486                         automaticSync = false;
487                         syncTimer.stop();
488                 }
489                 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
490                 syncThread = new QThread(syncRunner, "Synchronization Thread");
491                 syncThread.start();
492                 
493                 
494                 logger.log(logger.EXTREME, "Starting thumnail thread");
495                 pdfReadyQueue = new ArrayList<String>();
496                 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
497                                 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(),
498                                 Global.getResourceDatabaseUrl(),
499                                 Global.getBehaviorDatabaseUrl(), Global.getDatabaseUserid(),
500                                 Global.getDatabaseUserPassword(), Global.cipherPassword);
501                 
502                 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
503                 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
504                 thumbnailThread.start();
505                 thumbGenerators = new ArrayList<Thumbnailer>();
506                 thumbnailTimer = new QTimer();
507                 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
508                 thumbnailTimer();
509                 thumbnailTimer.setInterval(500*1000);  // Thumbnail every minute
510                 thumbnailTimer.start();
511                 
512 //              debugTimer = new QTimer();
513 //              debugTimer.timeout.connect(this, "debugDirty()");
514 //              debugTimer.start(1000*60);
515                 
516                 logger.log(logger.EXTREME, "Starting authentication timer");
517                 authTimer = new QTimer();
518                 authTimer.timeout.connect(this, "authTimer()");
519                 authTimer.start(1000*60*15);
520                 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
521                 
522                 logger.log(logger.EXTREME, "Setting save note timer");
523                 saveTimer = new QTimer();
524                 saveTimer.timeout.connect(this, "saveNote()");
525                 if (Global.getAutoSaveInterval() > 0) {
526                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval()); 
527                         saveTimer.start();
528                 }
529                 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
530                 
531                 logger.log(logger.EXTREME, "Starting external file monitor timer");
532                 externalFileSaveTimer = new QTimer();
533                 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
534                 externalFileSaveTimer.setInterval(1000*5);   // save every 5 seconds;
535                 externalFiles = new ArrayList<String>();
536                 importFilesDelete = new ArrayList<String>();
537                 importFilesKeep = new ArrayList<String>();
538                 externalFileSaveTimer.start();
539                 
540         notebookTree = new NotebookTreeWidget(conn);
541         attributeTree = new AttributeTreeWidget();
542         tagTree = new TagTreeWidget(conn);
543         savedSearchTree = new SavedSearchTreeWidget();
544         trashTree = new TrashTreeWidget();
545                 noteTableView = new TableView(logger, listManager, this);     
546         
547         searchField = new QComboBox();
548         searchField.setObjectName("searchField");
549         //setStyleSheet("QComboBox#searchField { background-color: yellow }");
550         searchField.setEditable(true);
551         searchField.activatedIndex.connect(this, "searchFieldChanged()");
552         searchField.setDuplicatesEnabled(false);
553         searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
554         searchShortcut = new QShortcut(this);
555         setupShortcut(searchShortcut, "Focus_Search");
556         searchShortcut.activated.connect(this, "focusSearch()");
557         
558         quotaBar = new QuotaProgressBar();
559         // Setup the zoom
560         zoomSpinner = new QSpinBox();
561         zoomSpinner.setMinimum(10);
562         zoomSpinner.setMaximum(1000);
563         zoomSpinner.setAccelerated(true);
564         zoomSpinner.setSingleStep(10);
565         zoomSpinner.setValue(100);
566         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
567         
568         searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
569         
570         
571         QGridLayout leftGrid = new QGridLayout();
572         leftSplitter1.setContentsMargins(5, 0, 0, 7);
573         leftSplitter1.setLayout(leftGrid);
574         leftGrid.addWidget(searchLayout,1,1);
575         leftGrid.addWidget(tagTree,2,1);
576         leftGrid.addWidget(attributeTree,3,1);
577         leftGrid.addWidget(savedSearchTree,4,1);
578         leftGrid.addWidget(trashTree,5, 1);
579         
580         // Setup the browser window
581         noteCache = new HashMap<String,String>();
582         readOnlyCache = new HashMap<String, Boolean>();
583         inkNoteCache = new HashMap<String, Boolean>();
584         browserWindow = new BrowserWindow(conn, cbObserver);
585
586                 // 下から移動してきた。
587                 historyGuids = new HashMap<Integer, ArrayList<String>>();
588                 historyPosition = new HashMap<Integer, Integer>();
589                 fromHistory = new HashMap<Integer, Boolean>();
590                 
591                 // タブブラウザ作成
592                 tabWindows = new HashMap<Integer, TabBrowse>();
593                 tabBrowser = new TabBrowserWidget(this);
594                 tabBrowser.setStyleSheet("QTabBar::tab{width:150px;}");
595                 tabBrowser.setMovable(true);
596                 tabBrowser.setTabsClosable(true);
597                 TabBrowse tab = new TabBrowse(conn, tabBrowser, cbObserver);
598                 browserWindow = tab.getBrowserWindow();
599                 int index = tabBrowser.addNewTab(tab, "");
600                 tabWindows.put(index, tab);
601                 tabBrowser.currentChanged.connect(this, "tabWindowChanged(int)");
602                 tabBrowser.tabCloseRequested.connect(this, "tabWindowClosing(int)");
603                 
604                 noteDirty = new HashMap<Integer, Boolean>();
605                 noteDirty.put(index, false);
606                 
607                 inkNote = new HashMap<Integer, Boolean>();
608                 readOnly = new HashMap<Integer, Boolean>();
609
610                 // 履歴記録のハッシュマップを初期化
611                 historyGuids.put(index, new ArrayList<String>());
612                 historyPosition.put(index, 0);
613                 fromHistory.put(index, false);
614                 
615         mainLeftRightSplitter.addWidget(leftSplitter1);
616         mainLeftRightSplitter.addWidget(browserIndexSplitter);
617         
618                 // 連想ノートリストをセットアップ
619         rensoNoteListDock = new RensoNoteListDock(conn, this, syncRunner, iconPath, tr("Renso Note List"));
620                 addDockWidget(DockWidgetArea.RightDockWidgetArea, rensoNoteListDock);
621
622                 if (Global.getListView() == Global.View_List_Wide) {
623                         browserIndexSplitter.addWidget(noteTableView);
624                         browserIndexSplitter.addWidget(tabBrowser);
625                 } else {
626                         mainLeftRightSplitter.addWidget(noteTableView);
627                         mainLeftRightSplitter.addWidget(tabBrowser);
628                 }
629         
630         // Setup the thumbnail viewer
631         thumbnailViewer = new ThumbnailViewer();
632         thumbnailViewer.upArrow.connect(this, "upAction()");
633         thumbnailViewer.downArrow.connect(this, "downAction()");
634         thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
635         thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
636         
637         //Setup external browser manager
638         externalWindows = new HashMap<String, ExternalBrowse>();
639
640         listManager.loadNotesIndex();
641         initializeNotebookTree();
642         initializeTagTree();
643         initializeSavedSearchTree();
644         attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
645         attributeTreeSelected = null;
646         initializeNoteTable();    
647
648                 selectedNoteGUIDs = new ArrayList<String>();
649                 statusBar = new QStatusBar();
650                 setStatusBar(statusBar);
651                 menuBar = new MainMenuBar(this);
652                 emitLog = new ArrayList<String>();
653                 
654                 tagTree.setDeleteAction(menuBar.tagDeleteAction);
655                 tagTree.setMergeAction(menuBar.tagMergeAction);
656                 tagTree.setEditAction(menuBar.tagEditAction);
657                 tagTree.setAddAction(menuBar.tagAddAction);
658                 tagTree.setIconAction(menuBar.tagIconAction);
659                 tagTree.setVisible(Global.isWindowVisible("tagTree"));
660                 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
661                 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
662                 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
663                 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
664                 
665                 if (!Global.isWindowVisible("zoom")) {
666                         searchLayout.hideZoom();
667                         menuBar.hideZoom.setChecked(false);
668                 } 
669         
670                 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
671                 notebookTree.setEditAction(menuBar.notebookEditAction);
672                 notebookTree.setAddAction(menuBar.notebookAddAction);
673                 notebookTree.setIconAction(menuBar.notebookIconAction);
674                 notebookTree.setStackAction(menuBar.notebookStackAction);
675                 notebookTree.setPublishAction(menuBar.notebookPublishAction);
676                 notebookTree.setShareAction(menuBar.notebookShareAction);
677                 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
678                 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
679                 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
680             notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
681                 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
682
683                 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
684                 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
685                 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
686                 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
687                 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
688                 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
689                 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
690                 
691                 // noteTableViewに新しいタブで開くを追加
692                 noteTableView.setOpenNewTabAction(menuBar.noteOpenNewTab);
693                         
694                 noteTableView.setAddAction(menuBar.noteAdd);
695                 
696                 // noteTableViewに新しいタブでノート追加を追加
697                 noteTableView.setAddNoteNewTabAction(menuBar.noteAddNewTab);
698                 
699                 noteTableView.setDeleteAction(menuBar.noteDelete);
700                 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
701                 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
702                 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
703                 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
704                 noteTableView.noteSignal.notePinned.connect(this, "notePinned()");
705                 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
706                 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
707                 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
708                 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
709                 
710                 quotaBar.setMouseClickAction(menuBar.accountAction);
711                 
712                 trashTree.load();
713         trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
714                 trashTree.setEmptyAction(menuBar.emptyTrashAction);
715                 trashTree.setVisible(Global.isWindowVisible("trashTree"));
716                 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
717                 trashTree.updateCounts(listManager.getTrashCount());
718                 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
719                 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
720
721                 noteTableView.setVisible(Global.isWindowVisible("noteList"));
722                 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
723                 
724                 if (!Global.isWindowVisible("editorButtonBar")) {
725                         menuBar.showEditorBar.setChecked(false);
726                         toggleEditorButtonBar();
727                 }
728                 
729                 if (!Global.isWindowVisible("leftPanel"))
730                         menuBar.hideLeftSide.setChecked(true);
731                 
732                 if (Global.isWindowVisible("noteInformation")) {
733                         menuBar.noteAttributes.setChecked(true);
734                         toggleNoteInformation();
735                 }
736                 
737                 quotaBar.setVisible(Global.isWindowVisible("quota"));
738                 // IFIXED quotaBar.isVisible() → Global.isWindowVisible("quota")
739                 // なぜかquotaBar.isVisible()が常にfalseを返すようなので修正
740                 if (!Global.isWindowVisible("quota"))
741                         menuBar.hideQuota.setChecked(false);
742                 
743                 searchField.setVisible(Global.isWindowVisible("searchField"));
744                 // IFIXED !searchField.isVisible() → !Global.isWindowVisible("searchField")
745                 // なぜかsearchField.isVisible()が常にfalseを返すようなので修正
746                 if (!Global.isWindowVisible("searchField"))
747                         menuBar.hideSearch.setChecked(false);
748                 
749                 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
750                         searchLayout.hide();
751                 
752                 setMenuBar(menuBar);
753                 setupToolBar();
754                 find = new FindDialog();
755                 find.getOkButton().clicked.connect(this, "doFindText()");
756                 
757                 // Setup the tray icon menu bar
758                 trayShowAction = new QAction(tr("Show/Hide"), this);
759                 trayExitAction = new QAction(tr("Exit"), this);
760                 trayAddNoteAction = new QAction(tr("Add Note"), this);
761                 
762                 trayExitAction.triggered.connect(this, "closeNeverNote()");
763                 trayAddNoteAction.triggered.connect(this, "addNote()");
764                 trayShowAction.triggered.connect(this, "trayToggleVisible()");
765                 
766                 trayMenu = new QMenu(this);
767                 trayMenu.addAction(trayAddNoteAction);
768                 trayMenu.addAction(trayShowAction);
769                 trayMenu.addAction(trayExitAction);
770                 
771                 
772                 trayIcon = new QSystemTrayIcon(this);
773                 trayIcon.setToolTip(tr("NeighborNote"));
774                 trayIcon.setContextMenu(trayMenu);
775                 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
776
777                 currentNoteGuid="";
778                 currentNoteGuid = Global.getLastViewedNoteGuid();
779                 if (currentNoteGuid.equals(""))
780                         currentNote = new Note();
781                 
782                 /* 上に移動したのでここには不要
783                  * historyGuids = new ArrayList<String>();
784                  * historyPosition = 0;
785                  * fromHistory = false;
786                  */
787                 
788                 if (!currentNoteGuid.trim().equals("")) {
789                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
790                 }
791                 
792                 noteIndexUpdated(true);
793                 showColumns();
794                 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
795                 if (menuBar.showEditorBar.isChecked())
796                 showEditorButtons(browserWindow);
797                 tagIndexUpdated(true);
798                 savedSearchIndexUpdated();
799                 notebookIndexUpdated();
800                 updateQuotaBar();
801         setupSyncSignalListeners();        
802         setupBrowserSignalListeners();
803         setupIndexListeners();
804               
805         
806         tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
807         tagTree.showAllTags(true);
808
809                 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
810                 if (QSystemTrayIcon.isSystemTrayAvailable()) {
811                         setWindowIcon(appIcon);
812                         trayIcon.setIcon(appIcon);
813                         if (Global.showTrayIcon() || Global.minimizeOnClose())
814                                 trayIcon.show();
815                         else
816                                 trayIcon.hide();
817                 }
818         
819         scrollToGuid(currentNoteGuid);
820         if (Global.automaticLogin()) {
821                 remoteConnect();
822                 if (Global.isConnected)
823                         syncTimer();
824         }
825         setupFolderImports();
826         
827         loadStyleSheet();
828         restoreWindowState(true);
829         
830         if (Global.mimicEvernoteInterface) {
831                 notebookTree.selectGuid("");
832         }
833         
834         threadMonitorTimer = new QTimer();
835         threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
836         threadMonitorTimer.start(1000*10);  // Check for threads every 10 seconds;              
837         
838                 // IFIXED 恐らく不要なのでコメントアウト
839                 /*
840                  * historyGuids.add(currentNoteGuid);
841                  * historyPosition = 1;
842                  */
843         
844         menuBar.blockSignals(true);
845         menuBar.narrowListView.blockSignals(true);
846         menuBar.wideListView.blockSignals(true);
847         if (Global.getListView() == Global.View_List_Narrow) { 
848                 menuBar.narrowListView.setChecked(true);
849         }
850         else{ 
851                 menuBar.wideListView.setChecked(true);
852         }
853         menuBar.blockSignals(false);
854         menuBar.narrowListView.blockSignals(false);
855         menuBar.wideListView.blockSignals(false);
856         
857                 // IFIXED 上に同じコードがあるのでコメントアウト
858                 /*
859                  * if (Global.getListView() == Global.View_List_Wide) {
860                  * browserIndexSplitter.addWidget(noteTableView);
861                  * browserIndexSplitter.addWidget(tabBrowser);
862                  * browserIndexSplitter.addWidget(browserWindow); } else {
863                  * mainLeftRightSplitter.addWidget(noteTableView);
864                  * mainLeftRightSplitter.addWidget(tabBrowser);
865                  * mainLeftRightSplitter.addWidget(browserWindow); }
866                  */
867         
868                 messageTimer = new QTimer();
869                 messageTimer.timeout.connect(this, "clearMessage()");
870                 messageTimer.setInterval(1000*15);
871                 clearMessage();
872         
873         int sortCol = Global.getSortColumn();
874                 int sortOrder = Global.getSortOrder();
875                 noteTableView.proxyModel.blocked = true;
876                 // We sort the table twice to fix a bug.  For some reaosn the table won't sort properly if it is in narrow
877                 // list view and sorted descending on the date  created.  By sorting it twice it forces the proper sort.  Ugly.
878                 if (sortCol == 0 && sortOrder == 1 && Global.getListView() == Global.View_List_Narrow) 
879                         noteTableView.sortByColumn(sortCol, SortOrder.resolve(0));   
880                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
881                 noteTableView.proxyModel.blocked = false;
882                 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
883                 
884                 // Set the startup notebook
885         String defaultNotebook = Global.getStartupNotebook();
886         if (!defaultNotebook.equals("AllNotebooks") && !defaultNotebook.equals("")) {
887                 for (int k=0; k<listManager.getNotebookIndex().size(); k++) {
888                         if (listManager.getNotebookIndex().get(k).isDefaultNotebook()) {
889                                 notebookTree.clearSelection();
890                                 notebookTree.selectGuid(listManager.getNotebookIndex().get(k).getGuid());
891                                 notebookTree.selectionSignal.emit();
892                         }
893                 }
894         }
895                 
896                 if (Global.checkVersionUpgrade()) {
897                         checkForUpdates();
898                 }
899                 
900                 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
901                         menuBar.noteAddNewTab.setEnabled(false);
902                 }
903         }
904         
905         
906         public void debugDirty() {
907                 List<Note> dirty = conn.getNoteTable().getDirty();
908                 logger.log(logger.LOW, "------ Dirty Notes List Begin ------");
909                 for (int i=0; i<dirty.size(); i++) {
910                         logger.log(logger.LOW, "GUID: " +dirty.get(i).getGuid() + " Title:" + dirty.get(i).getTitle());
911                 }
912                 logger.log(logger.LOW, "------ Dirty Notes List End ------");
913         }
914                 
915         // Main entry point
916         public static void main(String[] args) {
917                 log.setLevel(Level.FATAL);
918                 QApplication.initialize(args);
919                 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
920                 QSplashScreen splash = new QSplashScreen(pixmap);
921                 boolean showSplash;
922                 
923                 DatabaseConnection dbConn;
924
925         try {
926             initializeGlobalSettings(args);
927
928             showSplash = Global.isWindowVisible("SplashScreen");
929             if (showSplash)
930                 splash.show();
931
932             dbConn = setupDatabaseConnection();
933
934             // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
935             Global.getFileManager().purgeResDirectory(true);
936
937         } catch (InitializationException e) {
938             // Fatal
939             e.printStackTrace();
940             QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
941             return;
942         }
943         
944                 // Setup proxy crap
945                 String proxyUrl = Global.getProxyValue("url");
946                 String proxyPort = Global.getProxyValue("port");
947                 String proxyUserid = Global.getProxyValue("userid");
948                 String proxyPassword = Global.getProxyValue("password");
949                 boolean proxySet = false;
950                 QNetworkProxy proxy = new QNetworkProxy();
951                 proxy.setType(ProxyType.HttpProxy);
952                 if (!proxyUrl.trim().equals("")) {
953                         System.out.println("Proxy URL found: " +proxyUrl);
954                         proxySet = true;
955                         proxy.setHostName(proxyUrl);
956                 }
957                 if (!proxyPort.trim().equals("")) {
958                         System.out.println("Proxy Port found: " +proxyPort);
959                         proxySet = true;
960                         proxy.setPort(Integer.parseInt(proxyPort));
961                 }
962                 if (!proxyUserid.trim().equals("")) {
963                         System.out.println("Proxy Userid found: " +proxyUserid);
964                         proxySet = true;
965                         proxy.setUser(proxyUserid);
966                 }
967                 if (!proxyPassword.trim().equals("")) {
968                         System.out.println("Proxy URL found: " +proxyPassword);
969                         proxySet = true;
970                         proxy.setPassword(proxyPassword);
971                 }
972                 if (proxySet) {
973                         QNetworkProxy.setApplicationProxy(proxy);
974                 }
975                         
976
977         NeverNote application = new NeverNote(dbConn);
978                 if (Global.syncOnly) {
979                         System.out.println("Performing synchronization only.");
980                         application.remoteConnect();
981                         if (Global.isConnected) {
982                                 application.syncRunner.syncNeeded = true;
983                                 application.syncRunner.addWork("SYNC");
984                                 application.syncRunner.addWork("STOP");
985                                 while(!application.syncRunner.isIdle());
986                                 application.closeNeverNote();
987                         }
988                         return;
989                 }
990
991                 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
992                 if (Global.startMinimized()) 
993                         application.showMinimized();
994                 else {
995                         if (Global.wasWindowMaximized())
996                                 application.showMaximized();
997                         else
998                                 application.show();
999                 }
1000                 
1001                 if (showSplash)
1002                         splash.finish(application);
1003                 QApplication.exec();
1004                 System.out.println("Goodbye.");
1005                 QApplication.exit();
1006         }
1007
1008     /**
1009      * Open the internal database, or create if not present
1010      *
1011      * @throws InitializationException when opening the database fails, e.g. because another process has it locked
1012      */
1013     private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
1014         ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
1015         
1016         File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
1017         File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
1018                 // IFIXED resourceDatabaseNameになっていたので修正
1019                 File fi = Global.getFileManager().getDbDirFile(Global.indexDatabaseName + ".h2.db");
1020                 File fb = Global.getFileManager().getDbDirFile(Global.behaviorDatabaseName + ".h2.db");
1021                                 
1022                 if (!f.exists())
1023                         Global.setDatabaseUrl("");
1024                 if (!fr.exists())
1025                         Global.setResourceDatabaseUrl("");              
1026                 if (!fi.exists())
1027                         Global.setIndexDatabaseUrl(""); 
1028                 if (!fb.exists())
1029                         Global.setBehaviorDatabaseUrl("");
1030         
1031         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
1032             boolean goodCheck = false;
1033             while (!goodCheck) {
1034                 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
1035                 dialog.exec();
1036                 if (!dialog.okPressed())
1037                     System.exit(0);
1038                 Global.cipherPassword = dialog.getPassword();
1039                 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
1040                         Global.getDatabaseUserPassword(), Global.cipherPassword);
1041             }
1042         }
1043         DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), 
1044                         Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(), Global.getBehaviorDatabaseUrl(),
1045                         Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
1046        return dbConn;
1047     }
1048     
1049     // Encrypt the database upon shutdown
1050     private void encryptOnShutdown() {
1051         String dbPath= Global.getFileManager().getDbDirPath("");
1052         try {
1053                 
1054                 Statement st = conn.getConnection().createStatement();  
1055                 st.execute("shutdown");
1056                 st = conn.getResourceConnection().createStatement();
1057                 st.execute("shutdown");
1058                 st = conn.getIndexConnection().createStatement();
1059                 st.execute("shutdown");
1060                 st = conn.getBehaviorConnection().createStatement();
1061                 st.execute("shutdown");
1062                 
1063                 if (QMessageBox.question(this, tr("Are you sure"), 
1064                                 tr("Are you sure you wish to encrypt the database?"),
1065                                 QMessageBox.StandardButton.Yes, 
1066                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
1067                         ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
1068                         ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
1069                         ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
1070                         ChangeFileEncryption.execute(dbPath, "Behavior", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
1071                         
1072                         Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
1073                         Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
1074                         Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
1075                                 Global.setBehaviorDatabaseUrl(Global.getBehaviorDatabaseUrl() + ";CIPHER=" + encryptCipher);
1076
1077                         QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
1078                 }
1079         } catch (SQLException e) {
1080                         e.printStackTrace();
1081                 }       
1082     }
1083     
1084     // Decrypt the database upon shutdown
1085     private void decryptOnShutdown() {
1086         String dbPath= Global.getFileManager().getDbDirPath("");
1087         String dbName = "NeverNote";
1088         try {
1089                 Statement st = conn.getConnection().createStatement();  
1090                 st.execute("shutdown");
1091                 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
1092                         encryptCipher = "AES";
1093                 else
1094                         encryptCipher = "XTEA";
1095                 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure", 
1096                                 "Are you sure you wish to decrypt the database?"),
1097                                 QMessageBox.StandardButton.Yes, 
1098                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
1099
1100                         ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
1101                         Global.setDatabaseUrl("");
1102                         Global.setResourceDatabaseUrl("");
1103                         Global.setIndexDatabaseUrl("");
1104                         QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
1105                 }
1106                 } catch (SQLException e) {
1107                         e.printStackTrace();
1108                 }       
1109     }
1110     /**
1111      * Encrypt/Decrypt the local database
1112      **/
1113     public void doDatabaseEncrypt() {
1114         // The database is not currently encrypted
1115         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
1116                 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
1117                                 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
1118                                 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
1119                                 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
1120                                 "Do you wish to proceed?"),
1121                                 QMessageBox.StandardButton.Yes, 
1122                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1123                                 return;
1124                 }
1125                 DBEncryptDialog dialog = new DBEncryptDialog();
1126                 dialog.exec();
1127                 if (dialog.okPressed()) {
1128                         Global.cipherPassword = dialog.getPassword();
1129                         encryptOnShutdown  = true;
1130                         encryptCipher = dialog.getEncryptionMethod();
1131                 }
1132         } else {
1133             DBEncryptDialog dialog = new DBEncryptDialog();
1134             dialog.setWindowTitle(tr("Database Decryption"));
1135             dialog.hideEncryption();
1136             dialog.exec();
1137             if (dialog.okPressed()) {
1138                 if (!dialog.getPassword().equals(Global.cipherPassword)) {
1139                         QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
1140                         return;
1141                 }
1142                 decryptOnShutdown  = true;
1143                 encryptCipher = "";
1144             }
1145         }
1146         return;
1147     }
1148
1149         private static void initializeGlobalSettings(String[] args) throws InitializationException {
1150                 StartupConfig   startupConfig = new StartupConfig();
1151
1152         for (String arg : args) {
1153             String lower = arg.toLowerCase();
1154             if (lower.startsWith("--name="))
1155                startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
1156             if (lower.startsWith("--home="))
1157                startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
1158             if (lower.startsWith("--disable-viewing"))
1159                startupConfig.setDisableViewing(true);
1160             if (lower.startsWith("--sync-only=true"))
1161                 startupConfig.setSyncOnly(true);
1162         }
1163         Global.setup(startupConfig);
1164         
1165     }
1166
1167     // Exit point
1168         @Override
1169         public void closeEvent(QCloseEvent event) {     
1170                 if (Global.minimizeOnClose() && !closeAction) {
1171                         event.ignore();
1172                         hide();
1173                         return;
1174                 }
1175                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
1176                 waitCursor(true);
1177                 
1178                 if (currentNote != null & browserWindow != null) {
1179                         if (currentNote.getTitle() != null && browserWindow != null
1180                                         && !currentNote.getTitle().equals(browserWindow.getTitle()))
1181                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(),
1182                                                 browserWindow.getTitle());
1183                 }
1184                 
1185                 saveNote();
1186                 setMessage(tr("Beginning shutdown."));
1187                 
1188                 // Close down external windows
1189                 Collection<ExternalBrowse> windows = externalWindows.values();
1190                 Iterator<ExternalBrowse> iterator = windows.iterator();
1191                 while (iterator.hasNext()) {
1192                         ExternalBrowse browser = iterator.next();
1193                         browser.windowClosing.disconnect();
1194                         browser.close();
1195                 }
1196                 
1197                 // タブブラウザに対してクローズ処理を行う
1198                 Collection<TabBrowse> win = tabWindows.values();
1199                 Iterator<TabBrowse> it = win.iterator();
1200                 tabBrowser.currentChanged.disconnect();
1201                 tabBrowser.tabCloseRequested.disconnect();
1202                 while (it.hasNext()) {
1203                         TabBrowse browser = it.next();
1204                         browser.close();
1205                 }
1206                 
1207                 externalFileEditedSaver();
1208                 if (Global.isConnected && Global.synchronizeOnClose()) {
1209                         setMessage(tr("Performing synchronization before closing."));
1210                         syncRunner.syncNeeded = true;
1211                         syncRunner.addWork("SYNC");
1212                 } else {
1213                         syncRunner.keepRunning = false;
1214                 }
1215                 syncRunner.addWork("STOP");
1216                 setMessage("Closing Program.");
1217                 threadMonitorTimer.stop();
1218
1219                 thumbnailRunner.addWork("STOP");
1220                 indexRunner.addWork("STOP");
1221                 saveNote();
1222                 listManager.stop();
1223                 saveWindowState();
1224                 
1225                 // 連想ノートリストのEvernote関連ノート取得スレッドを終了
1226                 rensoNoteListDock.getRensoNoteList().stopThread();
1227
1228                 if (tempFiles != null)
1229                         tempFiles.clear();
1230
1231                 browserWindow.noteSignal.tagsChanged.disconnect();
1232                 browserWindow.noteSignal.titleChanged.disconnect();
1233                 browserWindow.noteSignal.noteChanged.disconnect();
1234                 browserWindow.noteSignal.notebookChanged.disconnect();
1235                 browserWindow.noteSignal.createdDateChanged.disconnect();
1236                 browserWindow.noteSignal.alteredDateChanged.disconnect();
1237                 syncRunner.searchSignal.listChanged.disconnect();
1238                 syncRunner.tagSignal.listChanged.disconnect();
1239         syncRunner.notebookSignal.listChanged.disconnect();
1240         syncRunner.noteIndexSignal.listChanged.disconnect();
1241
1242                 if (isVisible())
1243                         Global.saveWindowVisible("toolBar", toolBar.isVisible());
1244                 saveNoteColumnPositions();
1245                 saveNoteIndexWidth();
1246                 
1247                 int width = notebookTree.columnWidth(0);
1248                 Global.setColumnWidth("notebookTreeName", width);
1249                 width = tagTree.columnWidth(0);
1250                 Global.setColumnWidth("tagTreeName", width);
1251                 
1252                 Global.saveWindowMaximized(isMaximized());
1253                 Global.saveCurrentNoteGuid(currentNoteGuid);
1254                         
1255                 int sortCol = noteTableView.proxyModel.sortColumn();
1256                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1257                 Global.setSortColumn(sortCol);
1258                 Global.setSortOrder(sortOrder);
1259                 
1260                 hide();
1261                 trayIcon.hide();
1262                 Global.keepRunning = false;
1263                 try {
1264                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1265                         if (indexRunner.thread().isAlive())
1266                                 indexRunner.thread().join(50);
1267                         if (!indexRunner.thread().isAlive())
1268                                 logger.log(logger.MEDIUM, "Index thread has stopped");
1269                         else {
1270                                 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1271                                 indexRunner.thread().interrupt();
1272                         }
1273                 } catch (InterruptedException e1) {
1274                         e1.printStackTrace();
1275                 }
1276                 
1277                 if (!syncRunner.thread().isAlive()) {
1278                         logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1279                         if (syncRunner.thread().isAlive()) {
1280                                 System.out.println(tr("Synchronizing.  Please be patient."));
1281                                 for(;syncRunner.thread().isAlive();) {
1282                                         try {
1283                                                 wait(10);
1284                                         } catch (InterruptedException e) {
1285                                                 e.printStackTrace();
1286                                         }
1287                                 }
1288                         }
1289                         logger.log(logger.MEDIUM, "Sync thread has stopped");
1290                 }
1291
1292                 if (encryptOnShutdown) {
1293                         encryptOnShutdown();
1294                 }
1295                 if (decryptOnShutdown) {
1296                         decryptOnShutdown();
1297                 }
1298                 try {
1299                         Global.getFileManager().purgeResDirectory(false);
1300                 } catch (InitializationException e) {
1301                         System.out.println(tr("Empty res directory purge failed"));
1302                         e.printStackTrace();
1303                 }
1304                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1305         }
1306
1307
1308         private void closeNeverNote() {
1309                 closeAction = true;
1310                 close();
1311         }
1312         public void setMessage(String s) {
1313                 if (logger != null) 
1314                         logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1315                 else
1316                         System.out.println("*** ERROR *** " +s);
1317                 
1318                 if (statusBar != null) {
1319                         statusBar.show();
1320                         if (logger != null) 
1321                                 logger.log(logger.HIGH, "Message: " +s);
1322                         statusBar.showMessage(s);
1323                         if (emitLog != null)
1324                                 emitLog.add(s);
1325                 
1326                         if (messageTimer != null) {
1327                                 messageTimer.stop();
1328                                 messageTimer.setSingleShot(true);
1329                                 messageTimer.start();
1330                         }
1331                 }
1332                         
1333                 if (logger != null) 
1334                         logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1335         }
1336         
1337         private void clearMessage() {
1338                 statusBar.clearMessage();
1339                 statusBar.hide();
1340         }
1341                 
1342         private void waitCursor(boolean wait) {
1343                 if (wait) {
1344                         if (QApplication.overrideCursor() == null)
1345                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1346                 }
1347                 else {
1348                         if (QApplication.overrideCursor() != null)
1349                                 QApplication.restoreOverrideCursor();
1350                         else
1351                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.ArrowCursor));
1352                 }
1353                 listManager.refreshCounters();
1354         }
1355         
1356         private void setupIndexListeners() {
1357 //              indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1358 //              indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1359                 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1360                 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1361         }
1362         private void setupSyncSignalListeners() {
1363                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1364         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1365         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1366         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1367         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1368         
1369                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1370                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1371                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1372                 
1373                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1374                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1375                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1376                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1377                 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1378                 
1379                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1380         }
1381         
1382         private void setupBrowserSignalListeners() {
1383                 setupBrowserWindowListeners(browserWindow, true);
1384         }
1385
1386         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1387                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1388                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1389             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1390             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1391             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1392             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1393             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1394             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1395             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1396             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1397             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1398             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1399             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1400             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1401         browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1402         browser.unblockApplication.connect(this, "unblockApplication()");
1403             if (master) browser.focusLost.connect(this, "saveNote()");
1404             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1405             browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1406         }
1407
1408         //**************************************************
1409         //* Setup shortcuts
1410         //**************************************************
1411         private void setupShortcut(QShortcut action, String text) {
1412                 if (!Global.shortcutKeys.containsAction(text))
1413                         return;
1414                 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1415         }
1416         
1417         //***************************************************************
1418         //***************************************************************
1419         //* Settings and look & feel
1420         //***************************************************************
1421         //***************************************************************
1422         @SuppressWarnings("unused")
1423         private void settings() {
1424                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1425
1426                 saveNoteColumnPositions();
1427                 saveNoteIndexWidth();
1428                 showColumns();
1429         ConfigDialog settings = new ConfigDialog(this, conn);
1430         String dateFormat = Global.getDateFormat();
1431         String timeFormat = Global.getTimeFormat();
1432         
1433                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1434                 indexTimer.start(indexTime);  // reset indexing timer
1435         
1436         settings.exec();
1437         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1438 //        indexRunner.indexNoteBody = Global.indexNoteBody();
1439 //        indexRunner.indexNoteTitle = Global.indexNoteTitle();
1440 //        indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1441         indexRunner.indexImageRecognition = Global.indexImageRecognition();
1442         if (Global.showTrayIcon() || Global.minimizeOnClose())
1443                 trayIcon.show();
1444         else
1445                 trayIcon.hide();
1446         showColumns();
1447         if (menuBar.showEditorBar.isChecked()){
1448                 for(int i = 0; i < tabBrowser.count(); i++){
1449                         BrowserWindow browser = ((TabBrowse) tabBrowser.widget(i)).getBrowserWindow();
1450                         showEditorButtons(browser);
1451                 }
1452                 
1453         }
1454         
1455         // Reset the save timer
1456         if (Global.getAutoSaveInterval() > 0)
1457                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1458         else
1459                 saveTimer.stop();
1460         
1461         
1462         // Set special reloads
1463         if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1464                 conn.executeSql("Delete from LinkedNotebook");
1465                 conn.executeSql("delete from SharedNotebook");
1466                 conn.executeSql("Delete from Notebook where linked=true");
1467                 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1468                 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1469         }
1470
1471         // Reload user data
1472         noteCache.clear();
1473         readOnlyCache.clear();
1474         inkNoteCache.clear();
1475         noteIndexUpdated(true);
1476                 
1477         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1478         }
1479         // Restore things to the way they were
1480         private void restoreWindowState(boolean mainWindow) {
1481                 // We need to name things or this doesn't work.
1482                 setObjectName("NeverNote");
1483         restoreState(Global.restoreState(objectName()));
1484                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1485                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1486                 leftSplitter1.setObjectName("leftSplitter1");
1487                 rensoNoteListDock.setObjectName("rensoNoteListDock");
1488                 
1489                 // Restore the actual positions.
1490                 if (mainWindow)
1491                         restoreGeometry(Global.restoreGeometry(objectName()));
1492         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1493         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1494         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1495         rensoNoteListDock.restoreGeometry(Global.restoreGeometry(rensoNoteListDock.objectName()));
1496        
1497         }
1498         // Save window positions for the next start
1499         private void saveWindowState() {
1500                 Global.saveGeometry(objectName(), saveGeometry());
1501                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1502                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1503                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1504                 Global.saveState(objectName(), saveState());
1505                 Global.saveGeometry(rensoNoteListDock.objectName(), rensoNoteListDock.saveGeometry());
1506         }    
1507         // Load the style sheet
1508         private void loadStyleSheet() {
1509                 String styleSheetName = "default.qss";
1510                 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1511                                 styleSheetName = "default-cleanlooks.qss";
1512                 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1513                 QFile file = new QFile(fileName);
1514                 
1515                 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1516                 if (!file.exists()) {
1517                         fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1518                         file = new QFile(fileName);
1519                 }
1520                 file.open(OpenModeFlag.ReadOnly);
1521                 String styleSheet = file.readAll().toString();
1522                 file.close();
1523                 setStyleSheet(styleSheet);
1524         }
1525         // Save column positions for the next time
1526         private void saveNoteColumnPositions() {
1527                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1528                 Global.setColumnPosition("noteTableCreationPosition", position);
1529                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1530                 Global.setColumnPosition("noteTableTagPosition", position);
1531                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1532                 Global.setColumnPosition("noteTableNotebookPosition", position);
1533                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1534                 Global.setColumnPosition("noteTableChangedPosition", position);
1535                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1536                 Global.setColumnPosition("noteTableAuthorPosition", position);
1537                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1538                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1539                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1540                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1541                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1542                 Global.setColumnPosition("noteTableTitlePosition", position);
1543                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1544                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1545                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1546                 Global.setColumnPosition("noteTableGuidPosition", position);
1547                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1548                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1549                 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1550                 Global.setColumnPosition("noteTablePinnedPosition", position);
1551
1552         }
1553         // Save column widths for the next time
1554         private void saveNoteIndexWidth() {
1555                 int width;
1556         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1557         Global.setColumnWidth("noteTableCreationPosition", width);
1558                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1559                 Global.setColumnWidth("noteTableChangedPosition", width);
1560                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1561                 Global.setColumnWidth("noteTableGuidPosition", width);
1562                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1563                 Global.setColumnWidth("noteTableNotebookPosition", width);
1564                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1565                 Global.setColumnWidth("noteTableTagPosition", width);
1566                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1567                 Global.setColumnWidth("noteTableTitlePosition", width);
1568                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1569                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1570                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1571                 Global.setColumnWidth("noteTableAuthorPosition", width);
1572                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1573                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1574                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1575                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1576                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1577                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1578                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1579                 Global.setColumnWidth("noteTableGuidPosition", width);
1580                 width = noteTableView.getColumnWidth(Global.noteTablePinnedPosition);
1581                 Global.setColumnWidth("noteTablePinnedPosition", width);
1582         }
1583         
1584         @SuppressWarnings("unused")
1585         private void toggleSearchWindow() {
1586                 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1587         searchLayout.toggleSearchField();
1588         menuBar.hideSearch.setChecked(searchField.isVisible());
1589         Global.saveWindowVisible("searchField", searchField.isVisible());
1590         logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1591     }   
1592         @SuppressWarnings("unused")
1593         private void toggleQuotaWindow() {
1594                 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1595         searchLayout.toggleQuotaBar();
1596         menuBar.hideQuota.setChecked(quotaBar.isVisible());
1597         Global.saveWindowVisible("quota", quotaBar.isVisible());
1598         logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1599     }   
1600         @SuppressWarnings("unused")
1601         private void toggleZoomWindow() {
1602                 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1603         searchLayout.toggleZoom();
1604         menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1605         Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1606         logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1607     }   
1608         
1609         
1610         
1611     //***************************************************************
1612     //***************************************************************
1613     //** These functions deal with Notebook menu items
1614     //***************************************************************
1615     //***************************************************************
1616     // Setup the tree containing the user's notebooks.
1617     private void initializeNotebookTree() {       
1618         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1619 //      notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1620         notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1621         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1622         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1623     }   
1624     // Listener when a notebook is selected
1625         private void notebookTreeSelection() {
1626                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1627                 noteTableView.proxyModel.blocked = true;
1628                 
1629                 clearTrashFilter();
1630                 clearAttributeFilter();
1631                 clearSavedSearchFilter();
1632                 if (Global.mimicEvernoteInterface) {
1633                         clearTagFilter();
1634                         //searchField.clear();
1635                         searchField.clearEditText();
1636                 }
1637                 menuBar.noteRestoreAction.setVisible(false);            
1638         menuBar.notebookEditAction.setEnabled(true);
1639         menuBar.notebookDeleteAction.setEnabled(true);
1640         menuBar.notebookPublishAction.setEnabled(true);
1641         menuBar.notebookShareAction.setEnabled(true);
1642         menuBar.notebookIconAction.setEnabled(true);
1643         menuBar.notebookStackAction.setEnabled(true);
1644         
1645                 // ゴミ箱から元の画面に戻す。連想ノートリストをONに。
1646                 if (!rensoNoteListDock.isEnabled()) {
1647                         rensoNoteListDock.setEnabled(true);
1648                 }
1649                 
1650         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1651         selectedNotebookGUIDs.clear();
1652                 String guid = "";
1653                 String stackName = "";
1654                 if (selections.size() > 0) {
1655                 guid = (selections.get(0).text(2));
1656                 stackName = selections.get(0).text(0);
1657         }
1658                 if (!Global.mimicEvernoteInterface) {
1659                         // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1660                         if (selections.size()==0) {
1661                                 selectedNotebookGUIDs.clear();
1662                                 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1663                                         selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1664                                 }
1665                                 menuBar.notebookEditAction.setEnabled(false);
1666                                 menuBar.notebookDeleteAction.setEnabled(false);
1667                                 menuBar.notebookStackAction.setEnabled(false);
1668                                 menuBar.notebookIconAction.setEnabled(false);
1669                         }
1670                 }
1671         if (!guid.equals("") && !guid.equals("STACK")) {
1672                 selectedNotebookGUIDs.add(guid);
1673                 menuBar.notebookIconAction.setEnabled(true);
1674         } else {
1675                 menuBar.notebookIconAction.setEnabled(true);
1676                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1677                                 Notebook book = listManager.getNotebookIndex().get(j);
1678                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1679                                         selectedNotebookGUIDs.add(book.getGuid());
1680                         }
1681         }
1682         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1683         listManager.loadNotesIndex();
1684         noteIndexUpdated(false);
1685         refreshEvernoteNote(true);
1686         listManager.refreshCounters = true;
1687         listManager.refreshCounters();
1688         if (selectedNotebookGUIDs.size() == 1) {
1689                 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1690                 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1691                 if (col != -1) {
1692                         noteTableView.proxyModel.blocked = true;
1693                         if (order == 1)
1694                                 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1695                         else
1696                                 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1697                 }
1698         }
1699         noteTableView.proxyModel.blocked = false;
1700                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1701
1702     }
1703     private void clearNotebookFilter() {
1704         notebookTree.blockSignals(true);
1705         notebookTree.clearSelection();
1706                 menuBar.noteRestoreAction.setVisible(false);
1707         menuBar.notebookEditAction.setEnabled(false);
1708         menuBar.notebookDeleteAction.setEnabled(false);
1709         selectedNotebookGUIDs.clear();
1710         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1711         notebookTree.blockSignals(false);
1712     }
1713         // Triggered when the notebook DB has been updated
1714         private void notebookIndexUpdated() {
1715                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1716         
1717                 // Get the possible icons
1718                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1719         notebookTree.setIcons(icons);
1720         
1721         if (selectedNotebookGUIDs == null)
1722                         selectedNotebookGUIDs = new ArrayList<String>();
1723                 List<Notebook> books = conn.getNotebookTable().getAll();
1724                 for (int i=books.size()-1; i>=0; i--) {
1725                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1726                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1727                                         books.remove(i);
1728                                         j=listManager.getArchiveNotebookIndex().size();
1729                                 }
1730                         }
1731                 }
1732                 
1733                 
1734                 listManager.countNotebookResults(listManager.getNoteIndex());
1735                 notebookTree.blockSignals(true);
1736         notebookTree.load(books, listManager.getLocalNotebooks());
1737         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1738                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1739                 if (!found)
1740                         selectedNotebookGUIDs.remove(i);
1741         }
1742         listManager.refreshCounters = true;
1743         listManager.refreshCounters();
1744         notebookTree.blockSignals(false);
1745         
1746                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1747     }
1748     // Show/Hide note information
1749         @SuppressWarnings("unused")
1750         private void toggleNotebookWindow() {
1751                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1752                 searchLayout.toggleNotebook();
1753         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1754         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1755         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1756     }   
1757         // Add a new notebook
1758         @SuppressWarnings("unused")
1759         private void addNotebook() {
1760                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1761                 NotebookEdit edit = new NotebookEdit();
1762                 edit.setNotebooks(listManager.getNotebookIndex());
1763                 edit.exec();
1764         
1765                 if (!edit.okPressed())
1766                         return;
1767         
1768                 Calendar currentTime = new GregorianCalendar();
1769                 Long l = new Long(currentTime.getTimeInMillis());
1770                 String randint = new String(Long.toString(l));
1771         
1772                 Notebook newBook = new Notebook();
1773                 newBook.setUpdateSequenceNum(0);
1774                 newBook.setGuid(randint);
1775                 newBook.setName(edit.getNotebook());
1776                 newBook.setServiceCreated(new Date().getTime());
1777                 newBook.setServiceUpdated(new Date().getTime());
1778                 newBook.setDefaultNotebook(false);
1779                 newBook.setPublished(false);
1780                 
1781                 listManager.getNotebookIndex().add(newBook);
1782                 if (edit.isLocal())
1783                         listManager.getLocalNotebooks().add(newBook.getGuid());
1784                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1785                 notebookIndexUpdated();
1786                 listManager.countNotebookResults(listManager.getNoteIndex());
1787 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1788                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1789         }
1790         // Edit an existing notebook
1791         @SuppressWarnings("unused")
1792         private void stackNotebook() {
1793                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1794                 StackNotebook edit = new StackNotebook();
1795                 
1796                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1797                 QTreeWidgetItem currentSelection;
1798                 for (int i=0; i<selections.size(); i++) {
1799                         currentSelection = selections.get(0);
1800                         String guid = currentSelection.text(2);
1801                         if (guid.equalsIgnoreCase("")) {
1802                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1803                                  return;
1804                         }
1805                         if (guid.equalsIgnoreCase("STACK")) {
1806                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1807                                  return;
1808                         }
1809                 }
1810
1811                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1812
1813                 
1814                 edit.exec();
1815         
1816                 if (!edit.okPressed())
1817                         return;
1818         
1819                 String stack = edit.getStackName();
1820                 
1821                 for (int i=0; i<selections.size(); i++) {
1822                         currentSelection = selections.get(i);
1823                         String guid = currentSelection.text(2);
1824                         listManager.updateNotebookStack(guid, stack);
1825                 }
1826                 notebookIndexUpdated();
1827                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1828         }
1829         // Edit an existing notebook
1830         @SuppressWarnings("unused")
1831         private void editNotebook() {
1832                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1833                 NotebookEdit edit = new NotebookEdit();
1834                 
1835                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1836                 QTreeWidgetItem currentSelection;
1837                 currentSelection = selections.get(0);
1838                 edit.setNotebook(currentSelection.text(0));
1839                 
1840                 String guid = currentSelection.text(2);
1841                 if (!guid.equalsIgnoreCase("STACK")) {
1842                         edit.setTitle(tr("Edit Notebook"));
1843                         edit.setNotebooks(listManager.getNotebookIndex());
1844                         edit.setLocalCheckboxEnabled(false);
1845                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1846                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1847                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1848                                         i=listManager.getNotebookIndex().size();
1849                                 }
1850                         }
1851                 } else {
1852                         edit.setTitle(tr("Edit Stack"));
1853                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1854                         edit.hideLocalCheckbox();
1855                         edit.hideDefaultCheckbox();
1856                 }
1857                 
1858                 edit.exec();
1859         
1860                 if (!edit.okPressed())
1861                         return;
1862         
1863                 
1864                 if (guid.equalsIgnoreCase("STACK")) {
1865                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1866                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1867                                 if (listManager.getNotebookIndex().get(j).getStack() != null && 
1868                                         listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1869                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1870                         }
1871                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1872                         currentSelection.setText(0, edit.getNotebook());
1873                         return;
1874                 }
1875                 
1876                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1877                 currentSelection.setText(0, edit.getNotebook());
1878                 
1879                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1880                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1881                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1882                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1883                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1884                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1885                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1886                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1887                                 }
1888                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1889                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1890                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1891                                         linkedNotebook.setShareName(edit.getNotebook());
1892                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1893                                 }
1894                                 i=listManager.getNotebookIndex().size();
1895                         }
1896                 }
1897                 
1898                 // Build a list of non-closed notebooks
1899                 List<Notebook> nbooks = new ArrayList<Notebook>();
1900                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1901                         boolean found=false;
1902                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1903                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1904                                         found = true;
1905                         }
1906                         if (!found)
1907                                 nbooks.add(listManager.getNotebookIndex().get(i));
1908                 }
1909                 
1910                 
1911                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1912                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1913                 browserWindow.setNotebookList(filteredBooks);
1914                 Iterator<String> set = externalWindows.keySet().iterator();
1915                 while(set.hasNext())
1916                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1917                 
1918                 Iterator<Integer>it = tabWindows.keySet().iterator();
1919                 while (it.hasNext()) {
1920                         tabWindows.get(it.next()).getBrowserWindow()
1921                                         .setNotebookList(filteredBooks);
1922                 }
1923                 
1924                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1925         }
1926         // Publish a notebook
1927         @SuppressWarnings("unused")
1928         private void publishNotebook() {
1929                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1930                 QTreeWidgetItem currentSelection;
1931                 currentSelection = selections.get(0);
1932                 String guid = currentSelection.text(2);
1933
1934                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1935                         return;
1936                 
1937                 Notebook n = null;
1938                 int position = 0;
1939                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1940                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1941                                 n = listManager.getNotebookIndex().get(i);
1942                                 position = i;
1943                                 i = listManager.getNotebookIndex().size();
1944                         }
1945                 }
1946                 if (n == null)
1947                         return;
1948                 
1949                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1950                 publish.exec();
1951                 
1952                 if (!publish.okClicked()) 
1953                         return;
1954                 
1955                 Publishing p = publish.getPublishing();
1956                 boolean isPublished = !publish.isStopPressed();
1957                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1958                 n.setPublished(isPublished);
1959                 n.setPublishing(p);
1960                 listManager.getNotebookIndex().set(position, n);
1961                 notebookIndexUpdated();
1962         }
1963         // Publish a notebook
1964         @SuppressWarnings("unused")
1965         private void shareNotebook() {
1966                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1967                 QTreeWidgetItem currentSelection;
1968                 currentSelection = selections.get(0);
1969                 String guid = currentSelection.text(2);
1970
1971                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1972                         return;
1973                 
1974                 Notebook n = null;;
1975                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1976                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1977                                 n = listManager.getNotebookIndex().get(i);
1978                                 i = listManager.getNotebookIndex().size();
1979                         }
1980                 }
1981                                 
1982                 String authToken = null;
1983                 if (syncRunner.isConnected)
1984                         authToken = syncRunner.authToken;
1985                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1986                 share.exec();
1987                 
1988         }
1989
1990         // Delete an existing notebook
1991         @SuppressWarnings("unused")
1992         private void deleteNotebook() {
1993                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1994                 boolean stacksFound = false;
1995                 boolean notebooksFound = false;
1996                 boolean assigned = false;
1997                 // Check if any notes have this notebook
1998                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1999         for (int i=0; i<selections.size(); i++) {
2000                 QTreeWidgetItem currentSelection;
2001                 currentSelection = selections.get(i);
2002                 String guid = currentSelection.text(2);
2003                 if (!guid.equalsIgnoreCase("STACK")) {
2004                         notebooksFound = true;
2005                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2006                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
2007                                 if (noteGuid.equals(guid)) {
2008                                         assigned = true;
2009                                         j=listManager.getNoteIndex().size();
2010                                         i=selections.size();
2011                                 }
2012                         }
2013                 } else {
2014                         stacksFound = true;
2015                 }
2016         }
2017                 if (assigned) {
2018                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
2019                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
2020                         return;
2021                 }
2022                 
2023                 if (conn.getNotebookTable().getAll().size() == 1) {
2024                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
2025                         return;
2026                 }
2027         
2028         // If all notebooks are clear, verify the delete
2029                 String msg1 = new String(tr("Delete selected notebooks?"));
2030                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
2031                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
2032                                 " not deleted unless selected?"));
2033                 String msg = "";
2034                 if (stacksFound && notebooksFound)
2035                         msg = msg3;
2036                 if (!stacksFound && notebooksFound)
2037                         msg = msg1;
2038                 if (stacksFound && !notebooksFound)
2039                         msg = msg2;
2040                 if (QMessageBox.question(this, tr("Confirmation"), msg,
2041                         QMessageBox.StandardButton.Yes, 
2042                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2043                         return;
2044                 }
2045                 
2046                 // If confirmed, delete the notebook
2047         for (int i=selections.size()-1; i>=0; i--) {
2048                 QTreeWidgetItem currentSelection;
2049                 currentSelection = selections.get(i);
2050                 String guid = currentSelection.text(2);
2051                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
2052                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
2053                         listManager.renameStack(currentSelection.text(0), "");
2054                 } else {
2055                         conn.getNotebookTable().expungeNotebook(guid, true);
2056                         listManager.deleteNotebook(guid);
2057                 }
2058         }
2059
2060                 notebookIndexUpdated();
2061 //        notebookTreeSelection();
2062 //        notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
2063 //        listManager.countNotebookResults(listManager.getNoteIndex());
2064         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
2065         }
2066         // A note's notebook has been updated
2067         @SuppressWarnings("unused")
2068         private void updateNoteNotebook(String guid, String notebookGuid) {
2069                 // 同じノートブックに入れられたノート間の履歴を登録
2070                 conn.getHistoryTable().addSameNotebookHistory(guid, notebookGuid);
2071                 
2072                 // Update the list manager
2073                 listManager.updateNoteNotebook(guid, notebookGuid);
2074                 listManager.countNotebookResults(listManager.getNoteIndex());
2075 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
2076                 
2077                 // Find the name of the notebook
2078                 String notebookName = null;
2079                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
2080                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
2081                                 notebookName = listManager.getNotebookIndex().get(i).getName();
2082                                 break;
2083                         }
2084                 }
2085                 
2086                 // If we found the name, update the browser window
2087                 if (notebookName != null) {
2088                         updateListNoteNotebook(guid, notebookName);
2089                         if (guid.equals(currentNoteGuid)) {
2090                                 int pos =  browserWindow.notebookBox.findText(notebookName);
2091                                 if (pos >=0)
2092                                         browserWindow.notebookBox.setCurrentIndex(pos);
2093                         }
2094                 }
2095                 
2096                 // If we're dealing with the current note, then we need to be sure and update the notebook there
2097                 if (guid.equals(currentNoteGuid)) {
2098                         if (currentNote != null) {
2099                                 currentNote.setNotebookGuid(notebookGuid);
2100                         }
2101                 }
2102         }
2103         // Open/close notebooks
2104         @SuppressWarnings("unused")
2105         private void closeNotebooks() {
2106                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
2107                 na.exec();
2108                 if (!na.okClicked())
2109                         return;
2110                 
2111                 waitCursor(true);
2112                 listManager.getArchiveNotebookIndex().clear();
2113                 
2114                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
2115                         String text = na.getClosedBookList().takeItem(i).text();
2116                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
2117                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
2118                                         Notebook n = listManager.getNotebookIndex().get(j);
2119                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
2120                                         listManager.getArchiveNotebookIndex().add(n);
2121                                         j=listManager.getNotebookIndex().size();
2122                                 }
2123                         }
2124                 }
2125                 
2126                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
2127                         String text = na.getOpenBookList().takeItem(i).text();
2128                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
2129                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
2130                                         Notebook n = listManager.getNotebookIndex().get(j);
2131                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
2132                                         j=listManager.getNotebookIndex().size();
2133                                 }
2134                         }
2135                 }
2136                 notebookTreeSelection();
2137                 listManager.loadNotesIndex();
2138                 notebookIndexUpdated();
2139                 noteIndexUpdated(false);
2140                 reloadTagTree(true);
2141 //              noteIndexUpdated(false);
2142                 
2143                 // Build a list of non-closed notebooks
2144                 List<Notebook> nbooks = new ArrayList<Notebook>();
2145                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
2146                         boolean found=false;
2147                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
2148                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
2149                                         found = true;
2150                         }
2151                         if (!found)
2152                                 nbooks.add(listManager.getNotebookIndex().get(i));
2153                 }
2154                 
2155                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
2156                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
2157                 browserWindow.setNotebookList(filteredBooks);
2158                 
2159                 // Update any external windows
2160                 Iterator<String> set = externalWindows.keySet().iterator();
2161                 while(set.hasNext())
2162                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
2163                 
2164                 // 全てのタブウィンドウを更新
2165                 Iterator<Integer> it = tabWindows.keySet().iterator();
2166                 while (it.hasNext()) {
2167                         tabWindows.get(it.next()).getBrowserWindow()
2168                                         .setNotebookList(filteredBooks);
2169                 }
2170                 
2171                 waitCursor(false);
2172         }
2173         // Change the notebook's icon
2174         @SuppressWarnings("unused")
2175         private void setNotebookIcon() {
2176                 boolean stackSelected = false;
2177                 boolean allNotebookSelected = false;
2178                 
2179                 QTreeWidgetItem currentSelection;
2180                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
2181                 if (selections.size() == 0)
2182                         return;
2183                 
2184                 currentSelection = selections.get(0);   
2185                 String guid = currentSelection.text(2);
2186                 if (guid.equalsIgnoreCase(""))
2187                         allNotebookSelected = true;
2188                 if (guid.equalsIgnoreCase("STACK"))
2189                         stackSelected = true;
2190
2191                 QIcon currentIcon = currentSelection.icon(0);
2192                 QIcon icon;
2193                 SetIcon dialog;
2194                 
2195                 if (!stackSelected && !allNotebookSelected) {
2196                         icon = conn.getNotebookTable().getIcon(guid);
2197                         if (icon == null) {
2198                                 dialog = new SetIcon(currentIcon, saveLastPath);
2199                                 dialog.setUseDefaultIcon(true);
2200                         } else {
2201                                 dialog = new SetIcon(icon, saveLastPath);
2202                                 dialog.setUseDefaultIcon(false);
2203                         }
2204                 } else {
2205                         if (stackSelected) {
2206                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
2207                         } else {
2208                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
2209                         }
2210                         if (icon == null) {
2211                                 dialog = new SetIcon(currentIcon, saveLastPath);
2212                                 dialog.setUseDefaultIcon(true);
2213                         } else {
2214                                 dialog = new SetIcon(icon, saveLastPath);
2215                                 dialog.setUseDefaultIcon(false);
2216                         }
2217                 }
2218                 dialog.exec();
2219                 if (dialog.okPressed()) {
2220                 saveLastPath = dialog.getPath();
2221
2222                         QIcon newIcon = dialog.getIcon();
2223                         if (stackSelected) {
2224                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
2225                                 if (newIcon == null) {
2226                                         newIcon = new QIcon(iconPath+"books2.png");
2227                                 }
2228                                 currentSelection.setIcon(0,newIcon);
2229                                 return;
2230                         }
2231                         if (allNotebookSelected) {
2232                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
2233                                 if (newIcon == null) {
2234                                         newIcon = new QIcon(iconPath+"notebook-green.png");
2235                                 }
2236                                 currentSelection.setIcon(0,newIcon);
2237                                 return;
2238                         }
2239                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
2240                         if (newIcon == null) {
2241                                 boolean isPublished = false;;
2242                                 boolean found = false;
2243                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
2244                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
2245                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
2246                                                 found = true;
2247                                         }
2248                                 }
2249                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
2250                         }
2251                         currentSelection.setIcon(0, newIcon);
2252                 }
2253         
2254         }
2255         
2256         
2257     //***************************************************************
2258     //***************************************************************
2259     //** These functions deal with Tag menu items
2260     //***************************************************************
2261     //***************************************************************
2262         // Add a new notebook
2263         @SuppressWarnings("unused")
2264         private void addTag() {
2265                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2266                 TagEdit edit = new TagEdit();
2267                 edit.setTagList(listManager.getTagIndex());
2268
2269                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2270                 QTreeWidgetItem currentSelection = null;
2271                 if (selections.size() > 0) {
2272                         currentSelection = selections.get(0);
2273                         edit.setParentTag(currentSelection.text(0));
2274                 }
2275
2276                 edit.exec();
2277         
2278                 if (!edit.okPressed())
2279                         return;
2280         
2281                 Calendar currentTime = new GregorianCalendar();
2282                 Long l = new Long(currentTime.getTimeInMillis());
2283                 String randint = new String(Long.toString(l));
2284         
2285                 Tag newTag = new Tag();
2286                 newTag.setUpdateSequenceNum(0);
2287                 newTag.setGuid(randint);
2288                 newTag.setName(edit.getTag());
2289                 if (edit.getParentTag().isChecked()) {
2290                         newTag.setParentGuid(currentSelection.text(2));
2291                         newTag.setParentGuidIsSet(true);
2292                         currentSelection.setExpanded(true);
2293                 }
2294                 conn.getTagTable().addTag(newTag, true);
2295                 listManager.getTagIndex().add(newTag);
2296                 reloadTagTree(true);
2297                 
2298                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2299         }
2300         @SuppressWarnings("unused")
2301         private void reloadTagTree() {
2302                 reloadTagTree(false);
2303         }
2304         private void reloadTagTree(boolean reload) {
2305                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2306                 tagIndexUpdated(reload);
2307                 boolean filter = false;
2308                 if (reload)
2309                         listManager.countTagResults(listManager.getNoteIndex());
2310                 if (notebookTree.selectedItems().size() > 0 
2311                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2312                                                   filter = true;
2313                 if (tagTree.selectedItems().size() > 0)
2314                         filter = true;
2315                 tagTree.showAllTags(!filter);
2316                 tagIndexUpdated(false);
2317                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2318         }
2319         // Edit an existing tag
2320         @SuppressWarnings("unused")
2321         private void editTag() {
2322                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2323                 TagEdit edit = new TagEdit();
2324                 edit.setTitle("Edit Tag");
2325                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2326                 QTreeWidgetItem currentSelection;
2327                 currentSelection = selections.get(0);
2328                 edit.setTag(currentSelection.text(0));
2329                 edit.setTagList(listManager.getTagIndex());
2330                 edit.exec();
2331         
2332                 if (!edit.okPressed())
2333                         return;
2334         
2335                 String guid = currentSelection.text(2);
2336                 currentSelection.setText(0,edit.getTag());
2337                 
2338                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2339                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2340                                 listManager.getTagIndex().get(i).setName(edit.getTag());
2341                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2342                                 updateListTagName(guid);
2343                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2344                                         browserWindow.setTag(getTagNamesForNote(currentNote));
2345                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2346                                 //return;
2347                         }
2348                 }
2349                 listManager.reloadNoteTagNames(guid, edit.getTag());
2350                 noteIndexUpdated(true);
2351                 refreshEvernoteNote(true);
2352                 browserWindow.setTag(getTagNamesForNote(currentNote));
2353                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2354         }
2355         // Delete an existing tag
2356         @SuppressWarnings("unused")
2357         private void deleteTag() {
2358                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2359                 
2360                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2361                         QMessageBox.StandardButton.Yes, 
2362                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2363                                                         return;
2364                 }
2365                 
2366                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2367         for (int i=selections.size()-1; i>=0; i--) {
2368                 QTreeWidgetItem currentSelection;
2369                 currentSelection = selections.get(i);                   
2370                 removeTagItem(currentSelection.text(2));
2371         }
2372         tagIndexUpdated(true);
2373         tagTreeSelection();
2374         listManager.countTagResults(listManager.getNoteIndex());
2375 //              tagTree.updateCounts(listManager.getTagCounter());
2376         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2377         }
2378         // Remove a tag tree item.  Go recursively down & remove the children too
2379         private void removeTagItem(String guid) {
2380         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
2381                 String parent = listManager.getTagIndex().get(j).getParentGuid();
2382                 if (parent != null && parent.equals(guid)) {            
2383                         //Remove this tag's children
2384                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
2385                 }
2386         }
2387         //Now, remove this tag
2388         removeListTagName(guid);
2389         conn.getTagTable().expungeTag(guid, true);                      
2390         for (int a=0; a<listManager.getTagIndex().size(); a++) {
2391                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2392                         listManager.getTagIndex().remove(a);
2393                         return;
2394                 }
2395         }
2396         }
2397         // Setup the tree containing the user's tags
2398     private void initializeTagTree() {
2399         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2400 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2401 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
2402         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2403         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2404         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2405     }
2406     // Listener when a tag is selected
2407         private void tagTreeSelection() {
2408         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2409                 
2410         clearTrashFilter();
2411         clearAttributeFilter();
2412         clearSavedSearchFilter();
2413         
2414                 menuBar.noteRestoreAction.setVisible(false);
2415                 
2416                 // ゴミ箱から元の画面に戻す。連想ノートリストをONに。
2417                 if (!rensoNoteListDock.isEnabled()) {
2418                         rensoNoteListDock.setEnabled(true);
2419                 }
2420                 
2421         List<QTreeWidgetItem> selections = tagTree.selectedItems();
2422         QTreeWidgetItem currentSelection;
2423         selectedTagGUIDs.clear();
2424         for (int i=0; i<selections.size(); i++) {
2425                 currentSelection = selections.get(i);
2426                 selectedTagGUIDs.add(currentSelection.text(2));
2427         }
2428         if (selections.size() > 0) {
2429                 menuBar.tagEditAction.setEnabled(true);
2430                 menuBar.tagDeleteAction.setEnabled(true);
2431                 menuBar.tagIconAction.setEnabled(true);
2432         }
2433         else {
2434                 menuBar.tagEditAction.setEnabled(false);
2435                 menuBar.tagDeleteAction.setEnabled(false);
2436                 menuBar.tagIconAction.setEnabled(true);
2437         }
2438         if (selections.size() > 1)
2439                 menuBar.tagMergeAction.setEnabled(true);
2440         else
2441                 menuBar.tagMergeAction.setEnabled(false);
2442         listManager.setSelectedTags(selectedTagGUIDs);
2443         listManager.loadNotesIndex();
2444         noteIndexUpdated(false);
2445         refreshEvernoteNote(true);
2446         listManager.refreshCounters = true;
2447         listManager.refreshCounters();
2448         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2449     }
2450     // trigger the tag index to be refreshed
2451     @SuppressWarnings("unused")
2452         private void tagIndexUpdated() {
2453         tagIndexUpdated(true);
2454     }
2455     private void tagIndexUpdated(boolean reload) {
2456         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2457                 if (selectedTagGUIDs == null)
2458                         selectedTagGUIDs = new ArrayList<String>();
2459                 if (reload)
2460                         listManager.reloadTagIndex();
2461
2462                 tagTree.blockSignals(true);
2463                 if (reload) {
2464                         tagTree.setIcons(conn.getTagTable().getAllIcons());
2465                         tagTree.load(listManager.getTagIndex());
2466                 }
2467
2468         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2469                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2470                 if (!found)
2471                         selectedTagGUIDs.remove(i);
2472         }
2473         tagTree.blockSignals(false);
2474         
2475                 browserWindow.setTag(getTagNamesForNote(currentNote));
2476         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2477     }   
2478     // Show/Hide note information
2479         @SuppressWarnings("unused")
2480         private void toggleTagWindow() {
2481                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2482         if (tagTree.isVisible())
2483                 tagTree.hide();
2484         else
2485                 tagTree.show();
2486         menuBar.hideTags.setChecked(tagTree.isVisible());
2487         Global.saveWindowVisible("tagTree", tagTree.isVisible());
2488         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2489     }   
2490         // A note's tags have been updated
2491         @SuppressWarnings("unused")
2492         private void updateNoteTags(String guid, List<String> tags) {
2493                 // Save any new tags.  We'll need them later.
2494                 List<String> newTags = new ArrayList<String>();
2495                 for (int i=0; i<tags.size(); i++) {
2496                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
2497                                 newTags.add(tags.get(i));
2498                 }
2499                 
2500                 listManager.saveNoteTags(guid, tags, true);
2501                 listManager.countTagResults(listManager.getNoteIndex());
2502                 StringBuffer names = new StringBuffer("");
2503                 for (int i=0; i<tags.size(); i++) {
2504                         names = names.append(tags.get(i));
2505                         if (i<tags.size()-1) {
2506                                 names.append(Global.tagDelimeter + " ");
2507                         }
2508                 }
2509                 browserWindow.setTag(names.toString());
2510                 
2511                 for (TabBrowse tab: tabWindows.values()) {
2512                         if (tab.getBrowserWindow().getNote().getGuid().equals(guid)) {
2513                                 int index = tabBrowser.indexOf(tab);
2514                                 noteDirty.put(index, true);
2515                                 break;
2516                         }
2517                 }
2518                 
2519                 // Now, we need to add any new tags to the tag tree
2520                 for (int i=0; i<newTags.size(); i++) 
2521                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2522         }
2523         // Get a string containing all tag names for a note
2524         private String getTagNamesForNote(Note n) {
2525                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2526                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2527                         return "";
2528                 StringBuffer buffer = new StringBuffer(100);
2529                 Vector<String> v = new Vector<String>();
2530                 List<String> guids = n.getTagGuids();
2531                 
2532                 if (guids == null) 
2533                         return "";
2534                 
2535                 for (int i=0; i<guids.size(); i++) {
2536                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2537                 }
2538                 Comparator<String> comparator = Collections.reverseOrder();
2539                 Collections.sort(v,comparator);
2540                 Collections.reverse(v);
2541                 
2542                 for (int i = 0; i<v.size(); i++) {
2543                         if (i>0) 
2544                                 buffer.append(", ");
2545                         buffer.append(v.get(i));
2546                 }
2547                 
2548                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2549                 return buffer.toString();
2550         }       
2551         // Tags were added via dropping notes from the note list
2552         @SuppressWarnings("unused")
2553         private void tagsAdded(String noteGuid, String tagGuid) {
2554                 String tagName = null;
2555                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2556                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2557                                 tagName = listManager.getTagIndex().get(i).getName();
2558                                 i=listManager.getTagIndex().size();
2559                         }
2560                 }
2561                 if (tagName == null)
2562                         return;
2563                 
2564                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2565                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2566                                 List<String> tagNames = new ArrayList<String>();
2567                                 tagNames.add(new String(tagName));
2568                                 Note n = listManager.getMasterNoteIndex().get(i);
2569                                 for (int j=0; j<n.getTagNames().size(); j++) {
2570                                         tagNames.add(new String(n.getTagNames().get(j)));
2571                                 }
2572                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2573                                 if (n.getGuid().equals(currentNoteGuid)) {
2574                                         Collections.sort(tagNames);
2575                                         String display = "";
2576                                         for (int j=0; j<tagNames.size(); j++) {
2577                                                 display = display+tagNames.get(j);
2578                                                 if (j+2<tagNames.size()) 
2579                                                         display = display+Global.tagDelimeter+" ";
2580                                         }
2581                                         browserWindow.setTag(display);
2582                                 }
2583                                 i=listManager.getMasterNoteIndex().size();
2584                         }
2585                 }
2586                 
2587                 
2588                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2589         }
2590         private void clearTagFilter() {
2591                 tagTree.blockSignals(true);
2592                 tagTree.clearSelection();
2593                 menuBar.noteRestoreAction.setVisible(false);
2594                 menuBar.tagEditAction.setEnabled(false);
2595                 menuBar.tagMergeAction.setEnabled(false);
2596                 menuBar.tagDeleteAction.setEnabled(false);
2597                 menuBar.tagIconAction.setEnabled(false);
2598                 selectedTagGUIDs.clear();
2599         listManager.setSelectedTags(selectedTagGUIDs);
2600         tagTree.blockSignals(false);
2601         }
2602         // Change the icon for a tag
2603         @SuppressWarnings("unused")
2604         private void setTagIcon() {
2605                 QTreeWidgetItem currentSelection;
2606                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2607                 if (selections.size() == 0)
2608                         return;
2609                 
2610                 currentSelection = selections.get(0);   
2611                 String guid = currentSelection.text(2);
2612
2613                 QIcon currentIcon = currentSelection.icon(0);
2614                 QIcon icon = conn.getTagTable().getIcon(guid);
2615                 SetIcon dialog;
2616                 if (icon == null) {
2617                         dialog = new SetIcon(currentIcon, saveLastPath);
2618                         dialog.setUseDefaultIcon(true);
2619                 } else {
2620                         dialog = new SetIcon(icon, saveLastPath);
2621                         dialog.setUseDefaultIcon(false);
2622                 }
2623                 dialog.exec();
2624                 if (dialog.okPressed()) {
2625                 saveLastPath = dialog.getPath();
2626                         QIcon newIcon = dialog.getIcon();
2627                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2628                         if (newIcon == null) 
2629                                 newIcon = new QIcon(iconPath+"tag.png");
2630                         currentSelection.setIcon(0, newIcon);
2631                 }
2632         
2633         }
2634         // Merge tags
2635         @SuppressWarnings("unused")
2636         private void mergeTags() {
2637                 List<Tag> tags = new ArrayList<Tag>();
2638                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2639                 for (int i=0; i<selections.size(); i++) {
2640                         Tag record = new Tag();
2641                         record.setGuid(selections.get(i).text(2));
2642                         record.setName(selections.get(i).text(0));
2643                         tags.add(record);
2644                 }
2645
2646                 TagMerge mergeDialog = new TagMerge(tags);
2647                 mergeDialog.exec();
2648                 if (!mergeDialog.okClicked())
2649                         return;
2650                 String newGuid = mergeDialog.getNewTagGuid();
2651                 
2652                 for (int i=0; i<tags.size(); i++) {
2653                         if (!tags.get(i).getGuid().equals(newGuid)) {
2654                                 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2655                                 for (int j=0; j<noteGuids.size(); j++) {
2656                                         String noteGuid = noteGuids.get(j);
2657                                         conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2658                                         if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2659                                                 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid, true);
2660                                 }
2661                         }
2662                 }
2663                 listManager.reloadIndexes();
2664         }
2665         
2666     //***************************************************************
2667     //***************************************************************
2668     //** These functions deal with Saved Search menu items
2669     //***************************************************************
2670     //***************************************************************
2671         // Add a new notebook
2672         @SuppressWarnings("unused")
2673         private void addSavedSearch() {
2674                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2675                 SavedSearchEdit edit = new SavedSearchEdit();
2676                 edit.setSearchList(listManager.getSavedSearchIndex());
2677                 edit.exec();
2678         
2679                 if (!edit.okPressed())
2680                         return;
2681         
2682                 Calendar currentTime = new GregorianCalendar();         
2683                 Long l = new Long(currentTime.getTimeInMillis());
2684                 String randint = new String(Long.toString(l));
2685         
2686                 SavedSearch search = new SavedSearch();
2687                 search.setUpdateSequenceNum(0);
2688                 search.setGuid(randint);
2689                 search.setName(edit.getName());
2690                 search.setQuery(edit.getQuery());
2691                 search.setFormat(QueryFormat.USER);
2692                 listManager.getSavedSearchIndex().add(search);
2693                 conn.getSavedSearchTable().addSavedSearch(search, true);
2694                 savedSearchIndexUpdated();
2695                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2696         }
2697         // Edit an existing tag
2698         @SuppressWarnings("unused")
2699         private void editSavedSearch() {
2700                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2701                 SavedSearchEdit edit = new SavedSearchEdit();
2702                 edit.setTitle(tr("Edit Search"));
2703                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2704                 QTreeWidgetItem currentSelection;
2705                 currentSelection = selections.get(0);
2706                 String guid = currentSelection.text(1);
2707                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2708                 edit.setName(currentSelection.text(0));
2709                 edit.setQuery(s.getQuery());
2710                 edit.setSearchList(listManager.getSavedSearchIndex());
2711                 edit.exec();
2712         
2713                 if (!edit.okPressed())
2714                         return;
2715         
2716                 List<SavedSearch> list = listManager.getSavedSearchIndex();
2717                 SavedSearch search = null;
2718                 boolean found = false;
2719                 for (int i=0; i<list.size(); i++) {
2720                         search = list.get(i);
2721                         if (search.getGuid().equals(guid)) {
2722                                 i=list.size();
2723                                 found = true;
2724                         }
2725                 }
2726                 if (!found)
2727                         return;
2728                 search.setName(edit.getName());
2729                 search.setQuery(edit.getQuery());
2730                 conn.getSavedSearchTable().updateSavedSearch(search, true);
2731                 savedSearchIndexUpdated();
2732                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2733         }
2734         // Delete an existing tag
2735         @SuppressWarnings("unused")
2736         private void deleteSavedSearch() {
2737                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2738                 
2739                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2740                         QMessageBox.StandardButton.Yes, 
2741                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2742                                                         return;
2743                 }
2744                 
2745                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2746         for (int i=selections.size()-1; i>=0; i--) {
2747                 QTreeWidgetItem currentSelection;
2748                 currentSelection = selections.get(i);
2749                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2750                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2751                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2752                                 listManager.getSavedSearchIndex().remove(j);
2753                                 j=listManager.getSavedSearchIndex().size()+1;
2754                         }
2755                 }
2756                 selections.remove(i);
2757         }
2758         savedSearchIndexUpdated();
2759         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2760         }
2761     // Setup the tree containing the user's tags
2762     private void initializeSavedSearchTree() {
2763         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2764         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2765         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2766     }
2767     // Listener when a tag is selected
2768     @SuppressWarnings("unused")
2769         private void savedSearchTreeSelection() {
2770         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2771
2772         clearNotebookFilter();
2773         clearTagFilter();
2774         clearTrashFilter();
2775         clearAttributeFilter();
2776         
2777         String currentGuid = selectedSavedSearchGUID;
2778         menuBar.savedSearchEditAction.setEnabled(true);
2779         menuBar.savedSearchDeleteAction.setEnabled(true);
2780         menuBar.savedSearchIconAction.setEnabled(true);
2781         
2782                 // ゴミ箱から元の画面に戻す。連想ノートリストをONに。
2783                 if (!rensoNoteListDock.isEnabled()) {
2784                         rensoNoteListDock.setEnabled(true);
2785                 }
2786                 
2787         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2788         QTreeWidgetItem currentSelection;
2789         selectedSavedSearchGUID = "";
2790         for (int i=0; i<selections.size(); i++) {
2791                 currentSelection = selections.get(i);
2792                 if (currentSelection.text(1).equals(currentGuid)) {
2793                         currentSelection.setSelected(false);
2794                 } else {
2795                         selectedSavedSearchGUID = currentSelection.text(1);
2796                 }
2797 //              i = selections.size() +1;
2798         }
2799         
2800         // There is the potential for no notebooks to be selected if this 
2801         // happens then we make it look like all notebooks were selecetd.
2802         // If that happens, just select the "all notebooks"
2803         if (selections.size()==0) {
2804                 clearSavedSearchFilter();
2805         }
2806         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2807         
2808         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2809     }
2810     private void clearSavedSearchFilter() {
2811         menuBar.savedSearchEditAction.setEnabled(false);
2812         menuBar.savedSearchDeleteAction.setEnabled(false);
2813         menuBar.savedSearchIconAction.setEnabled(false);
2814         savedSearchTree.blockSignals(true);
2815         savedSearchTree.clearSelection();
2816         savedSearchTree.blockSignals(false);
2817         selectedSavedSearchGUID = "";
2818         searchField.setEditText("");
2819         searchPerformed = false;
2820         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2821     }
2822     // trigger the tag index to be refreshed
2823         private void savedSearchIndexUpdated() { 
2824                 if (selectedSavedSearchGUID == null)
2825                         selectedSavedSearchGUID = new String();
2826                 savedSearchTree.blockSignals(true);
2827                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2828         savedSearchTree.load(listManager.getSavedSearchIndex());
2829         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2830         savedSearchTree.blockSignals(false);
2831     }
2832     // trigger when the saved search selection changes
2833     @SuppressWarnings("unused")
2834         private void updateSavedSearchSelection() {
2835                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2836                 
2837         menuBar.savedSearchEditAction.setEnabled(true);
2838         menuBar.savedSearchDeleteAction.setEnabled(true);
2839         menuBar.savedSearchIconAction.setEnabled(true);
2840         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2841
2842         if (selections.size() > 0) {
2843                 menuBar.savedSearchEditAction.setEnabled(true);
2844                 menuBar.savedSearchDeleteAction.setEnabled(true);
2845                 menuBar.savedSearchIconAction.setEnabled(true);
2846                 selectedSavedSearchGUID = selections.get(0).text(1);
2847                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2848                 searchField.setEditText(s.getQuery());
2849         } else { 
2850                 menuBar.savedSearchEditAction.setEnabled(false);
2851                 menuBar.savedSearchDeleteAction.setEnabled(false);
2852                 menuBar.savedSearchIconAction.setEnabled(false);
2853                 selectedSavedSearchGUID = "";
2854                 searchField.setEditText("");
2855         }
2856         searchFieldChanged();
2857         
2858                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2859
2860         
2861     }
2862     // Show/Hide note information
2863         @SuppressWarnings("unused")
2864         private void toggleSavedSearchWindow() {
2865                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2866         if (savedSearchTree.isVisible())
2867                 savedSearchTree.hide();
2868         else
2869                 savedSearchTree.show();
2870         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2871                                 
2872                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2873         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2874     }
2875         // Change the icon for a saved search
2876         @SuppressWarnings("unused")
2877         private void setSavedSearchIcon() {
2878                 QTreeWidgetItem currentSelection;
2879                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2880                 if (selections.size() == 0)
2881                         return;
2882                 
2883                 currentSelection = selections.get(0);   
2884                 String guid = currentSelection.text(1);
2885
2886                 QIcon currentIcon = currentSelection.icon(0);
2887                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2888                 SetIcon dialog;
2889                 if (icon == null) {
2890                         dialog = new SetIcon(currentIcon, saveLastPath);
2891                         dialog.setUseDefaultIcon(true);
2892                 } else {
2893                         dialog = new SetIcon(icon, saveLastPath);
2894                         dialog.setUseDefaultIcon(false);
2895                 }
2896                 dialog.exec();
2897                 if (dialog.okPressed()) {
2898                 saveLastPath = dialog.getPath();
2899                         QIcon newIcon = dialog.getIcon();
2900                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2901                         if (newIcon == null) 
2902                                 newIcon = new QIcon(iconPath+"search.png");
2903                         currentSelection.setIcon(0, newIcon);
2904                 }
2905         
2906         }
2907         
2908         
2909         
2910         
2911     //***************************************************************
2912     //***************************************************************
2913     //** These functions deal with Help menu & tool menu items
2914     //***************************************************************
2915     //***************************************************************
2916         // Show database status
2917         @SuppressWarnings("unused")
2918         private void databaseStatus() {
2919                 waitCursor(true);
2920                 indexRunner.interrupt = true;
2921                 int dirty = conn.getNoteTable().getDirtyCount();
2922                 int unindexed = conn.getNoteTable().getUnindexedCount();
2923                 DatabaseStatus status = new DatabaseStatus();
2924                 status.setUnsynchronized(dirty);
2925                 status.setUnindexed(unindexed);
2926                 status.setNoteCount(conn.getNoteTable().getNoteCount());
2927                 status.setNotebookCount(listManager.getNotebookIndex().size());
2928                 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2929                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2930                 status.setTagCount(listManager.getTagIndex().size());
2931                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2932                 status.setWordCount(conn.getWordsTable().getWordCount());
2933                 status.setHistoryCount(conn.getHistoryTable().getHistoryCount());
2934                 status.setRensoClickCount(conn.getHistoryTable().getRensoClickCount());
2935                 waitCursor(false);
2936                 status.exec();
2937         }
2938         // Compact the database
2939         @SuppressWarnings("unused")
2940         private void compactDatabase() {
2941         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2942                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2943                                 "but please be aware that depending upon the size of your database this can be time consuming " +
2944                                 "and NeighborNote will be unresponsive until it is complete.  Do you wish to continue?"),
2945                                 QMessageBox.StandardButton.Yes, 
2946                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2947                                                         return;
2948                 }
2949                 setMessage("Compacting database.");
2950                 waitCursor(true);
2951                 listManager.compactDatabase();
2952                 waitCursor(false);
2953                 setMessage("Database compact is complete.");            
2954         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2955     }
2956         @SuppressWarnings("unused")
2957         private void accountInformation() {
2958                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2959                 AccountDialog dialog = new AccountDialog();
2960                 dialog.show();
2961                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2962         }
2963         @SuppressWarnings("unused")
2964         private void releaseNotes() {
2965                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2966                 QDialog dialog = new QDialog(this);
2967                 QHBoxLayout layout = new QHBoxLayout();
2968                 QTextEdit textBox = new QTextEdit();
2969                 layout.addWidget(textBox);
2970                 textBox.setReadOnly(true);
2971                 QFile file = new QFile(Global.getFileManager().getProgramDirPath("release.txt"));
2972                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2973                 QIODevice.OpenModeFlag.Text)))
2974                         return;
2975                 // 日本語文字化け対策
2976                 QTextCodec codec = QTextCodec.codecForName("UTF-8");
2977                 QTextStream textStream = new QTextStream(file);
2978                 textStream.setCodec(codec);
2979                 textBox.setText(textStream.readAll().toString());
2980                 
2981                 file.close();
2982                 dialog.setWindowTitle(tr("Release Notes"));
2983                 dialog.setLayout(layout);
2984                 dialog.show();
2985                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2986         }
2987         // Called when user picks Log from the help menu
2988         @SuppressWarnings("unused")
2989         private void logger() {
2990                 logger.log(logger.HIGH, "Entering NeverNote.logger");
2991                 LogFileDialog dialog = new LogFileDialog(emitLog);
2992                 dialog.exec();
2993                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2994         }
2995         // Menu option "help/about" was selected
2996         @SuppressWarnings("unused")
2997         private void about() {
2998                 logger.log(logger.HIGH, "Entering NeverNote.about");
2999                 QMessageBox.about(this, 
3000                                                 tr("About NeighborNote"),
3001                                                 tr("<h4><center><b>NeighborNote</b></center></h4><hr><center>Version ")
3002                                                 +Global.version + "(based on NixNote 1.5)"
3003                                                 //+"1.2.120724"
3004                                                 +tr("<hr>"
3005                                                                 +"Open Source Evernote Client.<br><br>" 
3006                                                                 +"Licensed under GPL v2.  <br><hr><br>"
3007                                                                 +"</center>Evernote is copyright 2001-2012 by Evernote Corporation<br>"
3008                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
3009                                                                 +"PDFRenderer is licened under the LGPL<br>"
3010                                                                 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
3011                                                                 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
3012                                                                 +"Jazzy is licened under the LGPL<br>"
3013                                                                 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
3014                                                                 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
3015                                                                 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
3016                 logger.log(logger.HIGH, "Leaving NeverNote.about");
3017         }
3018         // Hide the entire left hand side
3019         @SuppressWarnings("unused")
3020         private void toggleLeftSide() {
3021                 boolean hidden;
3022                 
3023                 hidden = !menuBar.hideLeftSide.isChecked();
3024                 menuBar.hideLeftSide.setChecked(!hidden);
3025                 
3026                 if (!hidden) 
3027                         leftSplitter1.setHidden(true);
3028                 else
3029                         leftSplitter1.setHidden(false);
3030                 
3031                 Global.saveWindowVisible("leftPanel", hidden);
3032                 
3033         }
3034         public void checkForUpdates() {
3035                 // Send off thread to check for a new version
3036                 versionChecker = new QNetworkAccessManager(this);
3037                 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
3038                 QNetworkRequest request = new QNetworkRequest();
3039                 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
3040                 versionChecker.get(request);
3041         }
3042         @SuppressWarnings("unused")
3043         private void upgradeFileRead(QNetworkReply reply) {
3044                 if (!reply.isReadable())
3045                         return;
3046                 
3047                 String winVersion = Global.version;
3048                 String osxVersion = Global.version;
3049                 String linuxVersion = Global.version;
3050                 String linux64Version = Global.version;
3051                 String version = Global.version;
3052                 
3053                 // Determine the versions available
3054                 QByteArray data = reply.readLine();
3055                 while (data != null && !reply.atEnd()) {
3056                         String line = data.toString();
3057                         String lineVersion;
3058                         if (line.contains(":")) 
3059                                 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
3060                         else
3061                                 lineVersion = "";
3062                         if (line.toLowerCase().contains("windows")) 
3063                                 winVersion = lineVersion;
3064                         else if (line.toLowerCase().contains("os-x")) 
3065                                 osxVersion = lineVersion;
3066                         else if (line.toLowerCase().contains("linux amd64")) 
3067                                 linux64Version = lineVersion;
3068                         else if (line.toLowerCase().contains("linux i386")) 
3069                                 linuxVersion = lineVersion;
3070                         else if (line.toLowerCase().contains("default")) 
3071                                 version = lineVersion;
3072                         
3073                         // Read the next line
3074                         data = reply.readLine();
3075                 }
3076                 
3077                 // Now we need to determine what system we are on.
3078                 if (System.getProperty("os.name").toLowerCase().contains("windows"))
3079                         version = winVersion;
3080                 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
3081                         version = osxVersion;
3082                 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
3083                         if (System.getProperty("os.arch").contains("amd64") ||
3084                                 System.getProperty("os.arch").contains("x86_64"))
3085                                         version = linux64Version;
3086                         else
3087                                 version = linuxVersion;
3088                 }
3089                 
3090                 
3091                 for (String validVersion : Global.validVersions) {
3092                         if (version.equals(validVersion))
3093                                 return;
3094                 }
3095                 
3096                 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
3097                 dialog.exec();
3098                 if (dialog.remindMe())
3099                         Global.setCheckVersionUpgrade(true);
3100                 else
3101                         Global.setCheckVersionUpgrade(false);
3102         }
3103                 
3104         
3105     //***************************************************************
3106     //***************************************************************
3107     //** These functions deal with the Toolbar
3108     //***************************************************************
3109     //*************************************************************** 
3110         @SuppressWarnings("unused")
3111         private void focusSearch() {
3112                 searchField.setFocus();
3113         }
3114
3115         // Text in the search bar has been cleared
3116         private void searchFieldCleared() {
3117                 saveNote();
3118                 
3119                 // This is done because we want to force a reload of
3120                 // images.  Some images we may want to highlight the text.
3121                 readOnlyCache.clear();
3122                 inkNoteCache.clear();
3123                 noteCache.clear();
3124                 QWebSettings.setMaximumPagesInCache(0);
3125                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
3126         
3127                 searchField.setEditText("");
3128                 saveNoteColumnPositions();
3129                 saveNoteIndexWidth();
3130                 noteIndexUpdated(true);
3131                 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
3132                         currentNote = listManager.getNoteIndex().get(0);
3133                         currentNoteGuid = currentNote.getGuid();
3134                 }
3135                 refreshEvernoteNote(true);
3136                 if (currentNote != null)
3137                         loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
3138         }
3139         // text in the search bar changed.  We only use this to tell if it was cleared, 
3140         // otherwise we trigger off searchFieldChanged.
3141         @SuppressWarnings("unused")
3142         private void searchFieldTextChanged(String text) {
3143                 QWebSettings.setMaximumPagesInCache(0);
3144                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
3145
3146                 if (text.trim().equals("")) {
3147                         searchFieldCleared();
3148                         if (searchPerformed) {
3149
3150                                 // This is done because we want to force a reload of
3151                                 // images.  Some images we may want to highlight the text.
3152                                 noteCache.clear();
3153                                 readOnlyCache.clear();
3154                                 inkNoteCache.clear();
3155                                 
3156                                 listManager.setEnSearch("");
3157                                 listManager.loadNotesIndex();
3158                                 refreshEvernoteNote(true);
3159                                 noteIndexUpdated(false);
3160                                 refreshEvernoteNote(true);
3161                         }
3162                         searchPerformed = false;
3163                 }
3164         }
3165     // Text in the toolbar has changed
3166     private void searchFieldChanged() {
3167         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
3168         noteCache.clear();
3169         readOnlyCache.clear();
3170         inkNoteCache.clear();
3171         saveNoteColumnPositions();
3172         saveNoteIndexWidth();
3173         String text = searchField.currentText();
3174         listManager.setEnSearch(text.trim());
3175         listManager.loadNotesIndex();
3176         noteIndexUpdated(false);
3177
3178         refreshEvernoteNote(true);
3179         searchPerformed = true;
3180         waitCursor(false);
3181         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
3182     }
3183
3184     // Build the window tool bar
3185     private void setupToolBar() {
3186         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
3187         toolBar = addToolBar(tr("Tool Bar"));   
3188         toolBar.setObjectName("toolBar");
3189         toolBar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon);
3190         menuBar.setupToolBarVisible();
3191         if (!Global.isWindowVisible("toolBar"))
3192                 toolBar.setVisible(false);
3193         else
3194                 toolBar.setVisible(true);
3195
3196 //      toolBar.addWidget(menuBar);
3197 //      menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
3198 //      toolBar.addSeparator();
3199         prevButton = toolBar.addAction(tr(""));
3200         prevButton.setToolTip(tr("Previous"));
3201         QIcon prevIcon = new QIcon(iconPath+"back.png");
3202         prevButton.setIcon(prevIcon);
3203         prevButton.triggered.connect(this, "previousViewedAction()");   
3204         togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
3205         
3206         nextButton = toolBar.addAction(tr(""));
3207         nextButton.setToolTip(tr("Next"));
3208         QIcon nextIcon = new QIcon(iconPath+"forward.png");
3209         nextButton.setIcon(nextIcon);
3210         nextButton.triggered.connect(this, "nextViewedAction()");       
3211         toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
3212         
3213         toolBar.addSeparator();
3214         
3215         upButton = toolBar.addAction(tr("Up"));
3216         QIcon upIcon = new QIcon(iconPath+"up.png");
3217         upButton.setIcon(upIcon);
3218         upButton.triggered.connect(this, "upAction()");         
3219         toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
3220
3221         
3222         downButton = toolBar.addAction(tr("Down"));
3223         QIcon downIcon = new QIcon(iconPath+"down.png");
3224         downButton.setIcon(downIcon);
3225         downButton.triggered.connect(this, "downAction()");
3226         toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
3227         
3228         synchronizeButton = toolBar.addAction(tr("Synchronize"));
3229         synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
3230         synchronizeIconAngle = 0;
3231         synchronizeButton.triggered.connect(this, "evernoteSync()");
3232         toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
3233         
3234         printButton = toolBar.addAction(tr("Print"));
3235         QIcon printIcon = new QIcon(iconPath+"print.png");
3236         printButton.setIcon(printIcon);
3237         printButton.triggered.connect(this, "printNote()");
3238         togglePrintButton(Global.isToolbarButtonVisible("print"));
3239
3240         tagButton = toolBar.addAction(tr("Tag")); 
3241         QIcon tagIcon = new QIcon(iconPath+"tag.png");
3242         tagButton.setIcon(tagIcon);
3243         tagButton.triggered.connect(browserWindow, "modifyTags()");
3244         toggleTagButton(Global.isToolbarButtonVisible("tag"));
3245
3246         attributeButton = toolBar.addAction(tr("Attributes")); 
3247         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
3248         attributeButton.setIcon(attributeIcon);
3249         attributeButton.triggered.connect(this, "toggleNoteAttributes()");
3250         toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
3251                 
3252         emailButton = toolBar.addAction(tr("Email"));
3253         QIcon emailIcon = new QIcon(iconPath+"email.png");
3254         emailButton.setIcon(emailIcon);
3255         emailButton.triggered.connect(this, "emailNote()");
3256         toggleEmailButton(Global.isToolbarButtonVisible("email"));
3257
3258         deleteButton = toolBar.addAction(tr("Delete"));         
3259         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
3260         deleteButton.setIcon(deleteIcon);
3261         deleteButton.triggered.connect(this, "deleteNote()");
3262         toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
3263
3264         newButton = toolBar.addAction(tr("New"));
3265         QIcon newIcon = new QIcon(iconPath+"new.png");
3266         if (Global.toolBarNewAction()) {
3267                 newButton.triggered.connect(this, "noteAddNewTab()");
3268         } else {
3269                 newButton.triggered.connect(this, "addNote()");
3270         }
3271
3272         newButton.setIcon(newIcon);
3273         toggleNewButton(Global.isToolbarButtonVisible("new"));
3274         
3275         allNotesButton = toolBar.addAction(tr("All Notes"));
3276         QIcon allIcon = new QIcon(iconPath+"books.png");
3277         allNotesButton.triggered.connect(this, "allNotes()");
3278         allNotesButton.setIcon(allIcon);
3279         toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
3280         
3281         //toolBar.addSeparator();
3282         //toolBar.addWidget(new QLabel(tr("Quota:")));
3283         //toolBar.addWidget(quotaBar);
3284         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
3285         updateQuotaBar();
3286         //toolBar.addSeparator();
3287         
3288         //toolBar.addWidget(new QLabel(tr("Zoom")));
3289         //toolBar.addWidget(zoomSpinner);
3290         
3291         //toolBar.addWidget(new QLabel("                    "));
3292         //toolBar.addSeparator();
3293         //toolBar.addWidget(new QLabel(tr("  Search:")));
3294         //toolBar.addWidget(searchField);
3295         QSizePolicy sizePolicy = new QSizePolicy();
3296         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
3297         QLabel spacer = new QLabel("");
3298         spacer.setSizePolicy(sizePolicy);
3299         toolBar.addWidget(spacer);
3300         //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3301
3302         //searchClearButton = toolBar.addAction("Search Clear");
3303         //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3304         //searchClearButton.setIcon(searchClearIcon);
3305         //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3306         //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3307
3308         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3309     }
3310     // Update the sychronize button picture
3311     @Override
3312         public QMenu createPopupMenu() {
3313         QMenu contextMenu = super.createPopupMenu();
3314         
3315         contextMenu.addSeparator();
3316         QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3317         contextMenu.addAction(prevAction);
3318         prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3319
3320         QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3321         contextMenu.addAction(nextAction);
3322         nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3323
3324         QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3325         contextMenu.addAction(upAction);
3326         upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3327
3328         QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3329         contextMenu.addAction(downAction);
3330         downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3331
3332         QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3333         contextMenu.addAction(synchronizeAction);
3334         synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3335
3336         QAction printAction = addContextAction("print", tr("Print"));
3337         contextMenu.addAction(printAction);
3338         printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3339
3340         QAction tagAction = addContextAction("tag", tr("Tag"));
3341         contextMenu.addAction(tagAction);
3342         tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3343         
3344         QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3345         contextMenu.addAction(attributeAction);
3346         attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3347         
3348         QAction emailAction = addContextAction("email", tr("Email"));
3349         contextMenu.addAction(emailAction);
3350         emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3351
3352         QAction deleteAction = addContextAction("delete", tr("Delete"));
3353         contextMenu.addAction(deleteAction);
3354         deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3355
3356         QAction newAction = addContextAction("new", tr("Add"));
3357         contextMenu.addAction(newAction);
3358         newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3359
3360         QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3361         contextMenu.addAction(allNotesAction);
3362         allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3363         
3364         QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3365         contextMenu.addAction(searchClearAction);
3366         searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3367         
3368         return contextMenu;
3369         
3370     }
3371     private QAction addContextAction(String config, String name) {
3372         QAction newAction = new QAction(this);
3373                 newAction.setText(name);
3374                 newAction.setCheckable(true);
3375                 newAction.setChecked(Global.isToolbarButtonVisible(config));
3376                 return newAction;
3377     }
3378     private void togglePrevArrowButton(Boolean toggle) {
3379                 prevButton.setVisible(toggle);
3380                 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3381     }
3382     private void toggleNextArrowButton(Boolean toggle) {
3383                 nextButton.setVisible(toggle);
3384                 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3385     }
3386     private void toggleUpArrowButton(Boolean toggle) {
3387                 upButton.setVisible(toggle);
3388                 Global.saveToolbarButtonsVisible("upArrow", toggle);
3389     }
3390     private void toggleDownArrowButton(Boolean toggle) {
3391                 downButton.setVisible(toggle);
3392                 Global.saveToolbarButtonsVisible("downArrow", toggle);
3393     }
3394     private void toggleSynchronizeButton(Boolean toggle) {
3395                 synchronizeButton.setVisible(toggle);
3396                 Global.saveToolbarButtonsVisible("synchronize", toggle);
3397     }
3398     private void togglePrintButton(Boolean toggle) {
3399                 printButton.setVisible(toggle);
3400                 Global.saveToolbarButtonsVisible("print", toggle);
3401     }
3402     private void toggleTagButton(Boolean toggle) {
3403                 tagButton.setVisible(toggle);
3404                 Global.saveToolbarButtonsVisible("tag", toggle);
3405     }
3406     private void toggleAttributeButton(Boolean toggle) {
3407                 attributeButton.setVisible(toggle);
3408                 Global.saveToolbarButtonsVisible("attribute", toggle);
3409     }
3410     private void toggleEmailButton(Boolean toggle) {
3411                 emailButton.setVisible(toggle);
3412                 Global.saveToolbarButtonsVisible("email", toggle);
3413     }
3414     private void toggleDeleteButton(Boolean toggle) {
3415                 deleteButton.setVisible(toggle);
3416                 Global.saveToolbarButtonsVisible("delete", toggle);
3417     }
3418     private void toggleNewButton(Boolean toggle) {
3419                 newButton.setVisible(toggle);
3420                 Global.saveToolbarButtonsVisible("new", toggle);
3421     }
3422     private void toggleAllNotesButton(Boolean toggle) {
3423                 allNotesButton.setVisible(toggle);
3424                 Global.saveToolbarButtonsVisible("allNotes", toggle);
3425     }
3426     @SuppressWarnings("unused")
3427         private void toggleSearchClearButton(Boolean toggle) {
3428                 searchClearButton.setVisible(toggle);
3429                 Global.saveToolbarButtonsVisible("searchClear", toggle);
3430     }
3431
3432
3433
3434
3435
3436     @SuppressWarnings("unused")
3437         private void updateSyncButton() {
3438                 
3439         if (syncIcons == null) {
3440                 syncIcons = new ArrayList<QPixmap>();
3441                 double angle = 0.0;
3442                 synchronizeIconAngle = 0;
3443                 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3444                 syncIcons.add(pix);
3445                 for (int i=0; i<=360; i++) {
3446                         QPixmap rotatedPix = new QPixmap(pix.size());
3447                         QPainter p = new QPainter(rotatedPix);
3448                 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3449                 QSize size = pix.size();
3450                 p.translate(size.width()/2, size.height()/2);
3451                 angle = angle+1.0;
3452                 p.rotate(angle);
3453                 p.setBackgroundMode(BGMode.OpaqueMode);
3454                 p.translate(-size.width()/2, -size.height()/2);
3455                 p.drawPixmap(0,0, pix);
3456                 p.end();
3457                 syncIcons.add(rotatedPix);
3458                 }
3459         }
3460
3461         synchronizeIconAngle++;
3462         if (synchronizeIconAngle > 359)
3463                 synchronizeIconAngle=0;
3464         synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3465         
3466     }
3467     // Synchronize with Evernote
3468
3469         private void evernoteSync() {
3470         logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3471         if (!Global.isConnected)
3472                 remoteConnect();
3473         if (Global.isConnected)
3474                 synchronizeAnimationTimer.start(5);
3475 //                      synchronizeAnimationTimer.start(200);
3476         syncTimer();
3477         logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3478     }
3479     private void updateQuotaBar() {
3480         long limit = Global.getUploadLimit();
3481         long amount = Global.getUploadAmount();
3482         if (amount>0 && limit>0) {
3483                 int percent =(int)(amount*100/limit);
3484                 quotaBar.setValue(percent);
3485         } else 
3486                 quotaBar.setValue(0);
3487     }
3488         // Zoom changed
3489     @SuppressWarnings("unused")
3490         private void zoomChanged() {
3491         browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3492     }
3493
3494     //****************************************************************
3495     //****************************************************************
3496     //* System Tray functions
3497     //****************************************************************
3498     //****************************************************************
3499         private void trayToggleVisible() {
3500         if (isVisible()) {
3501                 hide();
3502         } else {
3503                 show();
3504                 if (windowMaximized)
3505                         showMaximized();
3506                 else
3507                         showNormal();
3508                 raise();
3509         }
3510     }
3511     @SuppressWarnings("unused")
3512         private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3513         if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3514                 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3515                 trayToggleVisible();
3516         }
3517     }
3518     
3519     
3520     //***************************************************************
3521     //***************************************************************
3522     //** These functions deal with the trash tree
3523     //***************************************************************
3524     //***************************************************************    
3525     // Setup the tree containing the trash.
3526     @SuppressWarnings("unused")
3527         private void trashTreeSelection() {     
3528         logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3529         
3530         clearNotebookFilter();
3531         clearTagFilter();
3532         clearAttributeFilter();
3533         clearSavedSearchFilter();
3534         
3535         String tempGuid = currentNoteGuid;
3536         
3537 //      currentNoteGuid = "";
3538         currentNote = new Note();
3539         selectedNoteGUIDs.clear();
3540         listManager.getSelectedNotebooks().clear();
3541         listManager.getSelectedTags().clear();
3542         listManager.setSelectedSavedSearch("");
3543         browserWindow.clear();
3544     
3545         // toggle the add buttons
3546         newButton.setEnabled(!newButton.isEnabled());
3547         menuBar.noteAdd.setEnabled(newButton.isEnabled());
3548         menuBar.noteAdd.setVisible(true);
3549         
3550         List<QTreeWidgetItem> selections = trashTree.selectedItems();
3551         if (selections.size() == 0) {
3552                 currentNoteGuid = trashNoteGuid;
3553                         trashNoteGuid = tempGuid;
3554                 Global.showDeleted = false;
3555                 menuBar.noteRestoreAction.setEnabled(false);
3556                 menuBar.noteRestoreAction.setVisible(false);
3557                         // ゴミ箱から元の画面に戻す。連想ノートリストをONに。
3558                         rensoNoteListDock.setEnabled(true);
3559         }
3560         else {
3561                 trashNoteGuid = tempGuid;
3562                 currentNoteGuid = trashNoteGuid;
3563                 menuBar.noteRestoreAction.setEnabled(true);
3564                 menuBar.noteRestoreAction.setVisible(true);
3565                 // ゴミ箱を開く。連想ノートリストをOFFに。
3566                 rensoNoteListDock.setEnabled(false);
3567                                         
3568                 Global.showDeleted = true;
3569         }
3570         
3571         menuBar.noteAddNewTab.setEnabled(newButton.isEnabled());
3572                 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3573                         menuBar.noteAddNewTab.setEnabled(false);
3574                 }
3575         
3576         listManager.loadNotesIndex();
3577         noteIndexUpdated(false);
3578 ////            browserWindow.setEnabled(newButton.isEnabled());
3579         browserWindow.setReadOnly(!newButton.isEnabled());
3580         logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3581     }
3582     // Empty the trash file
3583     @SuppressWarnings("unused")
3584         private void emptyTrash() {
3585 //      browserWindow.clear();
3586         logger.log(logger.EXTREME, "Emptying Trash");
3587         listManager.emptyTrash();
3588         logger.log(logger.EXTREME, "Resetting view after trash empty");
3589         if (trashTree.selectedItems().size() > 0) {
3590                 listManager.getSelectedNotebooks().clear();
3591                 listManager.getSelectedTags().clear();
3592                 listManager.setSelectedSavedSearch("");
3593                 newButton.setEnabled(!newButton.isEnabled());
3594                 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3595                 menuBar.noteAddNewTab.setEnabled(newButton.isEnabled());
3596                 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3597                         menuBar.noteAddNewTab.setEnabled(false);
3598                 }
3599                 menuBar.noteAdd.setVisible(true);
3600                 browserWindow.clear();
3601                 
3602                 clearTagFilter();
3603                 clearNotebookFilter();
3604                 clearSavedSearchFilter();
3605                 clearAttributeFilter();
3606                         
3607                 Global.showDeleted = false;
3608                 menuBar.noteRestoreAction.setEnabled(false);
3609                 menuBar.noteRestoreAction.setVisible(false);
3610                 
3611                 listManager.loadNotesIndex();
3612                 noteIndexUpdated(false);
3613                 
3614                 // ゴミ箱から元の画面に戻す。連想ノートリストをONに。
3615                 if (!rensoNoteListDock.isEnabled()) {
3616                         rensoNoteListDock.setEnabled(true);
3617                 }
3618         }       
3619    }
3620     // Show/Hide trash window
3621         @SuppressWarnings("unused")
3622         private void toggleTrashWindow() {
3623                 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3624         if (trashTree.isVisible())
3625                 trashTree.hide();
3626         else
3627                 trashTree.show();
3628         menuBar.hideTrash.setChecked(trashTree.isVisible());
3629         
3630                 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3631         logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3632     }    
3633         private void clearTrashFilter() {
3634                 Global.showDeleted = false;
3635         newButton.setEnabled(true);
3636         menuBar.noteAdd.setEnabled(true);
3637                 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3638                         menuBar.noteAddNewTab.setEnabled(false);
3639                 } else {
3640                         menuBar.noteAddNewTab.setEnabled(true);
3641                 }
3642         menuBar.noteAdd.setVisible(true);
3643                 trashTree.blockSignals(true);
3644                 trashTree.clearSelection();
3645                 trashTree.blockSignals(false);
3646                 
3647         }
3648     
3649    
3650     //***************************************************************
3651     //***************************************************************
3652     //** These functions deal with connection settings
3653     //***************************************************************
3654     //***************************************************************
3655         // SyncRunner had a problem and things are disconnected
3656         @SuppressWarnings("unused")
3657         private void remoteErrorDisconnect() {
3658                 menuBar.connectAction.setText(tr("Connect"));
3659                 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3660                 menuBar.synchronizeAction.setEnabled(false);
3661                 Global.isConnected = false;
3662                 synchronizeAnimationTimer.stop();
3663                 return;
3664         }
3665         // Do a manual connect/disconnect
3666     private void remoteConnect() {
3667         
3668         logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3669
3670         // If we are already connected, we just disconnect
3671         if (Global.isConnected) {
3672                 Global.isConnected = false;
3673                 syncRunner.enDisconnect();
3674                 setupConnectMenuOptions();
3675                 setupOnlineMenu();
3676                 return;
3677         }
3678         
3679         OAuthTokenizer tokenizer = new OAuthTokenizer();
3680         AESEncrypter aes = new AESEncrypter();
3681         try {
3682                         aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("oauth.txt")));
3683                 } catch (FileNotFoundException e) {
3684                         // File not found, so we'll just get empty strings anyway. 
3685                 }
3686         
3687                 
3688                 if (Global.getProxyValue("url").equals("")) {
3689                         System.setProperty("http.proxyHost","") ;
3690                         System.setProperty("http.proxyPort", "") ;
3691                         System.setProperty("https.proxyHost","") ;
3692                         System.setProperty("https.proxyPort", "") ;         
3693                 } else {
3694                         // PROXY
3695                         System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3696                         System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3697                         System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3698                         System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3699  
3700                         if (Global.getProxyValue("userid").equals("")) {
3701                                 Authenticator.setDefault(new Authenticator() {
3702                         @Override
3703                         protected PasswordAuthentication getPasswordAuthentication() {
3704                                 return new
3705                                 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3706                                 }
3707                         });
3708                 }
3709         }
3710
3711                 syncRunner.userStoreUrl = Global.userStoreUrl;
3712                 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3713                 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3714                 
3715                 
3716                 
3717                 String authString = aes.getString();
3718                 if (!authString.equals("")) {
3719                         tokenizer.tokenize(authString);
3720                         syncRunner.authToken = tokenizer.oauth_token;
3721                 syncRunner.enConnect();
3722                 }               
3723
3724                 Global.isConnected = syncRunner.isConnected;
3725                 
3726                 boolean autoLoginMessageFlag = false;
3727                 if (!Global.isConnected) {
3728                 OAuthWindow window = new OAuthWindow(logger);
3729                 if (window.error) {
3730                         setMessage(window.errorMessage);
3731                         return;
3732                 }
3733                 window.exec();
3734                 if (window.error) {
3735                         setMessage(window.errorMessage);
3736                         return;
3737                         }
3738                 tokenizer.tokenize(window.response);
3739                 if (tokenizer.oauth_token.equals("")) {
3740                         setMessage(tr("Invalid authorization token received."));
3741                         return;
3742                 }
3743                 aes.setString(window.response);
3744                 try {
3745                                 aes.encrypt(new FileOutputStream(Global.getFileManager().getHomeDirFile("oauth.txt")));
3746                         } catch (FileNotFoundException e) {
3747                                 // TODO Auto-generated catch block
3748                                 e.printStackTrace();
3749                         }
3750                 syncRunner.authToken = tokenizer.oauth_token;
3751                         syncRunner.enConnect();
3752                         Global.isConnected = syncRunner.isConnected;
3753                         autoLoginMessageFlag = true;
3754                 }
3755 //              Global.username = syncRunner.username;
3756                         
3757                 if (!Global.isConnected)
3758                         return;
3759                 setupOnlineMenu();
3760                 setupConnectMenuOptions();
3761                 
3762                 // 初回ログイン時に自動ログインが無効だったら、有効化するか確認する
3763                 if (autoLoginMessageFlag && !Global.automaticLogin()) {
3764                         if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure you want to enable the auto-login feature?"), 
3765                                         QMessageBox.StandardButton.Yes, QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
3766                                 Global.setAutomaticLogin(true);
3767                         }
3768                 }
3769                 
3770                 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3771     }
3772     private void setupConnectMenuOptions() {
3773         logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3774                 if (!Global.isConnected) {
3775                         menuBar.connectAction.setText(tr("Connect"));
3776                         menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3777                         menuBar.synchronizeAction.setEnabled(false);
3778                 } else {
3779                         menuBar.connectAction.setText(tr("Disconnect"));
3780                         menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3781                         menuBar.synchronizeAction.setEnabled(true);
3782                 }
3783                 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3784     }
3785     
3786     
3787     
3788     //***************************************************************
3789     //***************************************************************
3790     //** These functions deal with the GUI Attribute tree
3791     //***************************************************************
3792     //***************************************************************    
3793     @SuppressWarnings("unused")
3794         private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3795         
3796 //      clearTagFilter();
3797 //      clearNotebookFilter();
3798         clearTrashFilter();
3799 //      clearSavedSearchFilter();
3800         
3801                 // ゴミ箱から元の画面に戻す。連想ノートリストをONに。
3802                 if (!rensoNoteListDock.isEnabled()) {
3803                         rensoNoteListDock.setEnabled(true);
3804                 }
3805
3806         if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3807                 if (item.childCount() > 0) {
3808                         item.setSelected(false);
3809                 } else {
3810                 Global.createdBeforeFilter.reset();
3811                 Global.createdSinceFilter.reset();
3812                 Global.changedBeforeFilter.reset();
3813                 Global.changedSinceFilter.reset();
3814                 Global.containsFilter.reset();
3815                         attributeTreeSelected = item;
3816                         DateAttributeFilterTable f = null;
3817                         f = findDateAttributeFilterTable(item.parent());
3818                         if (f!=null)
3819                                 f.select(item.parent().indexOfChild(item));
3820                         else {
3821                                 Global.containsFilter.select(item.parent().indexOfChild(item));
3822                         }
3823                 }
3824                 listManager.loadNotesIndex();
3825                 noteIndexUpdated(false);
3826                 return;
3827         }
3828                 attributeTreeSelected = null;
3829                 item.setSelected(false);
3830         Global.createdBeforeFilter.reset();
3831         Global.createdSinceFilter.reset();
3832         Global.changedBeforeFilter.reset();
3833         Global.changedSinceFilter.reset();
3834         Global.containsFilter.reset();
3835         listManager.loadNotesIndex();
3836                 noteIndexUpdated(false); 
3837     }
3838     // This determines what attribute filter we need, depending upon the selection
3839     private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3840                 if (w.parent() != null && w.childCount() > 0) {
3841                         QTreeWidgetItem parent = w.parent();
3842                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created && 
3843                                 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3844                                         return Global.createdSinceFilter;
3845                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created && 
3846                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3847                                         return Global.createdBeforeFilter;
3848                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified && 
3849                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3850                                         return Global.changedSinceFilter;
3851                 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified && 
3852                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3853                                                 return Global.changedBeforeFilter;
3854                 }
3855                 return null;
3856     }
3857
3858     // Show/Hide attribute search window
3859         @SuppressWarnings("unused")
3860         private void toggleAttributesWindow() {
3861                 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3862         if (attributeTree.isVisible())
3863                 attributeTree.hide();
3864         else
3865                 attributeTree.show();
3866         menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3867         
3868                 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3869         logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3870     }    
3871         private void clearAttributeFilter() {
3872         Global.createdBeforeFilter.reset();
3873         Global.createdSinceFilter.reset();
3874         Global.changedBeforeFilter.reset();
3875         Global.changedSinceFilter.reset();
3876         Global.containsFilter.reset();
3877         attributeTreeSelected = null;
3878                 attributeTree.blockSignals(true);
3879                 attributeTree.clearSelection();
3880                 attributeTree.blockSignals(false);
3881         }
3882     
3883         
3884     //***************************************************************
3885     //***************************************************************
3886     //** These functions deal with the GUI Note index table
3887     //***************************************************************
3888     //***************************************************************    
3889     // Initialize the note list table
3890         private void initializeNoteTable() {
3891                 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3892                 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3893                 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3894                 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3895         }       
3896     // Show/Hide trash window
3897         @SuppressWarnings("unused")
3898         private void toggleNoteListWindow() {
3899                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3900         if (noteTableView.isVisible())
3901                 noteTableView.hide();
3902         else
3903                 noteTableView.show();
3904         menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3905         
3906                 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3907         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3908     }   
3909         // Handle the event that a user selects a note from the table
3910     @SuppressWarnings("unused")
3911         private void noteTableSelection() {
3912                 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3913
3914                 saveNote();
3915                 
3916                 // 右クリックだったときの処理
3917                 if (QApplication.mouseButtons().isSet(MouseButton.RightButton)) {
3918                         // 選択されたノートのguidをselectedNoteGUIDsにセット
3919                         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3920                         if(selections.size() > 0){
3921                                 selectedNoteGUIDs.clear();
3922                                 for(int i = 0; i < selections.size(); i++){
3923                                         int row = selections.get(i).row();
3924                                         QModelIndex index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3925                                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3926                                         selectedNoteGUIDs.add((String) ix.values().toArray()[0]);
3927                                 }
3928                         }
3929                         return;
3930                 }
3931                 
3932                 // If we have more than one selection, then set the merge note action to true.
3933         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3934                 if (selections.size() > 1) 
3935                 menuBar.noteMergeAction.setEnabled(true);
3936                 else
3937                         menuBar.noteMergeAction.setEnabled(false);
3938
3939                 // If the ctrl key is pressed, then they are selecting multiple 
3940                 // entries and we don't want to change the currently viewed note.
3941                 // Shiftキーを押しながらの場合の処理も追加
3942                 if ((QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) ||
3943                                 QApplication.keyboardModifiers().isSet(KeyboardModifier.ShiftModifier)) &&
3944                                 QApplication.mouseButtons().isSet(MouseButton.LeftButton)){
3945                         selectedNoteGUIDs.clear();
3946                 for (int i=0; i<selections.size(); i++) {
3947                         int row = selections.get(i).row();
3948                         QModelIndex index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3949                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3950                         selectedNoteGUIDs.add((String)ix.values().toArray()[0]);
3951                 }
3952                         return;
3953                 }
3954                 
3955                 // IFIXED 恐らく不要なのでコメントアウト
3956 //              if (historyGuids.size() == 0) {
3957 //                      historyGuids.add(currentNoteGuid);
3958 //                      historyPosition = 1;
3959 //              }
3960
3961         noteTableView.showColumn(Global.noteTableGuidPosition);
3962         
3963         if (!Global.isColumnVisible("guid"))
3964                 noteTableView.hideColumn(Global.noteTableGuidPosition);
3965         
3966         if (selections.size() > 0) {
3967                 QModelIndex index;
3968                 menuBar.noteDuplicateAction.setEnabled(true);
3969                 menuBar.noteOnlineHistoryAction.setEnabled(true);
3970                 menuBar.noteMergeAction.setEnabled(true);
3971                 selectedNoteGUIDs.clear();
3972                 if (currentNoteGuid != null && !currentNoteGuid.equals("") && !Global.showDeleted) {
3973                         menuBar.noteAddNewTab.setEnabled(true);
3974                 }
3975                 if (selections.size() != 1 || Global.showDeleted) {
3976                         menuBar.noteDuplicateAction.setEnabled(false);
3977                 }
3978                 if (selections.size() != 1 || !Global.isConnected) {
3979                         menuBar.noteOnlineHistoryAction.setEnabled(false);
3980                 }
3981                 if (selections.size() == 1) {
3982                         menuBar.noteMergeAction.setEnabled(false);
3983                 }
3984                 for (int i=0; i<selections.size(); i++) {
3985                         int row = selections.get(i).row();
3986                         if (row == 0) 
3987                                 upButton.setEnabled(false);
3988                         else
3989                                 upButton.setEnabled(true);
3990                         if (row < listManager.getNoteTableModel().rowCount()-1)
3991                                 downButton.setEnabled(true);
3992                         else
3993                                 downButton.setEnabled(false);
3994                         index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3995                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3996                                 
3997                         currentNoteGuid = (String)ix.values().toArray()[0];                     
3998                         selectedNoteGUIDs.add(currentNoteGuid);
3999                 }
4000         }
4001         
4002         nextButton.setEnabled(true);
4003                 prevButton.setEnabled(true);
4004                 
4005                 int currentIndex = tabBrowser.currentIndex();
4006                 ArrayList<String> histGuids = historyGuids.get(currentIndex);
4007                 int histPosition = historyPosition.get(currentIndex);
4008                 boolean fromHist = fromHistory.get(currentIndex);
4009                 
4010                 if (!fromHist) {
4011                         int endPosition = histGuids.size() - 1;
4012
4013                         for (int j = histPosition; j <= endPosition; j++) {
4014                                 histGuids.remove(histGuids.size() - 1);
4015                         }
4016                         histGuids.add(currentNoteGuid);
4017                         historyPosition.put(currentIndex, histGuids.size());
4018                         histPosition = histGuids.size();
4019                 }
4020                 if (histPosition <= 1){
4021                         prevButton.setEnabled(false);
4022                 }
4023                 if (histPosition == histGuids.size())
4024                         nextButton.setEnabled(false);
4025                 fromHistory.put(currentIndex, false);
4026                 fromHist = false;
4027                 
4028         scrollToGuid(currentNoteGuid);
4029         refreshEvernoteNote(true);
4030         
4031                 if (currentNoteGuid != null && !currentNoteGuid.equals("")) {
4032                         if (!Global.showDeleted) { // ゴミ箱じゃなければ
4033                                 addBrowseHistory();
4034                         }
4035                 }
4036
4037                 // 連想ノートリストを更新
4038                 rensoNoteListDock.getRensoNoteList().refreshRensoNoteList(currentNoteGuid);
4039                 
4040                 waitCursor(false);
4041                 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
4042     }
4043     
4044     // 複数ノートの同時閲覧履歴をデータベースに保存
4045         private void addBrowseHistory() {
4046                 // このノートと他のタブウィンドウノートの関連性を内部データベースのHistoryテーブルに登録
4047                 if (tabWindows.size() >= 2) {
4048                         Iterator<Integer> it = tabWindows.keySet().iterator();
4049                         while (it.hasNext()) {
4050                                 int tabIndex = it.next();
4051                                 String nextGuid = ((TabBrowse) tabBrowser.widget(tabIndex)).getBrowserWindow().getNote().getGuid();
4052                                 // guid1=guid2のデータは登録しない
4053                                 if (!currentNoteGuid.equals(nextGuid)) {
4054                                         conn.getHistoryTable().addHistory("browse", currentNoteGuid, nextGuid);
4055                                 }
4056                         }
4057                 }
4058                 // このノートと他の外部ウィンドウノートの関連性を内部データベースのHistoryテーブルに登録
4059                 if (externalWindows.size() >= 1) {
4060                         Iterator<String> it = externalWindows.keySet().iterator();
4061                         while (it.hasNext()) {
4062                                 String nextGuid = it.next();
4063                                 // guid1=guid2のデータは登録しない
4064                                 if (!currentNoteGuid.equals(nextGuid)) {
4065                                         conn.getHistoryTable().addHistory("browse", currentNoteGuid, nextGuid);
4066                                 }
4067                         }
4068                 }
4069         }
4070         
4071         // Trigger a refresh when the note db has been updated
4072         private void noteIndexUpdated(boolean reload) {
4073                 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
4074                 saveNote();
4075         refreshEvernoteNoteList();
4076         logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
4077         noteTableView.load(reload);
4078         if (currentNoteGuid == null || currentNoteGuid.equals("")) {
4079                 int pos;
4080                 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
4081                         pos = noteTableView.proxyModel.rowCount();
4082                 else 
4083                         pos = 1;
4084                 if (noteTableView.proxyModel.rowCount() == 0)
4085                         pos = 0;
4086                 if (pos>0)      {
4087                         QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
4088                         if (i!=null) {
4089                                 currentNoteGuid = (String)i.data();
4090                         }
4091                 }
4092         }               
4093                 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
4094                         showColumns();
4095                 scrollToGuid(currentNoteGuid);
4096                 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
4097     }
4098         // Called when the list of notes is updated
4099     private void refreshEvernoteNoteList() {
4100         logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
4101         browserWindow.setDisabled(false);
4102                 if (selectedNoteGUIDs == null)
4103                         selectedNoteGUIDs = new ArrayList<String>();
4104                 selectedNoteGUIDs.clear();  // clear out old entries
4105                 
4106                 String saveCurrentNoteGuid = new String();
4107                 String tempNoteGuid = new String();
4108                 
4109                 int currentIndex = tabBrowser.currentIndex();
4110                 ArrayList<String> histGuids = historyGuids.get(currentIndex);
4111                 histGuids.clear();
4112                 historyPosition.put(currentIndex, 0);
4113                 
4114                 prevButton.setEnabled(false);
4115                 nextButton.setEnabled(false);
4116                 
4117                 if (currentNoteGuid == null) 
4118                         currentNoteGuid = new String();
4119                 
4120                 //determine current note guid
4121                 for (Note note : listManager.getNoteIndex()) {
4122                         tempNoteGuid = note.getGuid();
4123                         if (currentNoteGuid.equals(tempNoteGuid)) {
4124                                 saveCurrentNoteGuid = tempNoteGuid;
4125                         }
4126                 }
4127                 
4128                 if (listManager.getNoteIndex().size() == 0) {
4129                         currentNoteGuid = "";
4130                         currentNote = null;
4131                         browserWindow.clear();
4132                         browserWindow.setDisabled(true);
4133                         waitCursor(false);
4134                 } 
4135                 
4136                 if (Global.showDeleted && listManager.getNoteIndex().size() > 0 && saveCurrentNoteGuid.equals("")) {
4137                         currentNoteGuid = listManager.getNoteIndex().get(0).getGuid();
4138                         saveCurrentNoteGuid = currentNoteGuid;
4139                         refreshEvernoteNote(true);
4140                 }
4141                 
4142                 if (!saveCurrentNoteGuid.equals("")) {
4143                         refreshEvernoteNote(false);
4144                 } else {
4145                                 currentNoteGuid = "";
4146                 }
4147                 reloadTagTree(false);
4148
4149                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
4150         } 
4151     
4152         // Called when the previous arrow button is clicked
4153         @SuppressWarnings("unused")
4154         private void previousViewedAction() {
4155                 int currentIndex = tabBrowser.currentIndex();
4156                 ArrayList<String> histGuids = historyGuids.get(currentIndex);
4157                 int histPosition = historyPosition.get(currentIndex);
4158                 boolean fromHist = fromHistory.get(currentIndex);
4159                 if (!prevButton.isEnabled())
4160                         return;
4161                 if (histPosition == 0)
4162                         return;
4163                 histPosition--;
4164                 historyPosition.put(currentIndex, histPosition);
4165                 if (histPosition <= 0)
4166                         return;
4167                 String historyGuid = histGuids.get(histPosition - 1);
4168                 fromHistory.put(currentIndex, true);
4169                 fromHist = true;
4170                 for (int i = 0; i < noteTableView.model().rowCount(); i++) {
4171                         QModelIndex modelIndex = noteTableView.model().index(i,
4172                                         Global.noteTableGuidPosition);
4173                         if (modelIndex != null) {
4174                                 SortedMap<Integer, Object> ix = noteTableView.model().itemData(
4175                                                 modelIndex);
4176                                 String tableGuid = (String) ix.values().toArray()[0];
4177                                 if (tableGuid.equals(historyGuid)) {
4178                                         noteTableView.selectRow(i);
4179                                         return;
4180                                 }
4181                         }
4182                 }
4183         }
4184         
4185     @SuppressWarnings("unused")
4186         private void nextViewedAction() {
4187         if (!nextButton.isEnabled())
4188                 return;
4189         
4190                 int currentIndex = tabBrowser.currentIndex();
4191                 ArrayList<String> histGuids = historyGuids.get(currentIndex);
4192                 int histPosition = historyPosition.get(currentIndex);
4193                 boolean fromHist = fromHistory.get(currentIndex);
4194                 String historyGuid = histGuids.get(histPosition);
4195                 histPosition++;
4196                 historyPosition.put(currentIndex, histPosition);
4197                 fromHistory.put(currentIndex, true);
4198                 fromHist = true;
4199                 for (int i = 0; i < noteTableView.model().rowCount(); i++) {
4200                         QModelIndex modelIndex = noteTableView.model().index(i,
4201                                         Global.noteTableGuidPosition);
4202                         if (modelIndex != null) {
4203                                 SortedMap<Integer, Object> ix = noteTableView.model().itemData(
4204                                                 modelIndex);
4205                                 String tableGuid = (String) ix.values().toArray()[0];
4206                                 if (tableGuid.equals(historyGuid)) {
4207                                         noteTableView.selectRow(i);
4208                                         return;
4209                                 }
4210                         }
4211                 }
4212     }
4213     // Called when the up arrow is clicked 
4214     @SuppressWarnings("unused")
4215         private void upAction() {
4216         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
4217         int row = selections.get(0).row();
4218         if (row > 0) {
4219                 noteTableView.selectRow(row-1);
4220         }
4221     }
4222     // Called when the down arrow is clicked 
4223     @SuppressWarnings("unused")
4224         private void downAction() {
4225         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
4226         int row = selections.get(0).row();
4227         int max = listManager.getNoteTableModel().rowCount();
4228         if (row < max-1) {
4229                 noteTableView.selectRow(row+1);
4230         }
4231     }
4232     // Update a tag string for a specific note in the list
4233     @SuppressWarnings("unused")
4234         private void updateListTags(String guid, List<String> tags) {
4235         logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
4236         StringBuffer tagBuffer = new StringBuffer();
4237         for (int i=0; i<tags.size(); i++) {
4238                 tagBuffer.append(tags.get(i));
4239                 if (i<tags.size()-1)
4240                         tagBuffer.append(", ");
4241         }
4242         
4243         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4244                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4245                 if (modelIndex != null) {
4246                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4247                         String tableGuid =  (String)ix.values().toArray()[0];
4248                         if (tableGuid.equals(guid)) {
4249                                 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
4250                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4251                                 noteTableView.proxyModel.invalidate();
4252                                 return;
4253                         }
4254                 }
4255         }
4256         logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
4257     }
4258     // Update a title for a specific note in the list
4259     @SuppressWarnings("unused")
4260         private void updateListAuthor(String guid, String author) {
4261         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
4262
4263         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4264                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
4265                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4266                 if (modelIndex != null) {
4267                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4268                         String tableGuid =  (String)ix.values().toArray()[0];
4269                         if (tableGuid.equals(guid)) {
4270                                 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
4271                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4272                                 noteTableView.proxyModel.invalidate();
4273                                 return;
4274                         }       
4275                 }
4276         }
4277         
4278         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
4279     }
4280         private void updateListNoteNotebook(String guid, String notebook) {
4281         logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
4282         listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
4283         logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
4284     }
4285     // Update a title for a specific note in the list
4286     @SuppressWarnings("unused")
4287         private void updateListSourceUrl(String guid, String url) {
4288         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
4289
4290         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4291                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
4292                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4293                 if (modelIndex != null) {
4294 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
4295                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4296                         String tableGuid =  (String)ix.values().toArray()[0];
4297                         if (tableGuid.equals(guid)) {
4298                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4299                                 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
4300                                 noteTableView.proxyModel.invalidate();
4301                                 return;
4302                         }       
4303                 }
4304         }
4305         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
4306     }
4307         @SuppressWarnings("unused")
4308         private void updateListGuid(String oldGuid, String newGuid) {
4309         logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
4310
4311         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4312                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4313                 if (modelIndex != null) {
4314                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4315                         String tableGuid =  (String)ix.values().toArray()[0];
4316                         if (tableGuid.equals(oldGuid)) {
4317                                 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
4318                                 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4319                                 return;
4320                         }       
4321                 }
4322         }
4323         logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
4324     }
4325         private void updateListTagName(String guid) {
4326         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
4327                 
4328                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
4329                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
4330                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
4331
4332                                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4333                                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4334                                         if (modelIndex != null) {
4335                                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4336                                                 String noteGuid = (String)ix.values().toArray()[0];
4337                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
4338                                                         listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
4339                                                         i=listManager.getNoteTableModel().rowCount();
4340                                                 }
4341                                         }
4342                                 }
4343                         }
4344                 }       
4345         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
4346     }
4347         private void removeListTagName(String guid) {
4348         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
4349                 
4350                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
4351                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
4352                                 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
4353                                         if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
4354                                                 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
4355                                 }
4356                                 
4357                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
4358                                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4359                                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4360                                         if (modelIndex != null) {
4361                                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4362                                                 String noteGuid = (String)ix.values().toArray()[0];
4363                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
4364                                                         listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
4365                                                         i=listManager.getNoteTableModel().rowCount();
4366                                                 }
4367                                         }
4368                                 }
4369                         }
4370                 }       
4371         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
4372     }
4373     private void updateListNotebookName(String oldName, String newName) {
4374         logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
4375
4376         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4377                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition); 
4378                 if (modelIndex != null) {
4379                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4380                         String tableName =  (String)ix.values().toArray()[0];
4381                         if (tableName.equalsIgnoreCase(oldName)) {
4382                                 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
4383                         }
4384                 }
4385         }
4386         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
4387     }
4388     @SuppressWarnings("unused")
4389         private void updateListDateCreated(String guid, QDateTime date) {
4390         logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
4391
4392         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4393                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4394                 if (modelIndex != null) {
4395                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4396                         String tableGuid =  (String)ix.values().toArray()[0];
4397                         if (tableGuid.equals(guid)) {
4398                                 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4399                                 noteTableView.proxyModel.invalidate();
4400                                 return;
4401                         }
4402                 }
4403         }
4404         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
4405     }
4406     @SuppressWarnings("unused")
4407         private void updateListDateSubject(String guid, QDateTime date) {
4408         logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
4409
4410         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4411                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4412                 if (modelIndex != null) {
4413                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4414                         String tableGuid =  (String)ix.values().toArray()[0];
4415                         if (tableGuid.equals(guid)) {
4416                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4417                                 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4418                                 noteTableView.proxyModel.invalidate();
4419                                 return;
4420                         }
4421                 }
4422         }
4423         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
4424     }
4425         private void updateListDateChanged(String guid, QDateTime date) {
4426         logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
4427
4428         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4429                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4430                 if (modelIndex != null) {
4431                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4432                         String tableGuid =  (String)ix.values().toArray()[0];
4433                         if (tableGuid.equals(guid)) {
4434                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4435                                 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4436                                 return;
4437                         }
4438                 }
4439         }
4440         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4441     }
4442     private void updateListDateChanged() {
4443         logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
4444         QDateTime date = new QDateTime(QDateTime.currentDateTime());
4445         updateListDateChanged(currentNoteGuid, date);
4446         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4447     }  
4448     // Redo scroll
4449         private void scrollToCurrentGuid() {
4450         //scrollToGuid(currentNoteGuid);
4451         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
4452         if (selections.size() == 0)
4453                 return;
4454         QModelIndex index = selections.get(0);
4455         int row = selections.get(0).row();
4456         String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
4457         scrollToGuid(guid);
4458     }
4459         // Scroll to the current GUID in tthe list.
4460     // Scroll to a particular index item
4461     private void scrollToGuid(String guid) {
4462         if (currentNote == null || guid == null) 
4463                 return;
4464         if (currentNote.isActive() && Global.showDeleted) {
4465                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4466                         if (!listManager.getNoteIndex().get(i).isActive()) {
4467                                 currentNote = listManager.getNoteIndex().get(i);
4468                                 currentNoteGuid =  currentNote.getGuid();
4469                                 i = listManager.getNoteIndex().size();
4470                         }
4471                 }
4472         }
4473         if (!currentNote.isActive() && !Global.showDeleted) {
4474                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4475                         if (listManager.getNoteIndex().get(i).isActive()) {
4476                                 currentNote = listManager.getNoteIndex().get(i);
4477                                 currentNoteGuid =  currentNote.getGuid();
4478                                 i = listManager.getNoteIndex().size();
4479                         }
4480                 }
4481         }
4482         QModelIndex index; 
4483         for (int i=0; i<noteTableView.model().rowCount(); i++) {
4484                 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4485                 if (currentNoteGuid.equals(index.data())) {
4486 //                      noteTableView.selectionModel().blockSignals(true);
4487                         noteTableView.selectRow(i);
4488 //                              noteTableView.selectionModel().blockSignals(false);
4489                         noteTableView.scrollTo(index, ScrollHint.EnsureVisible);  // This should work, but it doesn't
4490                                 i=listManager.getNoteTableModel().rowCount();
4491                 }
4492         }
4493         noteTableView.repaint();
4494     }
4495     // Show/Hide columns
4496     private void showColumns() {
4497                 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4498                 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4499                 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4500                 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4501                 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4502                 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4503                 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4504                 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4505                 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4506                 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4507                 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));         
4508                 noteTableView.setColumnHidden(Global.noteTablePinnedPosition, !Global.isColumnVisible("pinned")); 
4509     }
4510     // Title color has changed
4511     @SuppressWarnings("unused")
4512         private void titleColorChanged(Integer color) {
4513         logger.log(logger.HIGH, "Entering NeverNote.titleColorChanged");
4514
4515         setNoteDirty();
4516         QColor backgroundColor = new QColor();
4517                 QColor foregroundColor = new QColor(QColor.black);
4518                 backgroundColor.setRgb(color);
4519                 
4520                 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4521                         foregroundColor.setRgb(QColor.white.rgb());
4522         
4523                 if (selectedNoteGUIDs.size() == 0)
4524                         selectedNoteGUIDs.add(currentNoteGuid);
4525                 
4526         for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4527                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4528                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4529                         if (modelIndex != null) {
4530                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4531                                 String tableGuid =  (String)ix.values().toArray()[0];
4532                                 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4533                                         for (int k=0; k<Global.noteTableColumnCount; k++) {
4534                                                 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4535                                                 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4536                                                 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4537                                         }
4538                                         i=listManager.getNoteTableModel().rowCount();
4539                                 }
4540                         }
4541                 }
4542         }
4543         logger.log(logger.HIGH, "Leaving NeverNote.titleColorChanged");
4544     }
4545     // A note has been pinned or unpinned
4546         @SuppressWarnings("unused")
4547         private void notePinned() {
4548                 logger.log(logger.EXTREME, "Entering NeverNote.notePinned()");
4549                 setNoteDirty();
4550
4551         for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4552                 NoteMetadata meta = listManager.getNoteMetadata().get(selectedNoteGUIDs.get(j));
4553                 boolean pinned = !meta.isPinned();
4554                 meta.setPinned(pinned);   // Toggle the pinned/unpinned 
4555                 
4556                 // Update the list & table
4557                 listManager.updateNoteMetadata(meta);   
4558                 noteTableView.proxyModel.addGuid(selectedNoteGUIDs.get(j), meta);
4559         }
4560                 logger.log(logger.EXTREME, "Leaving NeverNote.notePinned()");
4561     }
4562     // Wide list was chosen
4563     public void narrowListView() {
4564         saveNoteColumnPositions();
4565         saveNoteIndexWidth();
4566         saveWindowState();
4567                 int sortCol = noteTableView.proxyModel.sortColumn();
4568                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4569                 Global.setSortColumn(sortCol);
4570                 Global.setSortOrder(sortOrder);
4571
4572                 Global.setListView(Global.View_List_Narrow);
4573         
4574         menuBar.wideListView.blockSignals(true);
4575         menuBar.narrowListView.blockSignals(true);
4576         
4577         menuBar.wideListView.setChecked(false);
4578         menuBar.narrowListView.setChecked(true);
4579         
4580         menuBar.wideListView.blockSignals(false);
4581         menuBar.narrowListView.blockSignals(false);
4582         
4583         mainLeftRightSplitter.addWidget(noteTableView);
4584         mainLeftRightSplitter.addWidget(tabBrowser);
4585         
4586         restoreWindowState(false);
4587         noteTableView.repositionColumns();
4588         noteTableView.resizeColumnWidths();
4589         noteTableView.resizeRowHeights();
4590         
4591         sortCol = Global.getSortColumn();
4592                 sortOrder = Global.getSortOrder();
4593                 noteTableView.proxyModel.blocked = true;
4594                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4595                 noteTableView.proxyModel.blocked = false;
4596
4597                 
4598         showColumns();
4599         noteTableView.load(false);
4600         refreshEvernoteNote(true);
4601         scrollToCurrentGuid();
4602     }
4603     public void wideListView() {
4604                 int sortCol = noteTableView.proxyModel.sortColumn();
4605                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4606                 Global.setSortColumn(sortCol);
4607                 Global.setSortOrder(sortOrder);
4608
4609                 saveWindowState();
4610         saveNoteColumnPositions();
4611         saveNoteIndexWidth();
4612         Global.setListView(Global.View_List_Wide);
4613
4614         menuBar.wideListView.blockSignals(true);
4615         menuBar.narrowListView.blockSignals(true);
4616         
4617         menuBar.wideListView.setChecked(true);
4618         menuBar.narrowListView.setChecked(false);
4619
4620         menuBar.wideListView.blockSignals(false);
4621         menuBar.narrowListView.blockSignals(false);
4622         browserIndexSplitter.setVisible(true);
4623         browserIndexSplitter.addWidget(noteTableView);
4624                 browserIndexSplitter.addWidget(tabBrowser);
4625                 
4626         restoreWindowState(false);
4627         noteTableView.repositionColumns();
4628         noteTableView.resizeColumnWidths();
4629         noteTableView.resizeRowHeights();
4630         
4631         sortCol = Global.getSortColumn();
4632                 sortOrder = Global.getSortOrder();
4633                 noteTableView.proxyModel.blocked = true;
4634                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4635                 noteTableView.proxyModel.blocked = false;
4636
4637         showColumns();
4638         noteTableView.load(false);
4639         scrollToCurrentGuid();
4640     }
4641     // Sort order for the notebook has changed   
4642     public void tableSortOrderChanged(Integer column, Integer order) {
4643         
4644         // Find what notebook (if any) is selected.  We ignore stacks & the "All Notebooks".
4645         List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4646         if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4647                 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4648                 String notebook;
4649                 notebook = currentSelectedNotebook.text(2);
4650                 conn.getNotebookTable().setSortOrder(notebook, column, order);
4651         }       
4652     }
4653     
4654     //***************************************************************
4655     @SuppressWarnings("unused")
4656         private void evernoteLinkClick(String syncGuid, String locGuid) {
4657         String guid = null;
4658         if (conn.getNoteTable().guidExists(syncGuid)) {
4659                 guid = syncGuid;
4660         } else {
4661                 // If we didn't find it via the synchronized guid, look under the local guid
4662                 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was 
4663                 // later synchronized (that causes the guid to change so we need to find the new one).
4664                 if (conn.getNoteTable().guidExists(locGuid)) 
4665                         guid = locGuid;
4666                 else
4667                         guid = conn.getNoteTable().findAlternateGuid(locGuid);
4668         }
4669                 if (guid != null) {
4670                         openExternalEditor(guid);
4671                         return;
4672                 }
4673         
4674         //If we've gotten this far, we can't find the note
4675         QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4676                         " seem to find that note."));
4677     }
4678     //***************************************************************
4679     //***************************************************************
4680     //** External editor window functions                    
4681     //***************************************************************
4682     //***************************************************************
4683         private void listDoubleClick() {
4684                 saveNote();
4685         openExternalEditor(currentNoteGuid);
4686     }
4687     private void openExternalEditor(String guid) {
4688         
4689         if (externalWindows.containsKey(guid)) {
4690                 externalWindows.get(guid).raise();
4691                 return;
4692         }
4693         
4694         Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4695         // We have a new external editor to create
4696         QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4697         ExternalBrowse newBrowser = new ExternalBrowse(conn, cbObserver);
4698         
4699         newBrowser.setWindowIcon(appIcon);
4700         externalWindows.put(guid, newBrowser);
4701         showEditorButtons(newBrowser.getBrowserWindow());
4702         loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4703         setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4704         newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4705         //newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4706         newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4707         newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4708         newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4709         newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4710
4711         browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4712         browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4713         browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4714         
4715         newBrowser.show();
4716     }
4717     @SuppressWarnings({ "rawtypes", "unused" })
4718         private void externalWindowTagsEdited(String guid, List values) {
4719         StringBuffer line = new StringBuffer(100);
4720         for (int i=0; i<values.size(); i++) {
4721                 if (i>0) 
4722                         line.append(Global.tagDelimeter+" ");
4723                 line.append(values.get(i));
4724         }
4725         if (guid.equals(currentNoteGuid)) {
4726                 browserWindow.setTag(line.toString());
4727         }
4728     }
4729     @SuppressWarnings("unused")
4730         private void externalWindowClosing(String guid) {
4731                 externalWindows.remove(guid);
4732     }
4733     
4734         // ***************************************************************
4735         // ***************************************************************
4736         // ** タブウィンドウの機能
4737         // ***************************************************************
4738         // ***************************************************************
4739         @SuppressWarnings("unused")
4740         private void openNewTab() {
4741                 saveNote();
4742
4743                 // selectedNoteGUIDsをディープコピー
4744                 List<String> copySelected = new ArrayList<String>(selectedNoteGUIDs);
4745                 
4746                 for (int i=0; i < copySelected.size() ; i++) {
4747                         openTabEditor(copySelected.get(i));
4748                 }
4749         }
4750         
4751         // 連想ノートリストから新しいタブで開く
4752         @SuppressWarnings("unused")
4753         private void openNewTabFromRNL(){
4754                 if(rensoNotePressedItemGuid != null){
4755                         String prevCurrentNoteGuid = new String(currentNoteGuid);
4756                         
4757                         saveNote();
4758                         openTabEditor(rensoNotePressedItemGuid);
4759                         
4760                         // 連想ノートリストアイテムクリック操作を記録
4761                         conn.getHistoryTable().addHistory("rensoItemClick", prevCurrentNoteGuid, rensoNotePressedItemGuid);
4762                 }
4763         }
4764         
4765         private void openTabEditor(String guid) {
4766                 
4767                 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4768                 // 新しいタブエディタを作成
4769                 TabBrowse newBrowser = new TabBrowse(conn, tabBrowser, cbObserver);
4770                 showEditorButtons(newBrowser.getBrowserWindow());
4771                 
4772                 String noteTitle = note.getTitle();
4773                 int index = tabBrowser.addNewTab(newBrowser, noteTitle);
4774                 tabWindows.put(index, newBrowser);
4775                 noteDirty.put(index, false);
4776                 
4777                 // noteTableViewの選択を変更するとselectionChangedが発生してしまうので一度切断
4778                 noteTableView.selectionModel().selectionChanged.disconnect(this, "noteTableSelection()");
4779                 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4780                 // 再接続
4781                 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
4782                 
4783                 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4784                 
4785                 // ExtendedInformationを必要があれば表示する
4786                 toggleNoteInformation();
4787                 // Sourceを必要があれば表示する
4788                 viewSource();
4789                 // EditorButtonsBarを必要があれば表示する
4790                 toggleEditorButtonBar();
4791
4792                 // 履歴記録のハッシュマップを初期化
4793                 ArrayList<String> histGuids = new ArrayList<String>();
4794                 historyGuids.put(index, histGuids);
4795                 historyPosition.put(index, 0);
4796                 fromHistory.put(index, false);
4797
4798                 // 履歴に今開いたノートを追加
4799                 histGuids.add(guid);
4800                 historyPosition.put(index, histGuids.size());
4801
4802                 tabBrowser.setCurrentIndex(index);
4803
4804                 if (guid != null && !guid.equals("")) {
4805                         if (!Global.showDeleted) { // ゴミ箱じゃなければ
4806                                 addBrowseHistory();
4807                         }
4808                 }
4809         }
4810
4811         // タブが閉じられた
4812         private void tabWindowClosing(int index) {
4813                 // タブが1つしかなかったら閉じない
4814                 if (tabBrowser.count() <= 1) {
4815                         return;
4816                 }
4817
4818                 TabBrowse t = (TabBrowse) tabBrowser.widget(index);
4819                 String guid = t.getBrowserWindow().getNote().getGuid();
4820                 String content = t.getBrowserWindow().getContent();
4821                 BrowserWindow browser = t.getBrowserWindow();
4822                 // ノートが変更されていたら保存
4823                 if (t.getNoteDirty()) {
4824                         saveNoteTabBrowser(guid, content, true, browser);
4825                 }
4826
4827                 // シグナル切断
4828                 browser.noteSignal.tagsChanged.disconnect();
4829                 browser.noteSignal.titleChanged.disconnect();
4830                 browser.noteSignal.noteChanged.disconnect();
4831                 browser.noteSignal.notebookChanged.disconnect();
4832                 browser.noteSignal.createdDateChanged.disconnect();
4833                 browser.noteSignal.alteredDateChanged.disconnect();
4834
4835                 // ノートを削除
4836                 tabWindows.remove(index);
4837                 tabBrowser.removeTab(index);
4838                 noteDirty.remove(index);
4839                 inkNote.remove(index);
4840                 readOnly.remove(index);
4841
4842                 // 履歴記録のハッシュマップを削除
4843                 historyGuids.remove(index);
4844                 historyPosition.remove(index);
4845                 fromHistory.remove(index);
4846                 
4847                 // タブのインデックスを更新(削除によって空いた部分を詰める)
4848                 for(int i = index ; tabWindows.containsKey(i + 1) ; i++){
4849                         // tabWindows
4850                         TabBrowse tab = tabWindows.get(i + 1);
4851                         tabWindows.put(i, tab);
4852                         tabWindows.remove(i + 1);
4853                         // noteDirty
4854                         boolean isNoteDirty = noteDirty.get(i + 1);
4855                         noteDirty.put(i, isNoteDirty);
4856                         noteDirty.remove(i + 1);
4857                         // inkNote
4858                         boolean isInkNote = inkNote.get(i + 1);
4859                         inkNote.put(i, isInkNote);
4860                         inkNote.remove(i + 1);
4861                         // readOnly
4862                         boolean isReadOnly = readOnly.get(i + 1);
4863                         readOnly.put(i, isReadOnly);
4864                         readOnly.remove(i + 1);
4865                         // historyGuids
4866                         ArrayList<String> histGuids = historyGuids.get(i + 1);
4867                         historyGuids.put(i, histGuids);
4868                         historyGuids.remove(i + 1);
4869                         // historyPosition
4870                         int histPosition = historyPosition.get(i + 1);
4871                         historyPosition.put(i, histPosition);
4872                         historyPosition.remove(i + 1);
4873                         // fromHistory
4874                         boolean fromHist = fromHistory.get(i + 1);
4875                         fromHistory.put(i,  fromHist);
4876                         fromHistory.remove(i + 1);
4877                 }
4878                 
4879                 // タブが残り1つになったら、閉じるボタンを消す
4880                 if (tabBrowser.count() == 1) {
4881                         tabBrowser.hideTabCloseButton(0);
4882                 }
4883                 
4884                 // タブの閉じるボタンを押すと、tabWindowClosingより先にtabWindowChangedが呼ばれてしまうので、手動で呼びなおす
4885                 tabWindowChanged(tabBrowser.currentIndex());
4886         }
4887         
4888         @SuppressWarnings("unused")
4889         private void noteAddNewTab() {
4890                 saveNote();
4891                 
4892                 // ノート追加前に開いていたノートとの関連性を記録するためにguidをとっておく
4893                 TabBrowse prevTab = (TabBrowse)tabBrowser.currentWidget();
4894                 String prevTabGuid = null;
4895                 if (prevTab.getBrowserWindow() != null && prevTab.getBrowserWindow().getNote() != null) {
4896                         prevTabGuid = prevTab.getBrowserWindow().getNote().getGuid();
4897                 }
4898                 
4899                 openEmptyTabEditor();
4900                 addNote();
4901                 
4902                 // 追加されたノートのguidを取得し、ノート追加操作履歴としてデータベースに登録
4903                 if (prevTabGuid != null && !prevTabGuid.equals("")) {
4904                         TabBrowse addedTab = (TabBrowse)tabBrowser.currentWidget();
4905                         String addedTabGuid = addedTab.getBrowserWindow().getNote().getGuid();
4906                         if (addedTabGuid != null && !addedTabGuid.equals("")) {
4907                                 if (!prevTabGuid.equals(addedTabGuid)) {
4908                                         conn.getHistoryTable().addHistory("addNewNote", prevTabGuid, addedTabGuid);
4909                                 }
4910                         }
4911                 }
4912         }
4913         
4914         private void openEmptyTabEditor() {
4915                 // 新しいタブエディタを作成
4916                 TabBrowse newBrowser = new TabBrowse(conn, tabBrowser, cbObserver);
4917                 showEditorButtons(newBrowser.getBrowserWindow());
4918                 
4919                 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4920                 
4921                 int index = tabBrowser.addNewTab(newBrowser, "");
4922                 tabWindows.put(index, newBrowser);
4923                 noteDirty.put(index, false);
4924                 
4925                 // ExtendedInformationを必要があれば表示する
4926                 toggleNoteInformation();
4927                 // Sourceを必要があれば表示する
4928                 viewSource();
4929                 // EditorButtonsBarを必要があれば表示する
4930                 toggleEditorButtonBar();
4931
4932                 // 履歴記録のハッシュマップを初期化
4933                 ArrayList<String> histGuids = new ArrayList<String>();
4934                 historyGuids.put(index, histGuids);
4935                 historyPosition.put(index, 0);
4936                 fromHistory.put(index, false);
4937
4938                 tabBrowser.setCurrentIndex(index);
4939         }
4940
4941     //***************************************************************
4942     //***************************************************************
4943     //** These functions deal with Note specific things
4944     //***************************************************************
4945     //***************************************************************    
4946         private void setNoteDirty() {
4947                 for (String guid: selectedNoteGUIDs) {
4948                         setNoteDirty(guid);
4949                 }
4950         }
4951         
4952         private void setNoteDirty(String targetGuid) {
4953                 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4954                 
4955                 // Find if the note is being edited externally.  If it is, update it.
4956                 if (externalWindows.containsKey(targetGuid)) {
4957                         QTextCodec codec = QTextCodec.codecForName("UTF-8");
4958                 QByteArray unicode =  codec.fromUnicode(browserWindow.getContent());
4959                         ExternalBrowse window = externalWindows.get(targetGuid);
4960                 window.getBrowserWindow().setContent(unicode);
4961                 }
4962                 
4963                 // 他のタブで同じノートを開いていないか探す。もしあったら、内容を更新する。
4964                 Collection<Integer> tabIndexes = tabWindows.keySet();
4965                 Iterator<Integer>       indexIterator = tabIndexes.iterator();
4966                 
4967                 for (TabBrowse tab: tabWindows.values()) {
4968                         int index = indexIterator.next();
4969                         String guid = tab.getBrowserWindow().getNote().getGuid();
4970                         
4971                         QTextCodec codec = QTextCodec.codecForName("UTF-8");
4972                         QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4973                         
4974                         if (guid.equals(guid)) {
4975                                 if (index != tabBrowser.currentIndex()) {
4976                                         TabBrowse window = tabWindows.get(index);
4977                                         window.getBrowserWindow().setContent(unicode);
4978                                 }
4979                         }
4980                 }
4981                 
4982                 // ターゲットノートがタブで開かれていて、かつDirty = trueかどうかを取得する
4983                 // If the note is dirty, then it is unsynchronized by default.
4984                 int index = -1;
4985                 boolean isNoteDirty = false;
4986                 for (TabBrowse tab: tabWindows.values()) {
4987                         if (tab.getBrowserWindow().getNote().getGuid().equals(targetGuid)) {
4988                                 index = tabBrowser.indexOf(tab);
4989                                 isNoteDirty = noteDirty.get(index);
4990                                 break;
4991                         }
4992                 }
4993                 if (isNoteDirty) {
4994                         return;
4995                 }
4996                 
4997                 // Set the note as dirty and check if its status is synchronized in the display table
4998                 // まだダーティでなく、かつタブで開かれている場合にnoteDirty = trueにする
4999                 if (index >= 0) {
5000                         noteDirty.put(index, true);
5001                 }
5002
5003                 if (listManager.getNoteMetadata().containsKey(targetGuid) &&
5004                                 listManager.getNoteMetadata().get(targetGuid).isDirty()) {
5005                                 return;
5006                 }
5007                 
5008                 // If this wasn't already marked as unsynchronized, then we need to update the table
5009                 listManager.getNoteTableModel().updateNoteSyncStatus(targetGuid, false);
5010 //      listManager.getUnsynchronizedNotes().add(targetGuid);
5011         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
5012                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
5013                 if (modelIndex != null) {
5014                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
5015                         String tableGuid =  (String)ix.values().toArray()[0];
5016                         if (tableGuid.equals(targetGuid)) {
5017                                 listManager.getNoteTableModel().proxyModel.setData(i, Global.noteTableSynchronizedPosition, "false");
5018                                 return;
5019                         }
5020                 }
5021         }
5022         
5023                 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
5024     }
5025     @SuppressWarnings("unused")
5026         private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
5027                 QTextCodec codec = QTextCodec.codecForName("UTF-8");
5028         QByteArray unicode =  codec.fromUnicode(content);
5029         noteCache.remove(guid);
5030                 noteCache.put(guid, unicode.toString());
5031         if (guid.equals(currentNoteGuid)) {
5032                 int index = tabBrowser.currentIndex();
5033                 noteDirty.put(index, true);
5034                 browserWindow.setContent(unicode);
5035         } 
5036         if (save) {
5037                 thumbnailRunner.addWork("GENERATE "+ guid);
5038                 saveNote(guid, browser);
5039         }
5040         
5041     }
5042     
5043         private void saveNoteTabBrowser(String guid, String content, Boolean save,
5044                         BrowserWindow browser) {
5045                 QTextCodec codec = QTextCodec.codecForName("UTF-8");
5046                 QByteArray unicode = codec.fromUnicode(content);
5047                 noteCache.remove(guid);
5048                 noteCache.put(guid, unicode.toString());
5049                 if (save) {
5050                         thumbnailRunner.addWork("GENERATE " + guid);
5051                         saveNote(guid, browser);
5052                 }
5053         }
5054         
5055     private void saveNote() {
5056         // すべてのタブに対して、Dirtyを確認し、trueならセーブする
5057         Collection<Integer> dirtyIndex = noteDirty.keySet();
5058         Iterator<Integer> indexIterator = dirtyIndex.iterator();
5059         for (boolean isNoteDirty: noteDirty.values()) {
5060                 int index = indexIterator.next();
5061                 if (isNoteDirty) {
5062                         if (index < 0) {
5063                                 return;
5064                         }
5065                         BrowserWindow b = tabWindows.get(index).getBrowserWindow();
5066                         String guid = b.getNote().getGuid();
5067                         saveNote(guid, b);
5068                         thumbnailRunner.addWork("GENERATE "+ guid);
5069                         noteDirty.put(index, false);
5070                 }
5071         }
5072     }
5073     private void saveNote(String guid, BrowserWindow window) {
5074                 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
5075                 waitCursor(true);
5076                 
5077                 logger.log(logger.EXTREME, "Saving to cache");
5078                 QTextCodec codec = QTextCodec.codecForLocale();
5079 //              QTextDecoder decoder = codec.makeDecoder();
5080                 codec = QTextCodec.codecForName("UTF-8");
5081         QByteArray unicode =  codec.fromUnicode(window.getContent());
5082                 noteCache.put(guid, unicode.toString());
5083                         
5084                 logger.log(logger.EXTREME, "updating list manager");
5085                 listManager.updateNoteContent(guid, window.getContent());
5086                 logger.log(logger.EXTREME, "Updating title");
5087                 listManager.updateNoteTitle(guid, window.getTitle());
5088                 updateListDateChanged();
5089
5090                 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
5091                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
5092                 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
5093                         currentNote = listManager.getNoteIndex().get(i);
5094                         i = listManager.getNoteIndex().size();
5095                 }
5096         }
5097         waitCursor(false);
5098     }
5099     // Get a note from Evernote (and put it in the browser)
5100         private void refreshEvernoteNote(boolean reload) {
5101                 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
5102                 
5103                 if (Global.disableViewing) {
5104                         browserWindow.setEnabled(false);
5105                         return;
5106                 }
5107                 inkNote.put(tabBrowser.currentIndex(), false);
5108                 readOnly.put(tabBrowser.currentIndex(), false);
5109                 
5110                 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals("")) {
5111                         readOnly.put(tabBrowser.currentIndex(), true);
5112                 }
5113                 Global.cryptCounter =0;
5114                 if (readOnly.get(tabBrowser.currentIndex())) {
5115                         browserWindow.setReadOnly(true);
5116                 }
5117                 
5118                 if (!reload)
5119                         return;
5120                 
5121                 waitCursor(true);
5122                 browserWindow.loadingData(true);
5123
5124                 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
5125                 if (currentNote == null) {
5126                         waitCursor(false);
5127                         return;
5128                 }
5129                 
5130                 tabBrowser.setTabTitle(tabBrowser.currentIndex(), currentNote.getTitle());
5131                 
5132                 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
5133         }
5134
5135         private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
5136                 NoteFormatter   formatter = new NoteFormatter(logger, conn, tempFiles);
5137                 formatter.setNote(note, Global.pdfPreview());
5138                 formatter.setHighlight(listManager.getEnSearch());
5139                 QByteArray js;
5140                 int tabIndex = -1;
5141                 
5142                 // 対象のタブインデックスを取得
5143                 for (TabBrowse tab: tabWindows.values()) {
5144                         if (tab.getBrowserWindow() == browser) {
5145                                 tabIndex = tabBrowser.indexOf(tab);
5146                                 break;
5147                         }
5148                 }
5149                 
5150                 if (!noteCache.containsKey(guid)) {
5151                         js = new QByteArray();
5152                         // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly 
5153                         js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");               
5154                         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>");
5155                         js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
5156                         js.append("<style> img { height:auto; width:auto; max-height:auto; max-width:100%; }</style>");
5157                         if (Global.displayRightToLeft())
5158                                 js.append("<style> body { direction:rtl; }</style>");
5159                         js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
5160                         js.append("</head>");
5161                         formatter.setNote(note, Global.pdfPreview());
5162                         js.append(formatter.rebuildNoteHTML());
5163                         js.append("</HTML>");
5164                         js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
5165                         js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
5166                         js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
5167 //              if (Global.enableHTMLEntitiesFix) {
5168 //                      browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
5169 //              } else
5170                         browser.setContent(js);
5171                         noteCache.put(guid, js.toString());
5172
5173                         if (formatter.resourceError)
5174                                 resourceErrorMessage(tabIndex);
5175                         if (formatter.formatError) {
5176                                 waitCursor(false);
5177                              QMessageBox.information(this, tr("Error"),
5178                                                 tr("NeighborNote had issues formatting this note." +
5179                                                 " To protect your data this note is being marked as read-only."));      
5180                              waitCursor(true);
5181                         }
5182                         
5183                         if (tabIndex >= 0) {
5184                                 readOnly.put(tabIndex, formatter.readOnly);
5185                                 inkNote.put(tabIndex, formatter.inkNote);
5186                         } 
5187                         
5188                         if (tabIndex >= 0 && readOnly.get(tabIndex)) {
5189                                 readOnlyCache.put(guid, true);
5190                         }
5191                         if (tabIndex >= 0 && inkNote.get(tabIndex)) {
5192                                 inkNoteCache.put(guid, true);
5193                         }
5194                         
5195                 } else {
5196                         logger.log(logger.HIGH, "Note content is being pulled from the cache");
5197                         String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
5198                         js = new QByteArray(cachedContent);
5199                         browser.setContent(js);
5200                         if (readOnlyCache.containsKey(guid) && tabIndex >= 0) {
5201                                 readOnly.put(tabIndex, true);
5202                         } else {
5203                                 readOnly.put(tabIndex, false);
5204                         }
5205                         if (inkNoteCache.containsKey(guid) && tabIndex >= 0) {
5206                                 inkNote.put(tabIndex, true);
5207                         } else {
5208                                 inkNote.put(tabIndex, false);
5209                         }
5210                 }
5211                 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
5212                         thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
5213                 }
5214                 if (tabIndex >= 0 && (readOnly.get(tabIndex) || inkNote.get(tabIndex) || 
5215                                 (note.getAttributes() != null && note.getAttributes().getContentClass() != null && note.getAttributes().getContentClass() != "")))
5216                         browser.getBrowser().page().setContentEditable(false);  // We don't allow editing of ink notes
5217                 else
5218                         browser.getBrowser().page().setContentEditable(true);
5219                 if (tabIndex >= 0) {
5220                         browser.setReadOnly(readOnly.get(tabIndex));
5221                         deleteButton.setEnabled(!readOnly.get(tabIndex));
5222                         tagButton.setEnabled(!readOnly.get(tabIndex));
5223                         menuBar.noteDelete.setEnabled(!readOnly.get(tabIndex));
5224                         menuBar.noteTags.setEnabled(!readOnly.get(tabIndex));
5225                 }
5226                 browser.setNote(note);
5227                 
5228                 if (note != null && note.getNotebookGuid() != null && 
5229                                 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
5230                         deleteButton.setEnabled(false);
5231                         menuBar.notebookDeleteAction.setEnabled(false);
5232                 } else {
5233                         deleteButton.setEnabled(true);
5234                         menuBar.notebookDeleteAction.setEnabled(true);
5235                 }
5236                 
5237                 // Build a list of non-closed notebooks
5238                 List<Notebook> nbooks = new ArrayList<Notebook>();
5239                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
5240                         boolean found=false;
5241                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
5242                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) 
5243                                         found = true;
5244                         }
5245                         if (!found)
5246                                 nbooks.add(listManager.getNotebookIndex().get(i));
5247                 }
5248                 
5249                 browser.setTitle(note.getTitle());
5250                 browser.setTag(getTagNamesForNote(note));
5251                 browser.setAuthor(note.getAttributes().getAuthor());
5252
5253                 browser.setAltered(note.getUpdated());
5254                 browser.setCreation(note.getCreated());
5255                 if (note.getAttributes().getSubjectDate() > 0)
5256                         browser.setSubjectDate(note.getAttributes().getSubjectDate());
5257                 else
5258                         browser.setSubjectDate(note.getCreated());
5259                 browser.setUrl(note.getAttributes().getSourceURL());
5260                 
5261                 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
5262                 List<Tag> tagList = tagFilter.getValidTags(note);
5263                 browser.setAllTags(tagList);
5264                 
5265                 browser.setCurrentTags(note.getTagNames());
5266                 for (TabBrowse tab: tabWindows.values()) {
5267                         if (tab.getBrowserWindow().getNote().getGuid().equals(guid)) {
5268                                 int index = tabBrowser.indexOf(tab);
5269                                 noteDirty.put(index, false);
5270                                 break;
5271                         }
5272                 }
5273                 
5274                 scrollToGuid(guid);
5275                 
5276                 browser.loadingData(false);
5277                 if (thumbnailViewer.isActiveWindow())
5278                         thumbnailView();
5279                 
5280                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
5281                 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
5282
5283                 waitCursor(false);
5284                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
5285         }
5286         
5287         @SuppressWarnings("unused")
5288         private void toggleNoteAttributes() {
5289                 menuBar.noteAttributes.setChecked(!menuBar.noteAttributes.isChecked());
5290                 toggleNoteInformation();
5291         }
5292         
5293         // Save a generated thumbnail
5294         private void toggleNoteInformation() {
5295                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
5296         
5297                 boolean isChecked = menuBar.noteAttributes.isChecked();
5298                 
5299         for(int i = 0; i < tabBrowser.count(); i++){
5300                 BrowserWindow browser = ((TabBrowse) tabBrowser.widget(i)).getBrowserWindow();
5301                 boolean isExtended = browser.isExtended();
5302                 if((isChecked && !isExtended) || (!isChecked && isExtended)){
5303                         browser.toggleInformation();
5304                 }
5305         }
5306         
5307         menuBar.noteAttributes.setChecked(browserWindow.isExtended());
5308         Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
5309         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
5310     }
5311         
5312         // Listener triggered when a print button is pressed
5313     @SuppressWarnings("unused")
5314         private void printNote() {
5315                 logger.log(logger.HIGH, "Entering NeverNote.printNote");
5316
5317         QPrintDialog dialog = new QPrintDialog();
5318         if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
5319                 QPrinter printer = dialog.printer();
5320                 browserWindow.getBrowser().print(printer);
5321         }
5322                 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
5323
5324     }
5325     // Listener triggered when the email button is pressed
5326     @SuppressWarnings("unused")
5327         private void emailNote() {
5328         logger.log(logger.HIGH, "Entering NeverNote.emailNote");
5329         
5330         if (Desktop.isDesktopSupported()) {
5331             Desktop desktop = Desktop.getDesktop();
5332             
5333             String text2 = browserWindow.getContentsToEmail();
5334             QUrl url = new QUrl("mailto:");
5335             url.addQueryItem("subject", currentNote.getTitle());
5336 //            url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
5337             url.addQueryItem("body", text2);
5338             QDesktopServices.openUrl(url);
5339         }
5340 /*            
5341             
5342             if (desktop.isSupported(Desktop.Action.MAIL)) {
5343                 URI uriMailTo = null;
5344                 try {
5345                         //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
5346                         String text = browserWindow.getContentsToEmail();
5347                         //text = "<b>" +text +"</b>";
5348                                         uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
5349                                                         +"&BODY=" +text, null);
5350                                         uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
5351                                                         +"&ATTACHMENT=d:/test.pdf", null);
5352                                         desktop.mail(uriMailTo);
5353                                 } catch (URISyntaxException e) {
5354                                         e.printStackTrace();
5355                                 } catch (IOException e) {
5356                                         e.printStackTrace();
5357                                 }
5358
5359             }
5360
5361         }     
5362  */     
5363         logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
5364     }
5365         // Reindex all notes
5366     @SuppressWarnings("unused")
5367         private void fullReindex() {
5368         logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
5369         indexRunner.addWork("REINDEXALL");
5370         setMessage(tr("Database will be reindexed."));
5371         logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
5372     }
5373     // Listener when a user wants to reindex a specific note
5374     @SuppressWarnings("unused")
5375         private void reindexNote() {
5376         logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
5377                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
5378                         indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
5379                 }
5380                 if (selectedNotebookGUIDs.size() > 1)
5381                         setMessage(tr("Notes will be reindexed."));
5382                 else
5383                         setMessage(tr("Note will be reindexed."));
5384         logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
5385     }
5386     // Delete the note
5387     @SuppressWarnings("unused")
5388         private void deleteNote() {
5389         logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
5390         if (currentNote == null) 
5391                 return;
5392         if (currentNoteGuid.equals(""))
5393                 return;
5394         String title = null;
5395         if (selectedNoteGUIDs.size() == 1)
5396                 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
5397
5398         // If we are deleting non-trash notes
5399         if (currentNote.isActive()) { 
5400                 if (Global.verifyDelete()) {
5401                         String msg;
5402                         if (selectedNoteGUIDs.size() > 1) {
5403                                 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
5404                         } else {
5405                                 if (title != null)
5406                                         msg = new String(tr("Delete note \"") +title +"\"?");
5407                                 else                            
5408                                         msg = new String(tr("Delete note selected note?"));
5409                         }
5410                         if (QMessageBox.question(this, tr("Confirmation"), msg,
5411                                         QMessageBox.StandardButton.Yes, 
5412                                         QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
5413                                         return;
5414                         }
5415                 }
5416                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
5417                         selectedNoteGUIDs.add(currentNoteGuid);
5418                 closeTabs(selectedNoteGUIDs);
5419                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
5420                         listManager.deleteNote(selectedNoteGUIDs.get(i));
5421                 }
5422         } else { 
5423                 // If we are deleting from the trash.
5424                 if (Global.verifyDelete()) {
5425                         String msg;
5426                         if (selectedNoteGUIDs.size() > 1) {
5427                                 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
5428                         } else {
5429                                 if (title != null)
5430                                 msg = new String(tr("Permanently delete note \"") +title +"\"?");
5431                                 else
5432                                         msg = new String(tr("Permanently delete note selected note?"));
5433                         }
5434                         if (QMessageBox.question(this, "Confirmation", msg,
5435                                 QMessageBox.StandardButton.Yes, 
5436                                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {                                            
5437                                         return;
5438                         }
5439                 }
5440                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
5441                         selectedNoteGUIDs.add(currentNoteGuid);
5442                 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
5443                         for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
5444                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
5445                         if (modelIndex != null) {
5446                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
5447                                 String tableGuid =  (String)ix.values().toArray()[0];
5448                                 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
5449                                         listManager.getNoteTableModel().removeRow(j);
5450                                         j=-1;
5451                                 }
5452                         }
5453                 }
5454                         closeTabs(selectedNoteGUIDs);
5455                         listManager.expungeNote(selectedNoteGUIDs.get(i));
5456                         
5457                         conn.getHistoryTable().expungeHistory(selectedNoteGUIDs.get(i));
5458                         conn.getExcludedTable().expungeExcludedNote(selectedNoteGUIDs.get(i));
5459                         conn.getStaredTable().expungeStaredNote(selectedNoteGUIDs.get(i));
5460                         
5461                 }
5462         }
5463         currentNoteGuid = "";
5464         closeExternalWindows(selectedNoteGUIDs);
5465                 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
5466                         menuBar.noteAddNewTab.setEnabled(false);
5467                 }
5468                 
5469         listManager.loadNotesIndex();
5470         noteIndexUpdated(false);
5471         refreshEvernoteNote(true);
5472         scrollToGuid(currentNoteGuid);
5473         logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
5474     }
5475     
5476     // 対象ノートをタブで開いていたら閉じる
5477     private void closeTabs(List<String> noteGUIDs) {
5478                 Collection<TabBrowse> tabBrowsers = tabWindows.values();
5479                 Iterator<TabBrowse> tabIterator = tabBrowsers.iterator();
5480                 Collection<Integer> tabIndexes = tabWindows.keySet();
5481                 Iterator<Integer>       indexIterator = tabIndexes.iterator();
5482                 List<Integer> closeIndexes = new ArrayList<Integer>();  //イテレータ操作中に中身をいじっちゃダメなので
5483
5484                 while (tabIterator.hasNext()) {
5485                         TabBrowse tab = tabIterator.next();
5486                         int index = indexIterator.next();
5487                         String guid = tab.getBrowserWindow().getNote().getGuid();
5488                         
5489                         for(int i = 0; i < noteGUIDs.size(); i++){
5490                                 if(guid.equals(noteGUIDs.get(i))){
5491                                         closeIndexes.add(index);
5492                                 }
5493                         }
5494                 }
5495                 
5496                 for(int i = closeIndexes.size() - 1; i >= 0; i--){
5497                         tabWindowClosing(closeIndexes.get(i));
5498                 }
5499     }
5500     
5501     // 対象ノートを外部ウィンドウで開いていたら閉じる
5502     private void closeExternalWindows(List<String> noteGUIDs) {
5503                 Collection<ExternalBrowse>      windows = externalWindows.values();
5504                 Iterator<ExternalBrowse>        windowIterator = windows.iterator();
5505                 Collection<String>                      guids = externalWindows.keySet();
5506                 Iterator<String>                        guidIterator = guids.iterator();
5507                 List<ExternalBrowse>            closeWindows = new ArrayList<ExternalBrowse>(); // イテレータ操作中に中身をいじっちゃダメなので
5508                 
5509                 while (windowIterator.hasNext()) {
5510                         ExternalBrowse browser = windowIterator.next();
5511                         String guid = guidIterator.next();
5512                         
5513                         for (int i = 0; i < noteGUIDs.size(); i++) {
5514                                 if (guid.equals(noteGUIDs.get(i))) {
5515                                         closeWindows.add(browser);
5516                                 }
5517                         }
5518                 }
5519                 
5520                 for (int i = closeWindows.size() - 1; i >= 0; i--) {
5521                         closeWindows.get(i).close();
5522                 }
5523     }
5524     
5525     // Add a new note
5526         private void addNote() {
5527         logger.log(logger.HIGH, "Inside NeverNote.addNote");
5528 //      browserWindow.setEnabled(true);
5529         browserWindow.setReadOnly(false);
5530         saveNote();
5531         Calendar currentTime = new GregorianCalendar();
5532         StringBuffer noteString = new StringBuffer(100);
5533         noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
5534                 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
5535                 "<en-note>\n");
5536         
5537         if (Global.overrideDefaultFont()) {
5538                 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
5539                 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
5540                 noteString.append("<br clear=\"none\" />\n");
5541                 noteString.append("</span>\n</font>\n");
5542         } else
5543                 noteString.append("<br clear=\"none\" />\n");
5544         noteString.append("</en-note>");
5545         
5546         Long l = new Long(currentTime.getTimeInMillis());
5547         String randint = new String(Long.toString(l));          
5548         
5549         // Find a notebook.  We first look for a selected notebook (the "All Notebooks" one doesn't count).  
5550         // Then we look
5551         // for the first non-archived notebook.  Finally, if nothing else we 
5552         // pick the first notebook in the list.
5553         String notebook = null;
5554         listManager.getNotebookIndex().get(0).getGuid();
5555         List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
5556         if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
5557                 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
5558                 notebook = currentSelectedNotebook.text(2);
5559         } else {
5560                 boolean found = false;
5561                 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
5562                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
5563                         boolean match = false;
5564                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
5565                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
5566                                         match = true;
5567                                         j = listManager.getArchiveNotebookIndex().size();
5568                                 }
5569                         }
5570                         if (!match)
5571                                 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
5572                                 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
5573                 }
5574                 // Now we have a list of good notebooks, so we can look for the default
5575                 found = false;
5576                 for (int i=0; i<goodNotebooks.size(); i++) {
5577                         if (goodNotebooks.get(i).isDefaultNotebook()) {
5578                                 notebook = goodNotebooks.get(i).getGuid();
5579                                 found = true;
5580                                 i = goodNotebooks.size();
5581                         }
5582                 }
5583                 
5584                 if (goodNotebooks.size() > 0 && !found)
5585                         notebook = goodNotebooks.get(0).getGuid();
5586      
5587                 if (notebook==null)
5588                         notebook = listManager.getNotebookIndex().get(0).getGuid();             
5589         }
5590         
5591         Note newNote = new Note();
5592         newNote.setUpdateSequenceNum(0);
5593         newNote.setGuid(randint);
5594         newNote.setNotebookGuid(notebook);
5595         newNote.setTitle("Untitled Note");
5596         newNote.setContent(noteString.toString());
5597         newNote.setDeleted(0);
5598         newNote.setCreated(System.currentTimeMillis());
5599         newNote.setUpdated(System.currentTimeMillis());
5600         newNote.setActive(true);
5601         NoteAttributes na = new NoteAttributes();
5602         na.setLatitude(0.0);
5603         na.setLongitude(0.0);
5604         na.setAltitude(0.0);
5605         newNote.setAttributes(new NoteAttributes());
5606                 newNote.setTagGuids(new ArrayList<String>());
5607                 newNote.setTagNames(new ArrayList<String>());
5608         
5609         // If new notes are to be created based upon the selected tags, then we need to assign the tags
5610         if (Global.newNoteWithSelectedTags()) { 
5611                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
5612                 QTreeWidgetItem currentSelection;
5613                 for (int i=0; i<selections.size(); i++) {
5614                         currentSelection = selections.get(i);
5615                         newNote.getTagGuids().add(currentSelection.text(2));
5616                         newNote.getTagNames().add(currentSelection.text(0));
5617                 }
5618         }
5619         
5620         conn.getNoteTable().addNote(newNote, true);
5621         NoteMetadata metadata = new NoteMetadata();
5622         metadata.setGuid(newNote.getGuid());
5623         metadata.setDirty(true);
5624         listManager.addNote(newNote, metadata);
5625 //      noteTableView.insertRow(newNote, true, -1);
5626         
5627         String prevCurrentNoteGuid = new String(currentNoteGuid);
5628         
5629         currentNote = newNote;
5630         currentNoteGuid = currentNote.getGuid();
5631         // IFIXED こいつのせいで、ノート追加時にcurrentNoteGuidが更新されないので消す
5632         // noteTableView.clearSelection();
5633         
5634         // 新規に作成したノートとそれまで開いていたノートの関連性を追加
5635         if (prevCurrentNoteGuid != null && !prevCurrentNoteGuid.equals("")) {
5636                 if (currentNoteGuid != null && !currentNoteGuid.equals("")) {
5637                         conn.getHistoryTable().addHistory("addNewNote", prevCurrentNoteGuid, currentNoteGuid);
5638                 }
5639         }
5640         
5641         refreshEvernoteNote(true);
5642         listManager.countNotebookResults(listManager.getNoteIndex());
5643         browserWindow.titleLabel.setFocus();
5644         browserWindow.titleLabel.selectAll();
5645 //      notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
5646         
5647         // If the window is hidden, then we want to popup this in an external window & 
5648         if (!isVisible())
5649                 listDoubleClick();
5650         waitCursor(false);
5651         logger.log(logger.HIGH, "Leaving NeverNote.addNote");
5652     }
5653     // Restore a note from the trash;
5654     @SuppressWarnings("unused")
5655         private void restoreNote() {
5656         waitCursor(true);
5657                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
5658                         selectedNoteGUIDs.add(currentNoteGuid);
5659                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
5660                         listManager.restoreNote(selectedNoteGUIDs.get(i));
5661                 }
5662         currentNoteGuid = "";
5663         listManager.loadNotesIndex();
5664         noteIndexUpdated(false);
5665         waitCursor(false);
5666     }
5667     // Search a note for specific txt
5668     @SuppressWarnings("unused")
5669         private void findText() {
5670         find.show();
5671         find.setFocusOnTextField();
5672     }
5673     @SuppressWarnings("unused")
5674         private void doFindText() {
5675         browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
5676         find.setFocus();
5677     }
5678     @SuppressWarnings("unused")
5679         private void updateNoteTitle(String guid, String title) {
5680         listManager.setNoteSynchronized(guid, false);
5681         
5682         // We do this manually because if we've edited the note in an 
5683         // external window we run into the possibility of signal recursion
5684         // looping.
5685         if (guid.equals(currentNoteGuid)) {
5686                 browserWindow.titleLabel.blockSignals(true);
5687                 browserWindow.titleLabel.setText(title);
5688                 browserWindow.titleLabel.blockSignals(false);
5689         }
5690     }
5691     // Signal received that note content has changed.  Normally we just need the guid to remove
5692     // it from the cache.
5693     @SuppressWarnings("unused")
5694         private void invalidateNoteCache(String guid, String content) {
5695         noteCache.remove(guid);
5696                 refreshEvernoteNote(true);
5697     }
5698     // Signal received that a note guid has changed
5699     @SuppressWarnings("unused")
5700         private void noteGuidChanged(String oldGuid, String newGuid) {
5701         if (noteCache.containsKey(oldGuid)) {
5702                 if (!oldGuid.equals(currentNoteGuid)) {
5703                         String cache = noteCache.get(oldGuid);
5704                         noteCache.put(newGuid, cache);
5705                         noteCache.remove(oldGuid);
5706                 } else {
5707                         noteCache.remove(oldGuid);
5708                         noteCache.put(newGuid, browserWindow.getContent());
5709                 }
5710         }
5711   
5712         listManager.updateNoteGuid(oldGuid, newGuid, false);
5713         if (currentNoteGuid.equals(oldGuid)) {
5714                 if (currentNote != null)
5715                         currentNote.setGuid(newGuid);
5716                 currentNoteGuid = newGuid;
5717         }
5718                 
5719         if (externalWindows.containsKey(oldGuid)) {
5720                         ExternalBrowse b = externalWindows.get(oldGuid);
5721                         externalWindows.remove(oldGuid);
5722                         b.getBrowserWindow().getNote().setGuid(newGuid);
5723                         externalWindows.put(newGuid, b);
5724                 }
5725         
5726                 for(int i = 0; i < tabBrowser.count(); i++){
5727                         TabBrowse b = (TabBrowse)tabBrowser.widget(i);
5728                         if (b.getBrowserWindow().getNote().getGuid().equals(oldGuid)) {
5729                                 b.getBrowserWindow().getNote().setGuid(newGuid);
5730                         }
5731                 }
5732
5733         for (int i=0; i<listManager.getNoteIndex().size(); i++) {
5734                 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
5735                         noteTableView.proxyModel.addGuid(newGuid, listManager.getNoteMetadata().get(newGuid));
5736                         i=listManager.getNoteIndex().size();
5737                 }
5738         }
5739         
5740         if (listManager.getNoteTableModel().metaData.containsKey(oldGuid)) {
5741                 NoteMetadata meta = listManager.getNoteTableModel().metaData.get(oldGuid);
5742                 listManager.getNoteTableModel().metaData.put(newGuid, meta);
5743                 listManager.getNoteTableModel().metaData.remove(oldGuid);
5744         }
5745         
5746     }
5747         
5748     // Toggle the note editor button bar
5749     // すべてのタブに
5750     private void toggleEditorButtonBar() {
5751         boolean isChecked = menuBar.showEditorBar.isChecked();
5752         
5753         for(int i = 0; i < tabBrowser.count(); i++){
5754                 BrowserWindow browser = ((TabBrowse) tabBrowser.widget(i)).getBrowserWindow();
5755                 boolean isVisible = browser.buttonsVisible;
5756
5757                 if (isChecked && !isVisible) {
5758                         browser.buttonsVisible = true;
5759                         showEditorButtons(browser);
5760                 } else if(!isChecked && isVisible) {
5761                         browser.hideButtons();
5762                 }
5763         }
5764
5765         Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
5766     }
5767     
5768     // Show editor buttons
5769     private void showEditorButtons(BrowserWindow browser) {
5770                 browser.buttonLayout.setVisible(true);
5771                 browser.undoAction.setVisible(false);
5772                 
5773                 browser.undoButton.setVisible(false);
5774
5775                 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
5776                 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
5777                 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
5778                 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
5779                 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
5780                 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
5781                 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
5782                 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
5783                 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
5784                 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
5785                 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
5786                 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
5787                 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
5788                 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
5789                 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
5790                 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
5791                 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
5792                 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
5793                 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
5794                 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
5795                 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
5796                 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
5797                 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
5798     }
5799     private void duplicateNote(String guid) {
5800                 
5801                 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
5802                 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
5803                 oldNote.setContent(conn.getNoteTable().getNoteContentNoUTFConversion(guid));
5804                 oldNote.setResources(resList);
5805                 duplicateNote(oldNote);
5806         }
5807         private void duplicateNote(Note oldNote) {
5808                 waitCursor(true);
5809                 // Now that we have a good notebook guid, we need to move the conflicting note
5810                 // to the local notebook
5811                 Calendar currentTime = new GregorianCalendar();
5812                 Long l = new Long(currentTime.getTimeInMillis());
5813                 String newGuid = new String(Long.toString(l));
5814                                         
5815 //              Note newNote = oldNote.deepCopy();
5816                 Note newNote = (Note)Global.deepCopy(oldNote);
5817                 newNote.setUpdateSequenceNum(0);
5818                 newNote.setGuid(newGuid);
5819                 newNote.setDeleted(0);
5820                 newNote.setActive(true);
5821                 
5822                 /*
5823                 List<String> tagNames = new ArrayList<String>();
5824                 List<String> tagGuids = new ArrayList<String>();;
5825                 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
5826                         tagNames.add(oldNote.getTagNames().get(i));
5827                         tagGuids.add(oldNote.getTagGuids().get(i));
5828                 }
5829
5830                 // Sort note Tags to make them look nice
5831                 for (int i=0; i<tagNames.size()-1; i++) {
5832                         if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
5833                                 String n1 = tagNames.get(i);
5834                                 String n2 = tagNames.get(i+1);
5835                                 tagNames.set(i, n2);
5836                                 tagNames.set(i+1, n1);
5837                         }
5838                 }
5839                 newNote.setTagGuids(tagGuids);
5840                 newNote.setTagNames(tagNames);
5841                 
5842                 // Add tag guids to note
5843                 */
5844                 
5845                 // Duplicate resources
5846                 List<Resource> resList = oldNote.getResources();
5847                 if (resList == null)
5848                         resList = new ArrayList<Resource>();
5849                 long prevGuid = 0;
5850                 for (int i=0; i<resList.size(); i++) {
5851                         l = prevGuid;
5852                         while (l == prevGuid) {
5853                                 currentTime = new GregorianCalendar();
5854                                 l = new Long(currentTime.getTimeInMillis());
5855                         }
5856                         prevGuid = l;
5857                         String newResGuid = new String(Long.toString(l));
5858                         resList.get(i).setNoteGuid(newGuid);
5859                         resList.get(i).setGuid(newResGuid);
5860                         resList.get(i).setUpdateSequenceNum(0);
5861                         resList.get(i).setActive(true);
5862                         conn.getNoteTable().noteResourceTable.saveNoteResource(
5863                                         (Resource)Global.deepCopy(resList.get(i)), true);
5864                 }
5865                 newNote.setResources(resList);
5866                 
5867                 // 操作履歴と除外ノートとスター付きノートも複製する
5868                 if(Global.getDuplicateRensoNote()) {
5869                         conn.getHistoryTable().duplicateHistory(newGuid, oldNote.getGuid());
5870                         conn.getExcludedTable().duplicateExcludedNotes(newGuid, oldNote.getGuid());
5871                         conn.getStaredTable().duplicateStaredNotes(newGuid, oldNote.getGuid());
5872                 }
5873                 
5874                 // Add note to the database
5875                 conn.getNoteTable().addNote(newNote, true);
5876                 NoteMetadata metaData = new NoteMetadata();
5877                 NoteMetadata oldMeta = listManager.getNoteMetadata().get(oldNote.getGuid());
5878                 metaData.copy(oldMeta);
5879                 metaData.setGuid(newNote.getGuid());
5880                 listManager.addNote(newNote, metaData);
5881                 noteTableView.insertRow(newNote, metaData, true, -1);
5882                 currentNoteGuid = newNote.getGuid();
5883                 currentNote = newNote;
5884                 refreshEvernoteNote(true);
5885                 listManager.countNotebookResults(listManager.getNoteIndex());
5886                 waitCursor(false);
5887                 
5888         }
5889         // View all notes
5890         @SuppressWarnings("unused")
5891         private void allNotes() {
5892                 clearAttributeFilter();
5893                 clearNotebookFilter();
5894                 clearSavedSearchFilter();
5895                 clearTrashFilter();
5896                 clearTagFilter();
5897                 searchField.clear();
5898                 if (Global.mimicEvernoteInterface) {
5899                         notebookTree.selectGuid("");
5900                 }
5901                 notebookTreeSelection();
5902                 refreshEvernoteNote(true);
5903                 
5904                 // ゴミ箱から元の画面に戻す。連想ノートリストをONに。
5905                 if (!rensoNoteListDock.isEnabled()) {
5906                         rensoNoteListDock.setEnabled(true);
5907                 }
5908         }
5909         // Merge notes
5910         @SuppressWarnings("unused")
5911         private void mergeNotes() {
5912                 logger.log(logger.HIGH, "Merging notes");
5913                 waitCursor(true);
5914                 saveNote();
5915                 String masterGuid = null;
5916                 List<String> sources = new ArrayList<String>();
5917                 QModelIndex index;
5918                 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
5919                         int r = noteTableView.selectionModel().selectedRows().get(i).row();
5920                         index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
5921                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5922                 if (i == 0) 
5923                         masterGuid = (String)ix.values().toArray()[0];
5924                 else 
5925                         sources.add((String)ix.values().toArray()[0]);  
5926                 }
5927                 
5928                 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
5929                 logger.log(logger.EXTREME, "Children count: "+sources.size());
5930                 mergeNoteContents(masterGuid, sources);
5931                 currentNoteGuid = masterGuid;
5932                 
5933                 // 操作履歴と除外ノートとスター付きノートをマージ
5934                 if(Global.getMergeRensoNote()) {
5935                         for (int i = 0; i < sources.size(); i++) {
5936                                 String childGuid = sources.get(i);
5937                                 if(masterGuid != null && childGuid != null) {
5938                                         if(!masterGuid.equals(childGuid)) {
5939                                                 conn.getHistoryTable().mergeHistoryGuid(masterGuid, childGuid);
5940                                                 conn.getExcludedTable().mergeHistoryGuid(masterGuid, childGuid);
5941                                                 conn.getStaredTable().mergeHistoryGuid(masterGuid, childGuid);
5942                                         }
5943                                 }
5944                         }
5945                 }
5946                 
5947                 // マージしたノート(child)を外部ウィンドウで開いていたら、閉じる
5948                 Collection<ExternalBrowse>      windows = externalWindows.values();
5949                 Iterator<ExternalBrowse>        windowIterator = windows.iterator();
5950                 Collection<String>                      guids = externalWindows.keySet();
5951                 Iterator<String>                        guidIterator = guids.iterator();
5952                 List<ExternalBrowse>            closeWindows = new ArrayList<ExternalBrowse>();
5953                 
5954                 while (windowIterator.hasNext()) {
5955                         ExternalBrowse browser = windowIterator.next();
5956                         String guid = guidIterator.next();
5957                         
5958                         for (int i = 0; i < sources.size(); i++) {
5959                                 if (guid.equals(sources.get(i))) {
5960                                         closeWindows.add(browser);
5961                                 }
5962                         }
5963                 }
5964                 
5965                 for (int i = closeWindows.size() - 1; i >= 0; i--) {
5966                         closeWindows.get(i).close();
5967                 }
5968                 
5969         // マージしたノート(child)をタブで開いていたら、閉じる
5970                 Collection<TabBrowse> tabBrowsers = tabWindows.values();
5971                 Iterator<TabBrowse> tabIterator = tabBrowsers.iterator();
5972                 Collection<Integer> tabIndexes = tabWindows.keySet();
5973                 Iterator<Integer>       indexIterator = tabIndexes.iterator();
5974                 List<Integer> closeIndexes = new ArrayList<Integer>();
5975
5976                 while (tabIterator.hasNext()) {
5977                         TabBrowse tab = tabIterator.next();
5978                         int tabIndex = indexIterator.next();
5979                         String guid = tab.getBrowserWindow().getNote().getGuid();
5980                         
5981                         for(int i = 0; i < sources.size(); i++){
5982                                 if(guid.equals(sources.get(i))){
5983                                         closeIndexes.add(tabIndex);
5984                                 }
5985                         }
5986                 }
5987                 
5988                 for(int i = closeIndexes.size() - 1; i >= 0; i--){
5989                         tabWindowClosing(closeIndexes.get(i));
5990                 }
5991                 
5992                 noteIndexUpdated(false);
5993                 // IFIXED 
5994                 // マージ後の新しいノートコンテンツを表示するためキャッシュを削除
5995                 noteCache.remove(masterGuid);
5996                 
5997                 refreshEvernoteNote(true);
5998                 waitCursor(false);
5999         }
6000         private void mergeNoteContents(String targetGuid, List<String> sources) {
6001                 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
6002                 String newContent = target.getContent();
6003                 newContent = newContent.replace("</en-note>", "<br></br>");
6004                 
6005                 for (int i=0; i<sources.size(); i++) {
6006                         Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
6007                         if (source.isSetTitle()) {
6008                                 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
6009                         }
6010                         String sourceContent = source.getContent();
6011                         logger.log(logger.EXTREME, "Merging contents into note");
6012                         logger.log(logger.EXTREME, sourceContent);
6013                         logger.log(logger.EXTREME, "End of content");
6014                         int startOfNote = sourceContent.indexOf("<en-note>");
6015                         sourceContent = sourceContent.substring(startOfNote+9);
6016                         int endOfNote = sourceContent.indexOf("</en-note>");
6017                         sourceContent = sourceContent.substring(0,endOfNote);
6018                         newContent = newContent + sourceContent;
6019                         logger.log(logger.EXTREME, "New note content");
6020                         logger.log(logger.EXTREME, newContent);
6021                         logger.log(logger.EXTREME, "End of content");
6022                         for (int j=0; j<source.getResourcesSize(); j++) {
6023                                 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
6024                                 Resource r = source.getResources().get(j);
6025                                 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
6026                                 
6027                                 Calendar currentTime = new GregorianCalendar();
6028                                 Long l = new Long(currentTime.getTimeInMillis());
6029                                                         
6030                                 long prevGuid = 0;
6031                                 l = prevGuid;
6032                                 while (l == prevGuid) {
6033                                         currentTime = new GregorianCalendar();
6034                                         l = new Long(currentTime.getTimeInMillis());
6035                                 }
6036                                 String newResGuid = new String(Long.toString(l));
6037                                 newRes.setNoteGuid(targetGuid);
6038                                 newRes.setGuid(newResGuid);
6039                                 newRes.setUpdateSequenceNum(0);
6040                                 newRes.setActive(true);
6041                                 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
6042                         }
6043                 }
6044                 logger.log(logger.EXTREME, "Updating note");
6045                 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
6046                 for (int i=0; i<sources.size(); i++) {
6047                         logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
6048                         listManager.deleteNote(sources.get(i));
6049                 }
6050                 logger.log(logger.EXTREME, "Exiting merge note");
6051         }
6052         // A resource within a note has had a guid change 
6053         @SuppressWarnings("unused")
6054         private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
6055                 if (oldGuid != null && !oldGuid.equals(newGuid))
6056                         Global.resourceMap.put(oldGuid, newGuid);
6057         }
6058         // View a thumbnail of the note
6059         public void thumbnailView() {
6060                 
6061                 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
6062                 QFile thumbnail = new QFile(thumbnailName);
6063                 if (!thumbnail.exists()) {
6064                         
6065                         QImage img = new QImage();
6066                         img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
6067                         thumbnailViewer.setThumbnail(img);
6068                 } else
6069                         thumbnailViewer.setThumbnail(thumbnailName);
6070                 if (!thumbnailViewer.isVisible()) 
6071                         thumbnailViewer.showFullScreen();
6072         }
6073         // An error happened while saving a note.  Inform the user
6074         @SuppressWarnings("unused")
6075         private void saveRunnerError(String guid, String msg) {
6076                 if (msg == null) {
6077                         String title = "*Unknown*";
6078                         for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
6079                                 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
6080                                         title = listManager.getMasterNoteIndex().get(i).getTitle();
6081                                         i=listManager.getMasterNoteIndex().size();
6082                                 }
6083                         }
6084                         msg = tr("An error has happened while saving the note \"") +title+
6085                         tr("\".\n\nThis is probably due to a document that is too complex for NeighborNote to process.  "+
6086                         "As a result, changes to the note may not be saved properly in the database."+
6087                         "\n\nA cached copy is being preserved so you can recover any data, but data may" +
6088                         "\nbe lost.  Please review the note to recover any critical data before restarting.");
6089                         
6090                         QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
6091                 }
6092         }
6093         private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
6094                 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
6095                 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
6096                 // Find an idle preview object
6097                 for (int i=0; i<thumbGenerators.size(); i++) {
6098                         if (thumbGenerators.get(i).mutex.tryLock()) {
6099                                 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
6100                                 thumbGenerators.get(i).loadContent(guid, html, zoom);
6101                                 return;
6102                         }
6103                 } 
6104                 if (thumbGenerators.size() >= 1) {
6105                         logger.log(logger.EXTREME, "No available thumbnail generators.  Aborting " +guid);
6106                         return;
6107                 }
6108                 
6109                 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
6110                 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
6111                 thumbGenerators.add(preview);
6112
6113                 if (preview.mutex.tryLock()) {
6114                         logger.log(logger.EXTREME, "Loading thumbnail for  " +guid);
6115                         preview.loadContent(guid, html, zoom);
6116                 }
6117                 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
6118         }
6119         
6120         
6121         
6122         //**********************************************************
6123     //**********************************************************
6124     //* Online user actions
6125     //**********************************************************
6126     //**********************************************************
6127     private void setupOnlineMenu() {
6128         if (!Global.isConnected) {
6129                 menuBar.noteOnlineHistoryAction.setEnabled(false);
6130                 menuBar.selectiveSyncAction.setEnabled(false);
6131                 return;
6132         } else {
6133                 menuBar.noteOnlineHistoryAction.setEnabled(true);
6134                 menuBar.selectiveSyncAction.setEnabled(true);
6135         }
6136     }
6137     @SuppressWarnings("unused")
6138         private void viewNoteHistory() {
6139         if (currentNoteGuid == null || currentNoteGuid.equals("")) 
6140                 return;
6141         if (currentNote.getUpdateSequenceNum() == 0) {
6142                 setMessage(tr("Note has never been synchronized."));
6143                         QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
6144                         return;
6145         }
6146         
6147         setMessage(tr("Getting Note History"));
6148         waitCursor(true);
6149         Note currentOnlineNote = null;
6150         versions = null;
6151         try {
6152                 if (Global.isPremium())
6153                         versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
6154                 else
6155                         versions = new ArrayList<NoteVersionId>();
6156                 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
6157                 } catch (EDAMUserException e) {
6158                         setMessage("EDAMUserException: " +e.getMessage());
6159                         return;
6160                 } catch (EDAMSystemException e) {
6161                         if (e.getErrorCode() == EDAMErrorCode.RATE_LIMIT_REACHED) {
6162                                 QMessageBox.warning(this, tr("Rate limit reached"), tr("Rate limit reached.\nRetry your request in " + e.getRateLimitDuration() + " seconds."));
6163                         }
6164                         setMessage("EDAMSystemException: " +e.getMessage());
6165                         return;
6166                 } catch (EDAMNotFoundException e) {
6167                         setMessage(tr("Note not found on server."));
6168                         QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
6169                         return;
6170                 } catch (TException e) {
6171                         setMessage("EDAMTransactionException: " +e.getMessage());
6172                         return;
6173                 }
6174                 
6175                 // If we've gotten this far, we have a good note.
6176                 if (historyWindow == null) {
6177                         historyWindow = new OnlineNoteHistory(logger, conn, cbObserver);
6178                         
6179                         historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
6180                         historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
6181                         historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
6182                 } else {
6183                         historyWindow.historyCombo.clear();
6184                 }
6185                 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
6186                 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
6187                         isDirty = true;
6188                 historyWindow.setCurrent(isDirty);
6189                 
6190                 loadHistoryWindowContent(currentOnlineNote);
6191                 historyWindow.load(versions);
6192                 setMessage(tr("History retrieved"));
6193                 waitCursor(false);
6194                 historyWindow.exec();
6195     }
6196     private Note reloadHistoryWindow(String selection) {
6197         waitCursor(true);
6198                 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
6199                 String dateTimeFormat = new String(fmt);
6200                 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
6201                 int index = -1;
6202                 int usn = 0;
6203                 
6204                 for (int i=0; i<versions.size(); i++) {
6205                         StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
6206                         if (versionDate.toString().equals(selection))
6207                                 index = i;
6208                 }
6209                 
6210                 if (index > -1 || selection.indexOf("Current") > -1) {
6211                         Note historyNote = null;
6212                         try {
6213                                 if (index > -1) {
6214                                         usn = versions.get(index).getUpdateSequenceNum();
6215                                         historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
6216                                 } else
6217                                         historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
6218                         } catch (EDAMUserException e) {
6219                                 setMessage("EDAMUserException: " +e.getMessage());
6220                                 waitCursor(false);
6221                                 return null;
6222                         } catch (EDAMSystemException e) {
6223                                 if (e.getErrorCode() == EDAMErrorCode.RATE_LIMIT_REACHED) {
6224                                         QMessageBox.warning(this, tr("Rate limit reached"), tr("Rate limit reached.\nRetry your request in " + e.getRateLimitDuration() + " seconds."));
6225                                 }
6226                                 setMessage("EDAMSystemException: " +e.getMessage());
6227                                 waitCursor(false);
6228                                 return null;
6229                         } catch (EDAMNotFoundException e) {
6230                                 setMessage("EDAMNotFoundException: " +e.getMessage());
6231                                 waitCursor(false);
6232                                 return null;
6233                         } catch (TException e) {
6234                                 setMessage("EDAMTransactionException: " +e.getMessage());
6235                                 waitCursor(false);
6236                                 return null;
6237                         }
6238                         
6239                         waitCursor(false);
6240                         if (historyNote != null) 
6241                                 historyWindow.setContent(historyNote);
6242                         return historyNote;
6243                 }
6244                 waitCursor(false);
6245                 return null;
6246     }
6247     private void loadHistoryWindowContent(Note note) {
6248         note.setUpdateSequenceNum(0);
6249                 historyWindow.setContent(note); 
6250     }
6251     @SuppressWarnings("unused")
6252         private void restoreHistoryNoteAsNew() {
6253         setMessage(tr("Restoring as new note."));
6254         duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
6255         setMessage(tr("Note has been restored as a new note."));
6256     }
6257     @SuppressWarnings("unused")
6258         private void restoreHistoryNote() {
6259         setMessage(tr("Restoring note."));
6260         Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
6261         conn.getNoteTable().expungeNote(n.getGuid(), true, false);
6262         n.setActive(true);
6263         n.setDeleted(0);
6264                 for (int i=0; i<n.getResourcesSize(); i++) {
6265                         n.getResources().get(i).setActive(true);
6266                         conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
6267                 }
6268                 NoteMetadata metadata = new NoteMetadata();
6269                 metadata.setGuid(n.getGuid());
6270         listManager.addNote(n, metadata);
6271         conn.getNoteTable().addNote(n, true);
6272         refreshEvernoteNote(true);
6273         setMessage(tr("Note has been restored."));
6274     }
6275     @SuppressWarnings("unused")
6276         private void setupSelectiveSync() {
6277         
6278         // Get a list of valid notebooks
6279         List<Notebook> notebooks = null; 
6280         List<Tag> tags = null;
6281         List<LinkedNotebook> linkedNotebooks = null;
6282         try {
6283                         notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
6284                         tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
6285                         linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
6286                 } catch (EDAMUserException e) {
6287                         setMessage("EDAMUserException: " +e.getMessage());
6288                         return;
6289                 } catch (EDAMSystemException e) {
6290                         if (e.getErrorCode() == EDAMErrorCode.RATE_LIMIT_REACHED) {
6291                                 QMessageBox.warning(this, tr("Rate limit reached"), tr("Rate limit reached.\nRetry your request in " + e.getRateLimitDuration() + " seconds."));
6292                         }
6293                         setMessage("EDAMSystemException: " +e.getMessage());
6294                         return;
6295                 } catch (TException e) {
6296                         setMessage("EDAMTransactionException: " +e.getMessage());
6297                         return;
6298                 } catch (EDAMNotFoundException e) {
6299                         setMessage("EDAMNotFoundException: " +e.getMessage());
6300                         return;
6301                 }
6302         
6303                 // Split up notebooks into synchronized & non-synchronized
6304         List<Notebook> ignoredBooks = new ArrayList<Notebook>();
6305         List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
6306         
6307         for (int i=notebooks.size()-1; i>=0; i--) {
6308                 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
6309                         if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
6310                                 ignoredBooks.add(notebooks.get(i));
6311                                 j=dbIgnoredNotebooks.size();
6312                         }
6313                 }
6314         }
6315         
6316         // split up tags into synchronized & non-synchronized
6317         List<Tag> ignoredTags = new ArrayList<Tag>();
6318         List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
6319         
6320         for (int i=tags.size()-1; i>=0; i--) {
6321                 for (int j=0; j<dbIgnoredTags.size(); j++) {
6322                         if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
6323                                 ignoredTags.add(tags.get(i));
6324                                 j=dbIgnoredTags.size();
6325                         }
6326                 }
6327         }
6328         
6329         // split up linked notebooks into synchronized & non-synchronized
6330         List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
6331         List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
6332         for (int i=linkedNotebooks.size()-1; i>=0; i--) {
6333                 String notebookGuid = linkedNotebooks.get(i).getGuid();
6334                 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
6335                         if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
6336                                 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
6337                                 j=dbIgnoredLinkedNotebooks.size();
6338                         }
6339                 }
6340         }
6341         
6342                 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
6343                 ignore.exec();
6344                 if (!ignore.okClicked())
6345                         return;
6346                 
6347                 waitCursor(true);
6348                 
6349                 // Clear out old notebooks & add  the new ones
6350                 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
6351                 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
6352                         conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
6353                 }
6354                 
6355                 List<String> newNotebooks = new ArrayList<String>();
6356                 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
6357                         String text = ignore.getIgnoredBookList().takeItem(i).text();
6358                         for (int j=0; j<notebooks.size(); j++) {
6359                                 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
6360                                         Notebook n = notebooks.get(j);
6361                                         conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
6362                                         j=notebooks.size();
6363                                         newNotebooks.add(n.getGuid());
6364                                 }
6365                         }
6366                 }
6367                 
6368                 // Clear out old tags & add new ones
6369                 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
6370                 for (int i=0; i<oldIgnoreTags.size(); i++) {
6371                         conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
6372                 }
6373                 
6374                 List<String> newTags = new ArrayList<String>();
6375                 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
6376                         String text = ignore.getIgnoredTagList().takeItem(i).text();
6377                         for (int j=0; j<tags.size(); j++) {
6378                                 if (tags.get(j).getName().equalsIgnoreCase(text)) {
6379                                         Tag t = tags.get(j);
6380                                         conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
6381                                         newTags.add(t.getGuid());
6382                                         j=tags.size();
6383                                 }
6384                         }
6385                 }
6386                 
6387                 // Clear out old tags & add new ones
6388                 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
6389                 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
6390                         conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
6391                 }
6392                 
6393                 List<String> newLinked = new ArrayList<String>();
6394                 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
6395                         String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
6396                         for (int j=0; j<linkedNotebooks.size(); j++) {
6397                                 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
6398                                         LinkedNotebook t = linkedNotebooks.get(j);
6399                                         conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
6400                                         newLinked.add(t.getGuid());
6401                                         j=linkedNotebooks.size();
6402                                 }
6403                         }
6404                 }
6405                 
6406                 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
6407                 waitCursor(false);
6408                 refreshLists();
6409     }
6410     
6411     
6412         //**********************************************************
6413         //**********************************************************
6414         //* XML Modifying methods
6415         //**********************************************************
6416         //**********************************************************
6417         // An error has happended fetching a resource.  let the user know
6418         private void resourceErrorMessage(int tabIndex) {
6419                 if (tabIndex < 0) {
6420                         return;
6421                 }
6422                 if (inkNote.get(tabIndex))
6423                         return;
6424                 waitCursor(false);
6425                 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
6426                 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
6427                 "In a perfect world this wouldn't happen, but it has.\n" +
6428                 "It is embarasing when a program like me, designed to save all your\n"+
6429                 "precious data, has a problem finding data.\n\n" +
6430                 "I guess life isn't fair, but I'll survive.  Somehow...\n\n" +
6431                 "In the mean time, I'm not going to let you make changes to this note.\n" +
6432                 "Don't get angry.  I'm doing it to prevent you from messing up\n"+
6433                 "this note on the Evernote servers.  Sorry."+
6434                 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
6435                 inkNote.put(tabIndex, true);
6436                 browserWindow.setReadOnly(true);
6437                 waitCursor(true);
6438         }
6439
6440         
6441         
6442         
6443         //**********************************************************
6444         //**********************************************************
6445         //* Timer functions
6446         //**********************************************************
6447         //**********************************************************
6448         // We should now do a sync with Evernote
6449         private void syncTimer() {
6450                 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
6451                 syncRunner.syncNeeded = true;
6452                 syncRunner.disableUploads = Global.disableUploads;
6453                 syncStart();
6454                 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
6455         }
6456         private void syncStart() {
6457                 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
6458                 saveNote();
6459                 if (!syncRunning && Global.isConnected) {
6460                         syncRunner.setConnected(true);
6461                         syncRunner.setKeepRunning(Global.keepRunning);
6462                         syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
6463                         
6464                         if (syncThreadsReady > 0) {
6465                                 thumbnailRunner.interrupt = true;
6466                                 saveNoteIndexWidth();
6467                                 saveNoteColumnPositions();
6468                                 if (syncRunner.addWork("SYNC")) {
6469                                         syncRunning = true;
6470                                         syncRunner.syncNeeded = true;
6471                                         syncThreadsReady--;
6472                                 }                               
6473                         }
6474                 }
6475                 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
6476         }
6477         @SuppressWarnings("unused")
6478         private void syncThreadComplete(Boolean refreshNeeded) {
6479                 setMessage(tr("Finalizing Synchronization"));
6480                 syncThreadsReady++;
6481                 syncRunning = false;
6482                 syncRunner.syncNeeded = false;
6483                 synchronizeAnimationTimer.stop();
6484                 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
6485                 saveNote();
6486                 if (currentNote == null) {
6487                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
6488                 }
6489                 listManager.refreshNoteMetadata();
6490                 noteIndexUpdated(true);
6491                 noteTableView.selectionModel().blockSignals(true);
6492                 scrollToGuid(currentNoteGuid);
6493                 noteTableView.selectionModel().blockSignals(false);
6494                 refreshEvernoteNote(false);
6495                 scrollToGuid(currentNoteGuid);
6496                 waitCursor(false);
6497                 
6498                 // Check to see if there were any shared notebook errors
6499                 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
6500                         String guid = syncRunner.errorSharedNotebooks.get(0);
6501                         String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
6502                         String localName = listManager.getNotebookNameByGuid(notebookGuid);
6503                         SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
6504                         syncDialog.exec();
6505                         if (syncDialog.okPressed()) {
6506                                 if (syncDialog.doNothing.isChecked()) {
6507                                         syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
6508                                         evernoteSync();
6509                                 }
6510                                 if (syncDialog.deleteNotebook.isChecked()) {
6511                                         conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
6512                                         conn.getNotebookTable().expungeNotebook(notebookGuid, false);
6513                                         conn.getLinkedNotebookTable().expungeNotebook(guid, false);
6514                                         conn.getLinkedNotebookTable().expungeNotebook(guid, false);
6515                                         evernoteSync();
6516                                 }
6517                                 refreshLists();
6518                                 return;
6519                         }
6520                 }
6521                 
6522                 // Finalize the synchronization
6523                 if (!syncRunner.error)
6524                         setMessage(tr("Synchronization Complete"));
6525                 else
6526                         setMessage(tr("Synchronization completed with errors.  Please check the log for details."));
6527                 logger.log(logger.MEDIUM, "Sync complete.");
6528         }   
6529         public void saveUploadAmount(long t) {
6530                 Global.saveUploadAmount(t);
6531         }
6532         public void saveUserInformation(User user) {
6533                 Global.saveUserInformation(user);
6534         }
6535         public void saveEvernoteUpdateCount(int i) {
6536                 Global.saveEvernoteUpdateCount(i);
6537         }
6538         public void refreshLists() {
6539                 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
6540                 updateQuotaBar();
6541                 // すべてのタブのノートを調べて、Dirtyならばセーブする。その後refreshListsする。
6542                 Collection<Integer> tabIndex = noteDirty.keySet();
6543                 Iterator<Integer> indexIterator = tabIndex.iterator();
6544                 HashMap<Integer, Note> saveNotes = new HashMap<Integer, Note>();
6545                 HashMap<Integer, String> saveContents = new HashMap<Integer, String>();
6546                 for (boolean isNoteDirty: noteDirty.values()) {
6547                         int index = indexIterator.next();
6548                         if (isNoteDirty) {
6549                                 saveNotes.put(index, tabWindows.get(index).getBrowserWindow().getNote());
6550                                 saveContents.put(index, tabWindows.get(index).getBrowserWindow().getContent());
6551                         }
6552                 }
6553                 
6554                 listManager.saveUpdatedNotes(saveNotes, saveContents);
6555                 listManager.refreshLists();
6556
6557                 tagIndexUpdated(true);
6558                 notebookIndexUpdated();
6559                 savedSearchIndexUpdated();
6560                 listManager.loadNotesIndex();
6561
6562                 noteTableView.selectionModel().blockSignals(true);
6563         noteIndexUpdated(true);
6564                 noteTableView.selectionModel().blockSignals(false);
6565                 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
6566         }
6567
6568         
6569         @SuppressWarnings("unused")
6570         private void authTimer() {
6571         Calendar cal = Calendar.getInstance();
6572                 
6573         // If we are not connected let's get out of here
6574         if (!Global.isConnected)
6575                 return;
6576                 
6577                 // If this is the first time through, then we need to set this
6578  //             if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime) 
6579 //                      syncRunner.authRefreshTime = cal.getTimeInMillis();
6580                 
6581 //              long now = new Date().getTime();
6582 //              if (now > Global.authRefreshTime && Global.isConnected) {
6583                         syncRunner.authRefreshNeeded = true;
6584                         syncStart();
6585 //              }
6586         }
6587         @SuppressWarnings("unused")
6588         private void authRefreshComplete(boolean goodSync) {
6589                 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
6590                 Global.isConnected = syncRunner.isConnected;
6591                 if (goodSync) {
6592 //                      authTimer.start((int)syncRunner.authTimeRemaining/4);
6593                         authTimer.start(1000*60*15);
6594                         logger.log(logger.LOW, "Authentication token has been renewed");
6595 //                      setMessage("Authentication token has been renewed.");
6596                 } else {
6597                         authTimer.start(1000*60*5);
6598                         logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
6599 //                      setMessage("Authentication token renew has failed - retry in 5 minutes.");
6600                 }
6601                 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
6602         }
6603         
6604         
6605         @SuppressWarnings("unused")
6606         private synchronized void indexTimer() {
6607                 logger.log(logger.EXTREME, "Index timer activated.  Sync running="+syncRunning);
6608                 if (syncRunning) 
6609                         return;
6610                 if (!indexDisabled && indexRunner.idle) { 
6611                         thumbnailRunner.interrupt = true;
6612                         indexRunner.addWork("SCAN");
6613                 }
6614                 logger.log(logger.EXTREME, "Leaving NeighborNote index timer");
6615         }
6616
6617         @SuppressWarnings("unused")
6618         private void indexStarted() {
6619                 setMessage(tr("Indexing notes"));
6620         }
6621         @SuppressWarnings("unused")
6622         private void indexComplete() {
6623                 setMessage(tr("Index complete"));
6624         }
6625         @SuppressWarnings("unused")
6626         private synchronized void toggleNoteIndexing() {
6627                 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
6628                 indexDisabled = !indexDisabled;
6629                 if (!indexDisabled)
6630                         setMessage(tr("Indexing is now enabled."));
6631                 else
6632                         setMessage(tr("Indexing is now disabled."));
6633                 menuBar.disableIndexing.setChecked(indexDisabled);
6634         logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
6635     }  
6636         
6637         @SuppressWarnings("unused")
6638         private void threadMonitorCheck() {
6639                 int MAX=3;
6640                 
6641                 
6642                 boolean alive;
6643                 alive = listManager.threadCheck(Global.tagCounterThreadId);
6644                 if (!alive) {
6645                         tagDeadCount++;
6646                         if (tagDeadCount > MAX && !disableTagThreadCheck) {
6647                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died.  I recommend "+
6648                                 "checking stopping NeighborNote, saving the logs for later viewing, and restarting.  Sorry."));
6649                                 disableTagThreadCheck = true;
6650                         }
6651                 } else
6652                         tagDeadCount=0;
6653                 
6654                 alive = listManager.threadCheck(Global.notebookCounterThreadId);
6655                 if (!alive) {
6656                         notebookThreadDeadCount++;
6657                         if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
6658                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died.  I recommend "+
6659                                         "checking stopping NeighborNote, saving the logs for later viewing, and restarting.  Sorry."));
6660                                 disableNotebookThreadCheck=true;
6661                         }
6662                 } else
6663                         notebookThreadDeadCount=0;
6664                 
6665                 alive = listManager.threadCheck(Global.trashCounterThreadId);
6666                 if (!alive) {
6667                         trashDeadCount++;
6668                         if (trashDeadCount > MAX && !disableTrashThreadCheck) {
6669                                 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died.  I recommend "+
6670                                         "checking stopping NeighborNote, saving the logs for later viewing, and restarting.  Sorry."));
6671                                 disableTrashThreadCheck = true;
6672                         }
6673                 } else
6674                         trashDeadCount = 0;
6675
6676                 alive = listManager.threadCheck(Global.saveThreadId);
6677                 if (!alive) {
6678                         saveThreadDeadCount++;
6679                         if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
6680                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died.  I recommend "+
6681                                         "checking stopping NeighborNote, saving the logs for later viewing, and restarting.  Sorry."));
6682                                 disableSaveThreadCheck = true;
6683                         }
6684                 } else
6685                         saveThreadDeadCount=0;
6686
6687                 if (!syncThread.isAlive()) {
6688                         syncThreadDeadCount++;
6689                         if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
6690                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died.  I recommend "+
6691                                         "checking stopping NeighborNote, saving the logs for later viewing, and restarting.  Sorry."));
6692                                 disableSyncThreadCheck = true;
6693                         }
6694                 } else
6695                         syncThreadDeadCount=0;
6696
6697                 if (!indexThread.isAlive()) {
6698                         indexThreadDeadCount++;
6699                         if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
6700                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died.  I recommend "+
6701                                         "checking stopping NeighborNote, saving the logs for later viewing, and restarting.  Sorry."));
6702                                 disableIndexThreadCheck = true;
6703                         }
6704                 } else
6705                         indexThreadDeadCount=0;
6706
6707                 if (!rensoNoteListDock.getRensoNoteList().getEnRelatedNotesThread().isAlive()) {
6708                         enRelatedNotesThreadDeadCount++;
6709                         if (enRelatedNotesThreadDeadCount > MAX && !disableENRelatedNotesThreadCheck) {
6710                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the Evernote Related Notes thread has died.  I recommend "+
6711                                         "checking stopping NeighborNote, saving the logs for later viewing, and restarting.  Sorry."));
6712                                 disableENRelatedNotesThreadCheck = true;
6713                         }
6714                 } else
6715                         enRelatedNotesThreadDeadCount=0;
6716         }
6717
6718         private void thumbnailTimer() {
6719                 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
6720                         thumbnailRunner.addWork("SCAN");
6721                 }
6722         }
6723         
6724         //**************************************************
6725         //* Backup & Restore
6726         //**************************************************
6727         @SuppressWarnings("unused")
6728         private void databaseBackup() {
6729                 QFileDialog fd = new QFileDialog(this);
6730                 fd.setFileMode(FileMode.AnyFile);
6731                 fd.setConfirmOverwrite(true);
6732                 fd.setWindowTitle(tr("Backup Database"));
6733                 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
6734                 fd.setAcceptMode(AcceptMode.AcceptSave);
6735                 if (saveLastPath == null || saveLastPath.equals(""))
6736                         fd.setDirectory(System.getProperty("user.home"));
6737                 else
6738                         fd.setDirectory(saveLastPath);
6739                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
6740                         return;
6741                 }
6742                 
6743                 
6744         waitCursor(true);
6745         saveLastPath = fd.selectedFiles().get(0);
6746         saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
6747         setMessage(tr("Backing up database"));
6748         saveNote();
6749 //      conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
6750         
6751         ExportData noteWriter = new ExportData(conn, true);
6752         String fileName = fd.selectedFiles().get(0);
6753
6754         if (!fileName.endsWith(".nnex"))
6755                 fileName = fileName +".nnex";
6756         noteWriter.exportData(fileName);
6757         setMessage(tr("Database backup completed."));
6758  
6759
6760         waitCursor(false);
6761         }
6762         @SuppressWarnings("unused")
6763         private void databaseRestore() {
6764                 if (QMessageBox.question(this, tr("Confirmation"),
6765                                 tr("This is used to restore a database from backups.\n" +
6766                                 "It is HIGHLY recommened that this only be used to populate\n" +
6767                                 "an empty database.  Restoring into a database that\n already has data" +
6768                                 " can cause problems.\n\nAre you sure you want to continue?"),
6769                                 QMessageBox.StandardButton.Yes, 
6770                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
6771                                         return;
6772                                 }
6773                 
6774                 
6775                 QFileDialog fd = new QFileDialog(this);
6776                 fd.setFileMode(FileMode.ExistingFile);
6777                 fd.setConfirmOverwrite(true);
6778                 fd.setWindowTitle(tr("Restore Database"));
6779                 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
6780                 fd.setAcceptMode(AcceptMode.AcceptOpen);
6781                 if (saveLastPath == null || saveLastPath.equals(""))
6782                         fd.setDirectory(System.getProperty("user.home"));
6783                 else
6784                         fd.setDirectory(saveLastPath);
6785                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
6786                         return;
6787                 }
6788                 
6789                 
6790                 waitCursor(true);
6791         saveLastPath = fd.selectedFiles().get(0);
6792         saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
6793
6794                 setMessage(tr("Restoring database"));
6795         ImportData noteReader = new ImportData(conn, true);
6796         noteReader.importData(fd.selectedFiles().get(0));
6797         
6798         if (noteReader.lastError != 0) {
6799                 setMessage(noteReader.getErrorMessage());
6800                 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
6801                 waitCursor(false);
6802                 return;
6803         }
6804         
6805         listManager.loadNoteTitleColors();
6806         refreshLists();
6807         refreshEvernoteNote(true);
6808         setMessage(tr("Database has been restored."));
6809         waitCursor(false);
6810         }
6811         @SuppressWarnings("unused")
6812         private void exportNotes() {
6813                 QFileDialog fd = new QFileDialog(this);
6814                 fd.setFileMode(FileMode.AnyFile);
6815                 fd.setConfirmOverwrite(true);
6816                 fd.setWindowTitle(tr("Backup Database"));
6817                 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
6818                 fd.setAcceptMode(AcceptMode.AcceptSave);
6819                 fd.setDirectory(System.getProperty("user.home"));
6820                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
6821                         return;
6822                 }
6823                 
6824                 
6825         waitCursor(true);
6826         setMessage(tr("Exporting Notes"));
6827         saveNote();
6828         
6829                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
6830                         selectedNoteGUIDs.add(currentNoteGuid);
6831                 
6832         ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
6833         String fileName = fd.selectedFiles().get(0);
6834
6835         if (!fileName.endsWith(".nnex"))
6836                 fileName = fileName +".nnex";
6837         noteWriter.exportData(fileName);
6838         setMessage(tr("Export completed."));
6839  
6840
6841         waitCursor(false);
6842                 
6843         }
6844         @SuppressWarnings("unused")
6845         private void importNotes() {
6846                 QFileDialog fd = new QFileDialog(this);
6847                 fd.setFileMode(FileMode.ExistingFile);
6848                 fd.setConfirmOverwrite(true);
6849                 fd.setWindowTitle(tr("Import Notes"));
6850                 fd.setFilter(tr("NixNote Export (*.nnex);;Evernote Export (*.enex);;All Files (*.*)"));
6851                 fd.setAcceptMode(AcceptMode.AcceptOpen);
6852                 if (saveLastPath == null || saveLastPath.equals(""))
6853                         fd.setDirectory(System.getProperty("user.home"));
6854                 else
6855                         fd.setDirectory(saveLastPath);
6856                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
6857                         return;
6858                 }
6859                 
6860                 
6861         waitCursor(true);
6862         setMessage(tr("Importing Notes"));
6863         saveNote();
6864         
6865                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
6866                         selectedNoteGUIDs.add(currentNoteGuid);
6867                 
6868         String fileName = fd.selectedFiles().get(0);
6869 //      saveLastPath.substring(0,fileName.lastIndexOf("/"));
6870
6871         if (fileName.endsWith(".nnex")) {
6872                 ImportData noteReader = new ImportData(conn, false);
6873                 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0) 
6874                         noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
6875                 else
6876                         noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
6877   
6878                 noteReader.importData(fileName);
6879         
6880                 if (noteReader.lastError != 0) {
6881                         setMessage(noteReader.getErrorMessage());
6882                         logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
6883                         waitCursor(false);
6884                         return;
6885                 }
6886         } else {
6887                 if (fileName.endsWith(".enex")) {
6888                 ImportEnex noteReader = new ImportEnex(conn, false);
6889                         if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0) 
6890                                 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
6891                         else
6892                                 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
6893   
6894                         waitCursor(false);
6895                         if (QMessageBox.question(this, tr("Confirmation"), 
6896                                         tr("Create new tags from import?"),
6897                                         QMessageBox.StandardButton.Yes, 
6898                                         QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
6899                                                                 noteReader.createNewTags = true;
6900                         } else
6901                                 noteReader.createNewTags = false;
6902                         waitCursor(true);
6903                         noteReader.importData(fileName);
6904         
6905                         if (noteReader.lastError != 0) {
6906                                 setMessage(noteReader.getErrorMessage());
6907                                 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
6908                                 waitCursor(false);
6909                                 return;
6910                         }
6911                 }
6912         }
6913         
6914         listManager.loadNoteTitleColors();
6915         refreshLists();
6916         refreshEvernoteNote(false);
6917         setMessage(tr("Notes have been imported."));
6918         waitCursor(false);
6919         
6920         setMessage(tr("Import completed."));
6921  
6922
6923         waitCursor(false);
6924                 
6925         }
6926         
6927         //**************************************************
6928         //* Duplicate a note 
6929         //**************************************************
6930         @SuppressWarnings("unused")
6931         private void duplicateNote() {
6932                 saveNote();
6933                 duplicateNote(currentNoteGuid);
6934         }
6935
6936         //**************************************************
6937         //* Action from when a user clicks Copy As URL
6938         //**************************************************
6939         @SuppressWarnings("unused")
6940         private void copyAsUrlClicked() {
6941                 QClipboard clipboard = QApplication.clipboard();
6942                 QMimeData mime = new QMimeData();
6943                 String url;
6944                 mime.setText(currentNoteGuid);
6945                 List<QUrl> urls = new ArrayList<QUrl>();
6946                 
6947                 // Start building the URL
6948                 User user = Global.getUserInformation();
6949
6950                 // Check that we have everything we need
6951                 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
6952                         SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
6953                         warning.exec();
6954                         if (!warning.neverSynchronize())
6955                                 return;
6956                         else {
6957                                 Global.setBypassSynchronizationWarning(true);
6958                                 user.setShardId("s0");
6959                                 user.setId(0);
6960                         }       
6961                 }
6962
6963                 
6964                 // Start building a list of URLs based upon the selected notes
6965         noteTableView.showColumn(Global.noteTableGuidPosition);
6966         
6967         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
6968         if (!Global.isColumnVisible("guid"))
6969                 noteTableView.hideColumn(Global.noteTableGuidPosition);
6970
6971                 // Check that the note is either synchronized, or in a local notebook
6972                 for (int i=0; i<selections.size(); i++) {
6973                         QModelIndex index;
6974                         int row = selections.get(i).row();
6975                 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
6976                 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6977                 String selectedGuid = (String)ix.values().toArray()[0];
6978                 
6979                 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6980                 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
6981                         QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
6982                                         "new notes to a local notebook."));
6983                         return; 
6984                 }
6985                 }
6986
6987                 // Start building the URLs
6988         for (int i=0; i<selections.size(); i++) {
6989                 QModelIndex index;
6990                         int row = selections.get(i).row();
6991                 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
6992                 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6993                 String selectedGuid = (String)ix.values().toArray()[0];
6994                 mime.setText(selectedGuid);
6995                 
6996                 String lid;
6997                 String gid;
6998                 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6999                 if (selectedNote.getUpdateSequenceNum() > 0) {
7000                         gid = selectedGuid;
7001                         lid = selectedGuid;
7002                 } else {
7003                         gid = "00000000-0000-0000-0000-000000000000";
7004                         lid = selectedGuid;
7005                 }
7006                 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
7007                                 +gid+"/"+lid +"/");
7008                 urls.add(new QUrl(url));
7009         }
7010                 mime.setUrls(urls);
7011                 clipboard.setMimeData(mime);
7012         }
7013         
7014         
7015         //**************************************************
7016         //* Folder Imports
7017         //**************************************************
7018         public void setupFolderImports() {
7019                 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
7020                 
7021                 if (importKeepWatcher == null)
7022                         importKeepWatcher = new QFileSystemWatcher();
7023                 if (importDeleteWatcher == null) {
7024                         importDeleteWatcher = new QFileSystemWatcher();
7025                         for (int i=0; i<records.size(); i++) {
7026                                 if (!records.get(i).keep)
7027                                         folderImportDelete(records.get(i).folder); 
7028                         }
7029                 }
7030
7031                                 
7032                 
7033 //              importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
7034                 for (int i=0; i<records.size(); i++) {
7035                         logger.log(logger.LOW, "Adding file monitor: " +records.get(i).folder);
7036                         if (records.get(i).keep) 
7037                                 importKeepWatcher.addPath(records.get(i).folder);
7038                         else
7039                                 importDeleteWatcher.addPath(records.get(i).folder);
7040                 }
7041                 
7042                 logger.log(logger.EXTREME, "List of directories being watched (kept)...");
7043                 List<String> monitorDelete = importKeepWatcher.directories();
7044                 for (int i=0; i<monitorDelete.size(); i++) {
7045                         logger.log(logger.EXTREME, monitorDelete.get(i));
7046                 }
7047                 logger.log(logger.EXTREME, "<end of list>");
7048                 logger.log(logger.EXTREME, "List of directories being watched (delete)...");
7049                 monitorDelete = importDeleteWatcher.directories();
7050                 for (int i=0; i<monitorDelete.size(); i++) {
7051                         logger.log(logger.EXTREME, monitorDelete.get(i));
7052                 }
7053                 logger.log(logger.EXTREME, "<end of list>");
7054                 
7055                 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
7056                 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
7057                 
7058                 // Look at the files already there so we don't import them again if a new file is created
7059                 if (importedFiles == null) {
7060                         importedFiles = new ArrayList<String>();
7061                         for (int j=0; j<records.size(); j++) {
7062                                 QDir dir = new QDir(records.get(j).folder);
7063                                 List<QFileInfo> list = dir.entryInfoList();
7064                                 for (int k=0; k<list.size(); k++) {
7065                                         if (list.get(k).isFile())
7066                                                 importedFiles.add(list.get(k).absoluteFilePath());
7067                                 }
7068                         }
7069                 }
7070         }
7071         
7072         // Menu folderImport action triggered
7073         public void folderImport() {
7074                 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
7075                 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
7076                 dialog.exec();
7077                 if (!dialog.okClicked())
7078                         return;
7079                 
7080                 // We have some sort of update.
7081                 if (importKeepWatcher.directories().size() > 0)
7082                         importKeepWatcher.removePaths(importKeepWatcher.directories());
7083                 if (importDeleteWatcher.directories().size() > 0)
7084                         importDeleteWatcher.removePaths(importDeleteWatcher.directories());
7085                 
7086                 conn.getWatchFolderTable().expungeAll();
7087                 // Start building from the table
7088                 for (int i=0; i<dialog.table.rowCount(); i++) {
7089                         QTableWidgetItem item = dialog.table.item(i, 0);
7090                         String dir = item.text();
7091                         item = dialog.table.item(i, 1);
7092                         String notebook = item.text();
7093                         item = dialog.table.item(i, 2);
7094                         boolean keep;
7095                         if (item.text().equalsIgnoreCase("Keep"))
7096                                 keep = true;
7097                         else
7098                                 keep = false;
7099                         
7100                         String guid = conn.getNotebookTable().findNotebookByName(notebook);
7101                         conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
7102                 }
7103                 setupFolderImports();
7104         }
7105         
7106         
7107         public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
7108                 logger.log(logger.LOW, "Inside folderImportKeep");
7109                 String whichOS = System.getProperty("os.name");
7110                 if (whichOS.contains("Windows")) 
7111                         dirName = dirName.replace('/','\\');
7112                 
7113                 FileImporter importer = new FileImporter(logger, conn);
7114                 
7115                 QDir dir = new QDir(dirName);
7116                 List<QFileInfo> list = dir.entryInfoList();
7117                 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
7118
7119                 for (int i=0; i<list.size(); i++){
7120                         logger.log(logger.LOW, "File found: " +list.get(i).fileName());
7121                         boolean redundant = false;
7122                         // Check if we've already imported this one or if it existed before
7123                         for (int j=0; j<importedFiles.size(); j++) {
7124                                 logger.log(logger.LOW, "redundant file list: " +list.get(i).absoluteFilePath());
7125                                 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
7126                                         redundant = true;
7127                         }
7128                         
7129                         logger.log(logger.LOW, "Checking if redundant: " +redundant);
7130                         if (!redundant) {
7131                                 importer.setFileInfo(list.get(i));
7132                                 importer.setFileName(list.get(i).absoluteFilePath());
7133                         
7134                         
7135                                 logger.log(logger.LOW, "File importing is a file: " +list.get(i).isFile());
7136                                 logger.log(logger.LOW, "File importing is a valid: " +importer.isValidType());
7137                                 if (list.get(i).isFile() && importer.isValidType()) {
7138                         
7139                                         if (!importer.importFile()) {
7140                                                 // If we can't get to the file, it is probably locked.  We'll try again later.
7141                                                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
7142                                                 importFilesKeep.add(list.get(i).absoluteFilePath());
7143                                         } else {
7144
7145                                                 Note newNote = importer.getNote();
7146                                                 newNote.setNotebookGuid(notebook);
7147                                                 newNote.setTitle(dir.at(i));
7148                                                 NoteMetadata metadata = new NoteMetadata();
7149                                                 metadata.setDirty(true);
7150                                                 metadata.setGuid(newNote.getGuid());
7151                                                 listManager.addNote(newNote, metadata);
7152                                                 conn.getNoteTable().addNote(newNote, true);
7153                                                 noteTableView.insertRow(newNote, metadata, true, -1);
7154                                                 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
7155                                                 listManager.countNotebookResults(listManager.getNoteIndex());
7156                                                 importedFiles.add(list.get(i).absoluteFilePath());
7157                                         }
7158                                 }
7159                         }
7160                 }
7161         
7162         
7163         }
7164         
7165         public void folderImportDelete(String dirName) {
7166                 logger.log(logger.LOW, "Inside folderImportDelete");
7167                 String whichOS = System.getProperty("os.name");
7168                 if (whichOS.contains("Windows")) 
7169                         dirName = dirName.replace('/','\\');
7170                 
7171                 FileImporter importer = new FileImporter(logger, conn);
7172                 QDir dir = new QDir(dirName);
7173                 List<QFileInfo> list = dir.entryInfoList();
7174                 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
7175                 
7176                 for (int i=0; i<list.size(); i++){
7177                         logger.log(logger.LOW, "File found: " +list.get(i).fileName());
7178                         importer.setFileInfo(list.get(i));
7179                         importer.setFileName(list.get(i).absoluteFilePath());
7180                         
7181                         logger.log(logger.LOW, "File importing is a file: " +list.get(i).isFile());
7182                         logger.log(logger.LOW, "File importing is a valid: " +importer.isValidType());
7183                         if (list.get(i).isFile() && importer.isValidType()) {
7184                 
7185                                 if (!importer.importFile()) {
7186                                         // If we can't get to the file, it is probably locked.  We'll try again later.
7187                                         logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
7188                                         importFilesKeep.add(list.get(i).absoluteFilePath());
7189                                 } else {
7190                 
7191                                         Note newNote = importer.getNote();
7192                                         newNote.setNotebookGuid(notebook);
7193                                         newNote.setTitle(dir.at(i));
7194                                         NoteMetadata metadata = new NoteMetadata();
7195                                         metadata.setDirty(true);
7196                                         metadata.setGuid(newNote.getGuid());
7197                                         listManager.addNote(newNote, metadata);
7198                                         conn.getNoteTable().addNote(newNote, true);
7199                                         noteTableView.insertRow(newNote, metadata, true, -1);
7200                                         listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
7201                                         listManager.countNotebookResults(listManager.getNoteIndex());
7202                                         dir.remove(dir.at(i));
7203                                 }
7204                         }
7205                 }
7206         }
7207         
7208         
7209         //**************************************************
7210         //* External events
7211         //**************************************************
7212         private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
7213                 logger.log(logger.HIGH, "Entering exernalFileEdited");
7214
7215                 // Strip URL prefix and base dir path
7216                 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
7217                 String name = fileName.replace(dPath, "");
7218                 int pos = name.lastIndexOf('.');
7219                 String guid = name;
7220                 if (pos > -1) {
7221                         guid = guid.substring(0,pos);
7222                 }
7223                 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
7224                 if (pos > -1) {
7225                         guid = name.substring(0, pos);
7226                 }
7227                 
7228                 QFile file = new QFile(fileName);
7229         if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
7230                 // If we can't get to the file, it is probably locked.  We'll try again later.
7231                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
7232                 externalFiles.add(fileName);
7233                 return;
7234                 }
7235                 QByteArray binData = file.readAll();
7236         file.close();
7237         if (binData.size() == 0) {
7238                 // If we can't get to the file, it is probably locked.  We'll try again later.
7239                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
7240                 externalFiles.add(fileName);
7241                 return;
7242         }
7243         
7244         Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
7245         if (r==null)
7246                 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
7247         if (r == null || r.getData() == null || r.getData().getBody() == null)
7248                 return;
7249         String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
7250         MessageDigest md = MessageDigest.getInstance("MD5");
7251                 md.update(binData.toByteArray());
7252                 byte[] hash = md.digest();
7253         String newHash = Global.byteArrayToHexString(hash);
7254         if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
7255                 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
7256         }
7257         if (externalWindows.containsKey(r.getNoteGuid())) {
7258                 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(), 
7259                                 r.getGuid(), oldHash, newHash);
7260         }
7261         conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
7262         Data data = r.getData();
7263         data.setBody(binData.toByteArray());
7264         data.setBodyHash(hash);
7265         logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
7266         r.setData(data);
7267         conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
7268         
7269         if (r.getNoteGuid().equals(currentNoteGuid)) {
7270                         QWebSettings.setMaximumPagesInCache(0);
7271                         QWebSettings.setObjectCacheCapacities(0, 0, 0);
7272                         refreshEvernoteNote(true);
7273                         browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
7274         }
7275         
7276         if (externalWindows.containsKey(r.getNoteGuid())) {
7277                 QWebSettings.setMaximumPagesInCache(0);
7278                         QWebSettings.setObjectCacheCapacities(0, 0, 0);
7279                         externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
7280                         
7281         }
7282         
7283                 logger.log(logger.HIGH, "Exiting externalFielEdited");
7284         }
7285         // This is a timer event that tries to save any external files that were edited.  This
7286         // is only needed if we couldn't save a file earlier.
7287         public void externalFileEditedSaver() {
7288                 for (int i=externalFiles.size()-1; i>=0; i--) {
7289                         try {
7290                                 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
7291                                 externalFileEdited(externalFiles.get(i));
7292                                 externalFiles.remove(i);
7293                         } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
7294                 }
7295                 for (int i=0; i<importFilesKeep.size(); i++) {
7296                         try {
7297                                 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
7298                                 folderImportKeep(importFilesKeep.get(i));
7299                                 importFilesKeep.remove(i);
7300                         } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
7301                 }
7302                 for (int i=0; i<importFilesDelete.size(); i++) {
7303                         logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
7304                         folderImportDelete(importFilesDelete.get(i));
7305                         importFilesDelete.remove(i);
7306                 }
7307         }
7308         
7309         
7310         
7311         
7312         // If an attachment on the current note was edited, we need to update the current notes's hash
7313         // Update a note content's hash.  This happens if a resource is edited outside of NN
7314         public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
7315                 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
7316                 int endPos;
7317                 for (;position>-1;) {
7318                         endPos = browser.getContent().indexOf(">", position+1);
7319                         String oldSegment = browser.getContent().substring(position,endPos);
7320                         int hashPos = oldSegment.indexOf("hash=\"");
7321                         int hashEnd = oldSegment.indexOf("\"", hashPos+7);
7322                         String hash = oldSegment.substring(hashPos+6, hashEnd);
7323                         if (hash.equalsIgnoreCase(oldHash)) {
7324                                 String newSegment = oldSegment.replace(oldHash, newHash);
7325                                 String content = browser.getContent().substring(0,position) +
7326                                                  newSegment +
7327                                                  browser.getContent().substring(endPos);
7328                                 browser.setContent(new QByteArray(content));;
7329                         }
7330                         
7331                         position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
7332                 }
7333         }
7334
7335
7336         //*************************************************
7337         //* Minimize to tray
7338         //*************************************************
7339         @Override
7340         public void changeEvent(QEvent e) {
7341                 if (e.type() == QEvent.Type.WindowStateChange) {
7342                         if (QSystemTrayIcon.isSystemTrayAvailable()) {
7343                                 if (isMinimized() && (Global.showTrayIcon() || Global.showTrayIcon())) {
7344                                         e.accept();
7345                                         QTimer.singleShot(10, this, "hide()");
7346                                         return;
7347                                 }
7348                                 if (isMaximized())
7349                                         windowMaximized = true;
7350                                 else 
7351                                         windowMaximized = false;
7352                         }
7353                 }
7354         }
7355         
7356         //*************************************************
7357         //* Check database userid & passwords
7358         //*************************************************
7359         private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
7360                         Connection connection;
7361                         
7362                         try {
7363                                 Class.forName("org.h2.Driver");
7364                         } catch (ClassNotFoundException e1) {
7365                                 e1.printStackTrace();
7366                                 System.exit(16);
7367                         }
7368
7369                         try {
7370                                 String passwordString = null;
7371                                 if (cypherPassword==null || cypherPassword.trim().equals(""))
7372                                         passwordString = userPassword;
7373                                 else
7374                                         passwordString = cypherPassword+" "+userPassword;
7375                                 connection = DriverManager.getConnection(url,userid,passwordString);
7376                         } catch (SQLException e) {
7377                                 return false;
7378                         }
7379                         try {
7380                                 connection.close();
7381                         } catch (SQLException e) {
7382                                 e.printStackTrace();
7383                         }
7384                         return true;
7385         }
7386
7387         //*************************************************
7388         //* View / Hide source HTML for a note
7389         //*************************************************
7390         public void viewSource() {
7391                 // すべてのタブに対して
7392         for(int i = 0; i < tabBrowser.count(); i++){
7393                 BrowserWindow browser = ((TabBrowse) tabBrowser.widget(i)).getBrowserWindow();
7394                 browser.showSource(menuBar.viewSource.isChecked());
7395         }
7396         }
7397         //*************************************************
7398         // Block the program.  This is used for things  
7399         // like async web calls.
7400         //*************************************************
7401         @SuppressWarnings("unused")
7402         private void blockApplication(BrowserWindow b) {
7403                 // Block all signals
7404                 waitCursor(true);
7405                 blockSignals(true);
7406                 
7407                 blockTimer = new QTimer();
7408                 blockTimer.setSingleShot(true);
7409                 blockTimer.setInterval(15000);
7410                 blockTimer.timeout.connect(this, "unblockApplication()");
7411                 blockingWindow  = b;
7412                 blockTimer.start();
7413         }
7414         
7415         @SuppressWarnings("unused")
7416         private void unblockApplication() {
7417                 waitCursor(false);
7418                 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
7419                         QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
7420                         blockingWindow.unblockTime = -1;
7421                         blockingWindow.awaitingHttpResponse = false;
7422                 }
7423                 blockingWindow = null;
7424                 blockSignals(false);
7425         }
7426         
7427         // タブが変更された
7428         private void tabWindowChanged(int index) {
7429                 if (index < 0 || index >= tabBrowser.count()) {
7430                         return;
7431                 }
7432                 
7433                 saveNote();
7434
7435                 TabBrowse tab = (TabBrowse) tabBrowser.widget(index);
7436                 if (tab.getBrowserWindow().getNote() != null) {
7437                         currentNoteGuid = tab.getBrowserWindow().getNote().getGuid();
7438                         currentNote = tab.getBrowserWindow().getNote();
7439                 } else {
7440                         currentNoteGuid = "";
7441                         currentNote = null;
7442                 }
7443
7444                 // 選択ノートを更新
7445                 selectedNoteGUIDs.clear();
7446                 if (currentNoteGuid != null && !currentNoteGuid.equals("")) {
7447                         selectedNoteGUIDs.add(currentNoteGuid);
7448                 }
7449                 
7450                 // browserWindowを更新
7451                 browserWindow.noteSignal.noteChanged.disconnect(this,"setNoteDirty()");
7452                 browserWindow.focusLost.disconnect(this, "saveNote()");
7453                 browserWindow = tab.getBrowserWindow();
7454                 browserWindow.noteSignal.noteChanged.connect(this, "setNoteDirty()");
7455                 browserWindow.focusLost.connect(this, "saveNote()");
7456                 // メニューバーのボタンを新しいbrowserWindowに合わせる
7457                 menuBar.refreshTargetWindow();
7458                 
7459                 // 現在ゴミ箱かつ移るタブがアクティブなら通常テーブルに、現在通常テーブルかつこれから非アクティブのタブに移るならゴミ箱を表示させる
7460                 boolean nextIsActive;
7461                 if (tab.getBrowserWindow().getNote() != null) {
7462                         nextIsActive = tab.getBrowserWindow().getNote().isActive();
7463                 } else {
7464                         nextIsActive = true;
7465                 }
7466                 if (Global.showDeleted && nextIsActive) {
7467                         switchNoteTable(false);
7468                 } else if (!Global.showDeleted && !nextIsActive) {
7469                         switchNoteTable(true);
7470                 }
7471
7472                 // noteTableViewの選択を変更するとselectionChangedが発生してしまうので一度切断
7473                 noteTableView.selectionModel().selectionChanged.disconnect(this,"noteTableSelection()");
7474                 scrollToGuid(currentNoteGuid);
7475                 // 再接続
7476                 noteTableView.selectionModel().selectionChanged.connect(this,"noteTableSelection()");
7477
7478                 menuBar.noteDuplicateAction.setEnabled(true);
7479                 menuBar.noteOnlineHistoryAction.setEnabled(true);
7480                 menuBar.noteMergeAction.setEnabled(true);
7481                 
7482                 if (Global.showDeleted) {
7483                         menuBar.noteDuplicateAction.setEnabled(false);
7484                 }
7485                 if (!Global.isConnected) {
7486                         menuBar.noteOnlineHistoryAction.setEnabled(false);
7487                 }
7488                 menuBar.noteMergeAction.setEnabled(false);
7489                 try {
7490                         int row = noteTableView.selectionModel().selectedRows().get(0).row();
7491                         if (row == 0)
7492                                 upButton.setEnabled(false);
7493                         else
7494                                 upButton.setEnabled(true);
7495                         if (row < listManager.getNoteTableModel().rowCount() - 1)
7496                                 downButton.setEnabled(true);
7497                         else
7498                                 downButton.setEnabled(false);
7499                 } catch (Exception e) {
7500                         upButton.setEnabled(false);
7501                         downButton.setEnabled(false);
7502                 }
7503                 
7504                 int currentIndex = tabBrowser.currentIndex();
7505                 ArrayList<String> histGuids = historyGuids.get(currentIndex);
7506                 int histPosition = historyPosition.get(currentIndex);
7507
7508                 // prev, nextボタンの有効・無効化
7509                 nextButton.setEnabled(true);
7510                 prevButton.setEnabled(true);
7511
7512                 if (histPosition <= 1){
7513                         prevButton.setEnabled(false);
7514                 }
7515                 if (histPosition == histGuids.size()){
7516                         nextButton.setEnabled(false);
7517                 }
7518
7519                 refreshEvernoteNote(true);
7520
7521                 // 連想ノートリストを更新
7522                 rensoNoteListDock.getRensoNoteList().refreshRensoNoteList(currentNoteGuid);
7523         }
7524         
7525         // 生存ノートテーブル→ゴミ箱(またはその逆)に切り替える
7526         private void switchNoteTable(boolean toDeleted) {
7527         clearNotebookFilter();
7528         clearTagFilter();
7529         clearAttributeFilter();
7530         clearSavedSearchFilter();
7531         
7532         listManager.getSelectedNotebooks().clear();
7533         listManager.getSelectedTags().clear();
7534         listManager.setSelectedSavedSearch("");
7535     
7536         // toggle the add buttons
7537         newButton.setEnabled(!newButton.isEnabled());
7538         menuBar.noteAdd.setEnabled(newButton.isEnabled());
7539         menuBar.noteAddNewTab.setEnabled(newButton.isEnabled());
7540                 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
7541                         menuBar.noteAddNewTab.setEnabled(false);
7542                 }
7543         menuBar.noteAdd.setVisible(true);
7544         
7545         if (!toDeleted) {       // 生存ノートテーブルへ
7546                 trashTree.itemSelectionChanged.disconnect(this, "trashTreeSelection()");
7547                 trashTree.clearSelection();
7548                 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
7549                 Global.showDeleted = false;
7550                 menuBar.noteRestoreAction.setEnabled(false);
7551                 menuBar.noteRestoreAction.setVisible(false);
7552                 // ゴミ箱から元の画面に戻す。連想ノートリストをONに。
7553                 rensoNoteListDock.setEnabled(true);
7554         } else {        // ゴミ箱へ
7555                 trashTree.itemSelectionChanged.disconnect(this, "trashTreeSelection()");
7556                 trashTree.setCurrentItem(trashTree.getTrashItem());
7557                 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
7558                 Global.showDeleted = true;
7559                 menuBar.noteRestoreAction.setEnabled(true);
7560                 menuBar.noteRestoreAction.setVisible(true);
7561                 // ゴミ箱を開く。連想ノートリストをOFFに。
7562                 rensoNoteListDock.setEnabled(false);
7563         }
7564         
7565         listManager.loadNotesIndex();
7566         // noteTableViewの選択を変更するとselectionChangedが発生してしまうので一度切断
7567         noteTableView.selectionModel().selectionChanged.disconnect(this,"noteTableSelection()");
7568         noteIndexUpdated(false);
7569         // 再接続
7570         noteTableView.selectionModel().selectionChanged.connect(this,"noteTableSelection()");
7571         
7572         browserWindow.setReadOnly(!newButton.isEnabled());
7573         }
7574
7575         // ユーザが連想ノートリストのアイテムを選択した時の処理
7576         @SuppressWarnings("unused")
7577         private void rensoNoteItemPressed(QListWidgetItem current) {
7578                 logger.log(logger.HIGH, "Nevernote.rensoNoteSelectionChangeに入った");
7579
7580                 rensoNotePressedItemGuid = rensoNoteListDock.getRensoNoteList().getNoteGuid(current);
7581                 
7582                 // 右クリックだったら終了
7583                 if (QApplication.mouseButtons().isSet(MouseButton.RightButton)) {
7584                         return;
7585                 }
7586                 
7587                 saveNote();
7588
7589                 String prevCurrentNoteGuid = new String(currentNoteGuid);
7590                 
7591                 for (int i = 0; i < noteTableView.model().rowCount(); i++) {
7592                         QModelIndex modelIndex = noteTableView.model().index(i,
7593                                         Global.noteTableGuidPosition);
7594                         if (modelIndex != null) {
7595                                 SortedMap<Integer, Object> ix = noteTableView.model().itemData(
7596                                                 modelIndex);
7597                                 String tableGuid = (String) ix.values().toArray()[0];
7598                                 if (tableGuid.equals(rensoNotePressedItemGuid)) {
7599                                         noteTableView.selectRow(i);
7600                                         break;
7601                                 }
7602                         }
7603                 }
7604                 
7605                 // 連想ノートリストアイテムクリック操作を記録
7606                 conn.getHistoryTable().addHistory("rensoItemClick", prevCurrentNoteGuid, currentNoteGuid);
7607
7608                 logger.log(logger.HIGH, "Nevernote.rensoNoteSelectionChangeを出た");
7609         }
7610         
7611         // 関連ノートリストからノートを除外する
7612         @SuppressWarnings("unused")
7613         private void excludeNote() {
7614                 if (rensoNotePressedItemGuid != null) {
7615                         saveNote();
7616                         excludeNote(rensoNotePressedItemGuid);
7617                 }
7618         }
7619         
7620         // 関連ノートリストからノートを除外する
7621         private void excludeNote(String guid) {
7622                 if (Global.verifyExclude()) {
7623                         String msg;
7624                         Note note = conn.getNoteTable().getNote(guid, false, false, false, false, false);
7625                         String title = note.getTitle();
7626                         if (title != null) {
7627                                 msg = new String(tr("Exclude note \"") +title +"\"?");
7628                         } else {                                
7629                                 msg = new String(tr("Exclude note selected note?"));
7630                         }
7631                         
7632                         if (QMessageBox.question(this, tr("Confirmation"), msg,
7633                                         QMessageBox.StandardButton.Yes, 
7634                                         QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
7635                                         return;
7636                         }
7637                 }
7638                 
7639                 // Historyデータベースから除外するノートのデータを削除
7640                 conn.getHistoryTable().expungeHistory(guid, currentNoteGuid);
7641                 
7642                 // 除外ノートテーブルに追加
7643                 conn.getExcludedTable().addExclusion(guid, currentNoteGuid);
7644                 
7645                 rensoNoteListDock.getRensoNoteList().refreshRensoNoteList(currentNoteGuid);
7646         }
7647         
7648         // 関連ノートリストのノートにスターを付ける
7649         @SuppressWarnings("unused")
7650         private void starNote() {
7651                 if (rensoNotePressedItemGuid != null) {
7652                         saveNote();
7653                         starNote(rensoNotePressedItemGuid);
7654                 }
7655         }
7656         
7657         // 関連ノートリストのノートにスターを付ける
7658         private void starNote(String guid) {
7659                 // スター付きノートテーブルに追加
7660                 conn.getStaredTable().addStaredItem(currentNoteGuid, guid);
7661                 
7662                 rensoNoteListDock.getRensoNoteList().refreshRensoNoteList(currentNoteGuid);
7663         }
7664         
7665         // 関連ノートリストのノートからスターを外す
7666         @SuppressWarnings("unused")
7667         private void unstarNote() {
7668                 if (rensoNotePressedItemGuid != null) {
7669                         saveNote();
7670                         unstarNote(rensoNotePressedItemGuid);
7671                 }
7672         }
7673         
7674         // 関連ノートリストのノートからスターを外す
7675         private void unstarNote(String guid) {
7676                 // スター付きノートテーブルから削除
7677                 conn.getStaredTable().removeStaredItem(currentNoteGuid, guid);
7678                 
7679                 rensoNoteListDock.getRensoNoteList().refreshRensoNoteList(currentNoteGuid);
7680         }
7681         
7682         // currentNoteGuidを返す
7683         public String getCurrentNoteGuid() {
7684                 return currentNoteGuid;
7685         }
7686         
7687         @SuppressWarnings("unused")
7688         // タブ入れ替えによってタブインデックスが変わったので、インデックスで管理しているハッシュマップ達も入れ替える
7689         private void tabIndexChanged(int from, int to) {
7690                 // tabWindows
7691                 TabBrowse tab = tabWindows.get(from);
7692                 tabWindows.put(from, tabWindows.get(to));
7693                 tabWindows.put(to, tab);
7694                 // noteDirty
7695                 boolean isNoteDirty = noteDirty.get(from);
7696                 noteDirty.put(from, noteDirty.get(to));
7697                 noteDirty.put(to, isNoteDirty);
7698                 // inkNote
7699                 boolean isInkNote = inkNote.get(from);
7700                 inkNote.put(from, inkNote.get(to));
7701                 inkNote.put(to, isInkNote);
7702                 // readOnly
7703                 boolean isReadOnly = readOnly.get(from);
7704                 readOnly.put(from, readOnly.get(to));
7705                 readOnly.put(to, isReadOnly);
7706                 // historyGuids
7707                 ArrayList<String> histGuids = historyGuids.get(from);
7708                 historyGuids.put(from, historyGuids.get(to));
7709                 historyGuids.put(to, histGuids);
7710                 // historyPosition
7711                 int histPosition = historyPosition.get(from);
7712                 historyPosition.put(from, historyPosition.get(to));
7713                 historyPosition.put(to, histPosition);
7714                 // fromHistory
7715                 boolean fromHist = fromHistory.get(from);
7716                 fromHistory.put(from,  fromHistory.get(to));
7717                 fromHistory.put(to, fromHist);
7718         }
7719         
7720         // 連想ノートリストのgetter
7721         public RensoNoteList getRensoNoteList() {
7722                 return rensoNoteListDock.getRensoNoteList();
7723         }
7724         
7725         // 帯域制限の超過をユーザに通知
7726         @SuppressWarnings("unused")
7727         private void informRateLimit(Integer rateLimitDuration) {
7728                 QMessageBox.warning(this, tr("Rate limit reached"), tr("Rate limit reached.\nRetry your request in " + rateLimitDuration + " seconds."));
7729         }
7730         
7731         // ツールバーの「新規」ボタンの接続スロットを設定
7732         public void connectNewButtonSlot(String slot) {
7733                 newButton.triggered.disconnect();
7734                 newButton.triggered.connect(this, slot);
7735         }
7736 }