OSDN Git Service

最後に開いていたタブのインデックスを正しく復元できるように修正。
[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.apache.thrift.TException;
51 import org.h2.tools.ChangeFileEncryption;
52
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.trolltech.qt.QThread;
70 import com.trolltech.qt.core.QByteArray;
71 import com.trolltech.qt.core.QDateTime;
72 import com.trolltech.qt.core.QDir;
73 import com.trolltech.qt.core.QEvent;
74 import com.trolltech.qt.core.QFile;
75 import com.trolltech.qt.core.QFileInfo;
76 import com.trolltech.qt.core.QFileSystemWatcher;
77 import com.trolltech.qt.core.QIODevice;
78 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
79 import com.trolltech.qt.core.QLocale;
80 import com.trolltech.qt.core.QMimeData;
81 import com.trolltech.qt.core.QModelIndex;
82 import com.trolltech.qt.core.QSize;
83 import com.trolltech.qt.core.QTemporaryFile;
84 import com.trolltech.qt.core.QTextCodec;
85 import com.trolltech.qt.core.QTextStream;
86 import com.trolltech.qt.core.QThreadPool;
87 import com.trolltech.qt.core.QTimer;
88 import com.trolltech.qt.core.QTranslator;
89 import com.trolltech.qt.core.QUrl;
90 import com.trolltech.qt.core.Qt;
91 import com.trolltech.qt.core.Qt.BGMode;
92 import com.trolltech.qt.core.Qt.DockWidgetArea;
93 import com.trolltech.qt.core.Qt.ItemDataRole;
94 import com.trolltech.qt.core.Qt.KeyboardModifier;
95 import com.trolltech.qt.core.Qt.MouseButton;
96 import com.trolltech.qt.core.Qt.SortOrder;
97 import com.trolltech.qt.core.Qt.WidgetAttribute;
98 import com.trolltech.qt.gui.QAbstractItemView;
99 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
100 import com.trolltech.qt.gui.QAction;
101 import com.trolltech.qt.gui.QApplication;
102 import com.trolltech.qt.gui.QClipboard;
103 import com.trolltech.qt.gui.QCloseEvent;
104 import com.trolltech.qt.gui.QColor;
105 import com.trolltech.qt.gui.QComboBox;
106 import com.trolltech.qt.gui.QCursor;
107 import com.trolltech.qt.gui.QDesktopServices;
108 import com.trolltech.qt.gui.QDialog;
109 import com.trolltech.qt.gui.QDockWidget;
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.config.InitializationException;
150 import cx.fbn.nevernote.config.StartupConfig;
151 import cx.fbn.nevernote.dialog.AccountDialog;
152 import cx.fbn.nevernote.dialog.ConfigDialog;
153 import cx.fbn.nevernote.dialog.DBEncryptDialog;
154 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
155 import cx.fbn.nevernote.dialog.DatabaseStatus;
156 import cx.fbn.nevernote.dialog.FindDialog;
157 import cx.fbn.nevernote.dialog.IgnoreSync;
158 import cx.fbn.nevernote.dialog.LogFileDialog;
159 import cx.fbn.nevernote.dialog.NotebookArchive;
160 import cx.fbn.nevernote.dialog.NotebookEdit;
161 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
162 import cx.fbn.nevernote.dialog.PublishNotebook;
163 import cx.fbn.nevernote.dialog.SavedSearchEdit;
164 import cx.fbn.nevernote.dialog.SetIcon;
165 import cx.fbn.nevernote.dialog.ShareNotebook;
166 import cx.fbn.nevernote.dialog.SharedNotebookSyncError;
167 import cx.fbn.nevernote.dialog.StackNotebook;
168 import cx.fbn.nevernote.dialog.SynchronizationRequiredWarning;
169 import cx.fbn.nevernote.dialog.TagEdit;
170 import cx.fbn.nevernote.dialog.TagMerge;
171 import cx.fbn.nevernote.dialog.ThumbnailViewer;
172 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
173 import cx.fbn.nevernote.dialog.WatchFolder;
174 import cx.fbn.nevernote.evernote.NoteMetadata;
175 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
176 import cx.fbn.nevernote.filters.FilterEditorTags;
177 import cx.fbn.nevernote.gui.AttributeTreeWidget;
178 import cx.fbn.nevernote.gui.BrowserWindow;
179 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
180 import cx.fbn.nevernote.gui.ExternalBrowse;
181 import cx.fbn.nevernote.gui.MainMenuBar;
182 import cx.fbn.nevernote.gui.NotebookTreeWidget;
183 import cx.fbn.nevernote.gui.RensoNoteList;
184 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
185 import cx.fbn.nevernote.gui.SearchPanel;
186 import cx.fbn.nevernote.gui.TabBrowse;
187 import cx.fbn.nevernote.gui.TabBrowserWidget;
188 import cx.fbn.nevernote.gui.TableView;
189 import cx.fbn.nevernote.gui.TagTreeWidget;
190 import cx.fbn.nevernote.gui.Thumbnailer;
191 import cx.fbn.nevernote.gui.TrashTreeWidget;
192 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
193 import cx.fbn.nevernote.neighbornote.ClipBoardObserver;
194 import cx.fbn.nevernote.oauth.OAuthTokenizer;
195 import cx.fbn.nevernote.oauth.OAuthWindow;
196 import cx.fbn.nevernote.sql.DatabaseConnection;
197 import cx.fbn.nevernote.sql.WatchFolderRecord;
198 import cx.fbn.nevernote.threads.IndexRunner;
199 import cx.fbn.nevernote.threads.SyncRunner;
200 import cx.fbn.nevernote.threads.ThumbnailRunner;
201 import cx.fbn.nevernote.utilities.AESEncrypter;
202 import cx.fbn.nevernote.utilities.ApplicationLogger;
203 import cx.fbn.nevernote.utilities.FileImporter;
204 import cx.fbn.nevernote.utilities.FileUtils;
205 import cx.fbn.nevernote.utilities.ListManager;
206 import cx.fbn.nevernote.utilities.SyncTimes;
207 import cx.fbn.nevernote.xml.ExportData;
208 import cx.fbn.nevernote.xml.ImportData;
209 import cx.fbn.nevernote.xml.ImportEnex;
210 import cx.fbn.nevernote.xml.NoteFormatter;
211
212
213 public class NeverNote extends QMainWindow{
214         
215         QStatusBar                              statusBar;                                      // Application status bar
216         
217         DatabaseConnection              conn;
218         
219         MainMenuBar                             menuBar;                                        // Main menu bar
220         FindDialog                              find;                                           // Text search in note dialog
221         List<String>                    emitLog;                                        // Messages displayed in the status bar;
222         QSystemTrayIcon                 trayIcon;                                       // little tray icon
223         QMenu                                   trayMenu;                                       // System tray menu
224         QAction                                 trayExitAction;                         // Exit the application
225         QAction                                 trayShowAction;                         // toggle the show/hide action          
226         QAction                                 trayAddNoteAction;                      // Add a note from the system tray
227         QNetworkAccessManager   versionChecker;                         // Used when checking for new versions
228         
229     NotebookTreeWidget          notebookTree;                           // List of notebooks
230     AttributeTreeWidget         attributeTree;                          // List of note attributes
231     TagTreeWidget                       tagTree;                                        // list of user created tags
232     SavedSearchTreeWidget       savedSearchTree;                        // list of saved searches
233     TrashTreeWidget                     trashTree;                                      // Trashcan
234     TableView                           noteTableView;                          //      List of notes (the widget).
235
236     public BrowserWindow        browserWindow;                          // Window containing browser & labels
237     public QToolBar             toolBar;                                        // The tool bar under the menu
238     QComboBox                           searchField;                            // search filter bar on the toolbar;
239     QShortcut                           searchShortcut;                         // Shortcut to search bar
240     boolean                                     searchPerformed = false;        // Search was done?
241     QuotaProgressBar            quotaBar;                                       // The current quota usage
242     
243     ApplicationLogger           logger;
244     List<String>                        selectedNotebookGUIDs;          // List of notebook GUIDs
245     List<String>                        selectedTagGUIDs;                       // List of selected tag GUIDs
246     List<String>                        selectedNoteGUIDs;                      // List of selected notes
247     String                                      selectedSavedSearchGUID;        // Currently selected saved searches
248     private final HashMap<String, ExternalBrowse>       externalWindows;        // Notes being edited by an external window;
249     
250     NoteFilter                          filter;                                         // Note filter
251     String                                      currentNoteGuid;                        // GUID of the current note 
252     Note                                        currentNote;                            // The currently viewed note
253     // ICHANGED
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     boolean                             disableTagThreadCheck=false;
332     boolean                             disableNotebookThreadCheck=false;
333     boolean                             disableTrashThreadCheck=false;
334     boolean                             disableSaveThreadCheck=false;
335     boolean                             disableSyncThreadCheck=false;
336     boolean                             disableIndexThreadCheck=false;
337     
338     HashMap<String, String>             noteCache;                      // Cash of note content 
339     HashMap<String, Boolean>    readOnlyCache;          // List of cashe notes that are read-only
340     HashMap<String, Boolean>    inkNoteCache;           // List of cache notes that are ink notes 
341         // ICHANGED
342         HashMap<Integer, ArrayList<String>> historyGuids;  // タブごとの以前見たノートのGUID
343         HashMap<Integer, Integer> historyPosition; // Position within the viewed items
344         HashMap<Integer, Boolean> fromHistory; // Is this from the history queue?
345         
346     String                              trashNoteGuid;                          // Guid to restore / set into or out of trash to save position
347     List<Thumbnailer>   thumbGenerators;                                // generate preview image
348     ThumbnailViewer             thumbnailViewer;                        // View preview thumbnail; 
349     boolean                             encryptOnShutdown;                      // should I encrypt when I close?
350     boolean                             decryptOnShutdown;                      // should I decrypt on shutdown;
351     String                              encryptCipher;                          // What cipher should I use?
352     //Signal0                   minimizeToTray;
353     boolean                             windowMaximized = false;        // Keep track of the window state for restores
354     List<String>                pdfReadyQueue;                          // Queue of PDFs that are ready to be rendered.
355     List<QPixmap>               syncIcons;                                      // Array of icons used in sync animation
356     private boolean             closeAction = false;            // Used to say when to close or when to minimize
357     private static Logger log = Logger.getLogger(NeverNote.class); 
358     private String              saveLastPath;                           // last path we used
359     private final QTimer                messageTimer;                           // Timer to clear the status message.
360     private QTimer              blockTimer;
361     BrowserWindow               blockingWindow;
362     
363         // ICHANGED
364         private final TabBrowserWidget tabBrowser; // ブラウザウィンドウをタブ化
365         private final HashMap<Integer, TabBrowse> tabWindows; // タブウィンドウ
366         private final RensoNoteList rensoNoteList; // 連想ノートリスト
367         private final QDockWidget rensoNoteListDock; // 連想ノートリストドックウィジェット
368         ClipBoardObserver cbObserver;
369         String rensoNotePressedItemGuid;
370         
371     String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
372         
373         
374     //***************************************************************
375     //***************************************************************
376     //** Constructor & main entry point
377     //***************************************************************
378     //***************************************************************
379     // Application Constructor  
380         @SuppressWarnings("static-access")
381         public NeverNote(DatabaseConnection dbConn)  {
382                 // ICHANGED
383                 cbObserver = new ClipBoardObserver();
384                 
385                 conn = dbConn;          
386                 if (conn.getConnection() == null) {
387                         String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
388                                 "is accessing the database or NeighborNote is already running.\n\n" +
389                                 "Please end any other process or shutdown the other NeighborNote before starting.\n\nExiting program."));
390                         
391             QMessageBox.critical(null, tr("Database Connection Error") ,msg);
392                         System.exit(16);
393                 }
394                 setObjectName("mainWindow");
395 //              thread().setPriority(Thread.MAX_PRIORITY);
396                 
397                 logger = new ApplicationLogger("nevernote.log");
398                 logger.log(logger.HIGH, "Starting Application");
399                 
400                 decryptOnShutdown = false;
401                 encryptOnShutdown = false;
402                 conn.checkDatabaseVersion();
403                 
404                 
405                 
406                 // Start building the invalid XML tables
407                 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
408                 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
409                 
410                 for (int i=0; i<elements.size(); i++) {
411                         Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
412                 }
413                 
414                 logger.log(logger.EXTREME, "Starting GUI build");
415
416                 QTranslator nevernoteTranslator = new QTranslator();
417                 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
418                 QApplication.instance().installTranslator(nevernoteTranslator);
419
420                 Global.originalPalette = QApplication.palette();
421                 QApplication.setStyle(Global.getStyle());
422                 if (Global.useStandardPalette())
423                         QApplication.setPalette(QApplication.style().standardPalette());
424         setWindowTitle(tr("NeighborNote"));
425
426         mainLeftRightSplitter = new QSplitter();
427                 // ICHANGED
428                 mainLeftRightSplitter.setOrientation(Qt.Orientation.Horizontal);
429                 
430         setCentralWidget(mainLeftRightSplitter);
431         leftSplitter1 = new QSplitter();
432         leftSplitter1.setOrientation(Qt.Orientation.Vertical);
433                 
434         browserIndexSplitter = new QSplitter();
435         browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
436         
437         //* Setup threads & thread timers
438 //        int indexRunnerCount = Global.getIndexThreads();
439 //       indexRunnerCount = 1;
440         QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount);     // increase max thread count
441
442                 logger.log(logger.EXTREME, "Building list manager");
443         listManager = new ListManager(conn, logger);
444         
445                 logger.log(logger.EXTREME, "Building index runners & timers");
446                 // ICHANGED Global.getBehaviorDatabaseUrl()を追加
447                 indexRunner = new IndexRunner("indexRunner.log",
448                                 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(),
449                                 Global.getResourceDatabaseUrl(),
450                                 Global.getBehaviorDatabaseUrl(), Global.getDatabaseUserid(),
451                                 Global.getDatabaseUserPassword(), Global.cipherPassword);
452                 
453                 indexThread = new QThread(indexRunner, "Index Thread");
454         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
455         indexRunner.indexImageRecognition = Global.indexImageRecognition();
456         indexRunner.indexNoteBody = Global.indexNoteBody();
457         indexRunner.indexNoteTitle = Global.indexNoteTitle();
458         indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
459                 indexThread.start();
460                 
461         synchronizeAnimationTimer = new QTimer();
462         synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
463         
464                 indexTimer = new QTimer();
465                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
466                 indexTimer.start(indexTime);  // Start indexing timer
467                 indexTimer.timeout.connect(this, "indexTimer()");
468                 indexDisabled = false;
469                 indexRunning = false;
470                                 
471                 logger.log(logger.EXTREME, "Setting sync thread & timers");
472                 syncThreadsReady=1;
473                 // ICHANGED Global.getBehaviorDatabaseUrl()を追加
474                 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(),
475                                 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
476                                 Global.getBehaviorDatabaseUrl(), Global.getDatabaseUserid(),
477                                 Global.getDatabaseUserPassword(), Global.cipherPassword);
478                 
479                 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
480                 syncTimer = new QTimer();
481                 syncTimer.timeout.connect(this, "syncTimer()");
482         syncRunner.status.message.connect(this, "setMessage(String)");
483         syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
484         syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
485         syncRunning = false;    
486                 if (syncTime > 0) {
487                         automaticSync = true;
488                         syncTimer.start(syncTime*60*1000);
489                 } else {
490                         automaticSync = false;
491                         syncTimer.stop();
492                 }
493                 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
494                 syncThread = new QThread(syncRunner, "Synchronization Thread");
495                 syncThread.start();
496                 
497                 
498                 logger.log(logger.EXTREME, "Starting thumnail thread");
499                 pdfReadyQueue = new ArrayList<String>();
500                 // ICHANGED Global.getBehaviorDatabaseUrl()を追加
501                 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
502                                 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(),
503                                 Global.getResourceDatabaseUrl(),
504                                 Global.getBehaviorDatabaseUrl(), Global.getDatabaseUserid(),
505                                 Global.getDatabaseUserPassword(), Global.cipherPassword);
506                 
507                 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
508                 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
509                 thumbnailThread.start();
510                 thumbGenerators = new ArrayList<Thumbnailer>();
511                 thumbnailTimer = new QTimer();
512                 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
513                 thumbnailTimer();
514                 thumbnailTimer.setInterval(500*1000);  // Thumbnail every minute
515                 thumbnailTimer.start();
516                 
517 //              debugTimer = new QTimer();
518 //              debugTimer.timeout.connect(this, "debugDirty()");
519 //              debugTimer.start(1000*60);
520                 
521                 logger.log(logger.EXTREME, "Starting authentication timer");
522                 authTimer = new QTimer();
523                 authTimer.timeout.connect(this, "authTimer()");
524                 authTimer.start(1000*60*15);
525                 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
526                 
527                 logger.log(logger.EXTREME, "Setting save note timer");
528                 saveTimer = new QTimer();
529                 saveTimer.timeout.connect(this, "saveNote()");
530                 if (Global.getAutoSaveInterval() > 0) {
531                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval()); 
532                         saveTimer.start();
533                 }
534                 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
535                 
536                 logger.log(logger.EXTREME, "Starting external file monitor timer");
537                 externalFileSaveTimer = new QTimer();
538                 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
539                 externalFileSaveTimer.setInterval(1000*5);   // save every 5 seconds;
540                 externalFiles = new ArrayList<String>();
541                 importFilesDelete = new ArrayList<String>();
542                 importFilesKeep = new ArrayList<String>();
543                 externalFileSaveTimer.start();
544                 
545         notebookTree = new NotebookTreeWidget(conn);
546         attributeTree = new AttributeTreeWidget();
547         tagTree = new TagTreeWidget(conn);
548         savedSearchTree = new SavedSearchTreeWidget();
549         trashTree = new TrashTreeWidget();
550                 // ICHANGED
551                 noteTableView = new TableView(logger, listManager, this);     
552         
553         searchField = new QComboBox();
554         searchField.setObjectName("searchField");
555         //setStyleSheet("QComboBox#searchField { background-color: yellow }");
556         searchField.setEditable(true);
557         searchField.activatedIndex.connect(this, "searchFieldChanged()");
558         searchField.setDuplicatesEnabled(false);
559         searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
560         searchShortcut = new QShortcut(this);
561         setupShortcut(searchShortcut, "Focus_Search");
562         searchShortcut.activated.connect(this, "focusSearch()");
563         
564         quotaBar = new QuotaProgressBar();
565         // Setup the zoom
566         zoomSpinner = new QSpinBox();
567         zoomSpinner.setMinimum(10);
568         zoomSpinner.setMaximum(1000);
569         zoomSpinner.setAccelerated(true);
570         zoomSpinner.setSingleStep(10);
571         zoomSpinner.setValue(100);
572         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
573         
574         searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
575         
576         
577         QGridLayout leftGrid = new QGridLayout();
578         leftSplitter1.setContentsMargins(5, 0, 0, 7);
579         leftSplitter1.setLayout(leftGrid);
580         leftGrid.addWidget(searchLayout,1,1);
581         leftGrid.addWidget(tagTree,2,1);
582         leftGrid.addWidget(attributeTree,3,1);
583         leftGrid.addWidget(savedSearchTree,4,1);
584         leftGrid.addWidget(trashTree,5, 1);
585         
586         // Setup the browser window
587         noteCache = new HashMap<String,String>();
588         readOnlyCache = new HashMap<String, Boolean>();
589         inkNoteCache = new HashMap<String, Boolean>();
590         // ICHANGED
591         browserWindow = new BrowserWindow(conn, cbObserver);
592
593                 // ICHANGED 下から移動してきた。
594                 historyGuids = new HashMap<Integer, ArrayList<String>>();
595                 historyPosition = new HashMap<Integer, Integer>();
596                 fromHistory = new HashMap<Integer, Boolean>();
597                 
598                 // ICHANGED タブブラウザ作成
599                 tabWindows = new HashMap<Integer, TabBrowse>();
600                 tabBrowser = new TabBrowserWidget(this);
601                 tabBrowser.setStyleSheet("QTabBar::tab{width:150px;}");
602                 tabBrowser.setMovable(true);
603                 tabBrowser.setTabsClosable(true);
604                 tabBrowser.currentChanged.connect(this, "tabWindowChanged(int)");
605                 tabBrowser.tabCloseRequested.connect(this, "tabWindowClosing(int)");
606                 
607                 inkNote = new HashMap<Integer, Boolean>();
608                 readOnly = new HashMap<Integer, Boolean>();
609                 
610         mainLeftRightSplitter.addWidget(leftSplitter1);
611         mainLeftRightSplitter.addWidget(browserIndexSplitter);
612         
613                 // ICHANGED
614                 // 連想ノートリストをセットアップ
615                 rensoNoteList = new RensoNoteList(conn, this);
616                 rensoNoteList.itemPressed.connect(this,
617                                 "rensoNoteItemPressed(QListWidgetItem)");
618                 rensoNoteListDock = new QDockWidget(tr("Renso Note List"), this);
619                 rensoNoteListDock.setWidget(rensoNoteList);
620                 addDockWidget(DockWidgetArea.RightDockWidgetArea, rensoNoteListDock);
621
622                 if (Global.getListView() == Global.View_List_Wide) {
623                         browserIndexSplitter.addWidget(noteTableView);
624                         // ICHANGED
625                         browserIndexSplitter.addWidget(tabBrowser);
626                         // browserIndexSplitter.addWidget(browserWindow);
627                 } else {
628                         mainLeftRightSplitter.addWidget(noteTableView);
629                         // ICHANGED
630                         mainLeftRightSplitter.addWidget(tabBrowser);
631                         // mainLeftRightSplitter.addWidget(browserWindow);
632                 }
633         
634         // Setup the thumbnail viewer
635         thumbnailViewer = new ThumbnailViewer();
636         thumbnailViewer.upArrow.connect(this, "upAction()");
637         thumbnailViewer.downArrow.connect(this, "downAction()");
638         thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
639         thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
640         
641         //Setup external browser manager
642         externalWindows = new HashMap<String, ExternalBrowse>();
643
644         listManager.loadNotesIndex();
645         initializeNotebookTree();
646         initializeTagTree();
647         initializeSavedSearchTree();
648         attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
649         attributeTreeSelected = null;
650         initializeNoteTable();    
651
652                 selectedNoteGUIDs = new ArrayList<String>();
653                 statusBar = new QStatusBar();
654                 setStatusBar(statusBar);
655                 menuBar = new MainMenuBar(this);
656                 emitLog = new ArrayList<String>();
657                 
658                 tagTree.setDeleteAction(menuBar.tagDeleteAction);
659                 tagTree.setMergeAction(menuBar.tagMergeAction);
660                 tagTree.setEditAction(menuBar.tagEditAction);
661                 tagTree.setAddAction(menuBar.tagAddAction);
662                 tagTree.setIconAction(menuBar.tagIconAction);
663                 tagTree.setVisible(Global.isWindowVisible("tagTree"));
664                 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
665                 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
666                 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
667                 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
668                 
669                 if (!Global.isWindowVisible("zoom")) {
670                         searchLayout.hideZoom();
671                         menuBar.hideZoom.setChecked(false);
672                 } 
673         
674                 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
675                 notebookTree.setEditAction(menuBar.notebookEditAction);
676                 notebookTree.setAddAction(menuBar.notebookAddAction);
677                 notebookTree.setIconAction(menuBar.notebookIconAction);
678                 notebookTree.setStackAction(menuBar.notebookStackAction);
679                 notebookTree.setPublishAction(menuBar.notebookPublishAction);
680                 notebookTree.setShareAction(menuBar.notebookShareAction);
681                 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
682                 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
683                 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
684             notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
685                 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
686
687                 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
688                 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
689                 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
690                 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
691                 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
692                 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
693                 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
694                 
695                 // ICHANGED noteTableViewに新しいタブで開くを追加
696                 noteTableView.setOpenNewTabAction(menuBar.noteOpenNewTab);
697                         
698                 noteTableView.setAddAction(menuBar.noteAdd);
699                 
700                 // ICHANGED noteTableViewに新しいタブでノート追加を追加
701                 noteTableView.setAddNoteNewTabAction(menuBar.noteAddNewTab);
702                 
703                 noteTableView.setDeleteAction(menuBar.noteDelete);
704                 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
705                 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
706                 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
707                 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
708                 noteTableView.noteSignal.notePinned.connect(this, "notePinned()");
709                 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
710                 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
711                 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
712                 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
713                 
714                 quotaBar.setMouseClickAction(menuBar.accountAction);
715                 
716                 trashTree.load();
717         trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
718                 trashTree.setEmptyAction(menuBar.emptyTrashAction);
719                 trashTree.setVisible(Global.isWindowVisible("trashTree"));
720                 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
721                 trashTree.updateCounts(listManager.getTrashCount());
722                 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
723                 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
724
725                 noteTableView.setVisible(Global.isWindowVisible("noteList"));
726                 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
727                 
728                 // ICHANGED
729                 if (!Global.isWindowVisible("editorButtonBar")) {
730                         menuBar.showEditorBar.setChecked(false);
731                         toggleEditorButtonBar();
732                 }
733                 
734                 if (!Global.isWindowVisible("leftPanel"))
735                         menuBar.hideLeftSide.setChecked(true);
736                 
737                 // ICHANGED
738                 if (Global.isWindowVisible("noteInformation")) {
739                         menuBar.noteAttributes.setChecked(true);
740                         toggleNoteInformation();
741                 }
742                 
743                 quotaBar.setVisible(Global.isWindowVisible("quota"));
744                 // IFIXED quotaBar.isVisible() → Global.isWindowVisible("quota")
745                 // なぜかquotaBar.isVisible()が常にfalseを返すようなので修正
746                 if (!Global.isWindowVisible("quota"))
747                         menuBar.hideQuota.setChecked(false);
748                 
749                 searchField.setVisible(Global.isWindowVisible("searchField"));
750                 // IFIXED !searchField.isVisible() → !Global.isWindowVisible("searchField")
751                 // なぜかsearchField.isVisible()が常にfalseを返すようなので修正
752                 if (!Global.isWindowVisible("searchField"))
753                         menuBar.hideSearch.setChecked(false);
754                 
755                 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
756                         searchLayout.hide();
757                 
758                 setMenuBar(menuBar);
759                 setupToolBar();
760                 find = new FindDialog();
761                 find.getOkButton().clicked.connect(this, "doFindText()");
762                 
763                 // Setup the tray icon menu bar
764                 trayShowAction = new QAction(tr("Show/Hide"), this);
765                 trayExitAction = new QAction(tr("Exit"), this);
766                 trayAddNoteAction = new QAction(tr("Add Note"), this);
767                 
768                 trayExitAction.triggered.connect(this, "closeNeverNote()");
769                 trayAddNoteAction.triggered.connect(this, "addNote()");
770                 trayShowAction.triggered.connect(this, "trayToggleVisible()");
771                 
772                 trayMenu = new QMenu(this);
773                 trayMenu.addAction(trayAddNoteAction);
774                 trayMenu.addAction(trayShowAction);
775                 trayMenu.addAction(trayExitAction);
776                 
777                 
778                 trayIcon = new QSystemTrayIcon(this);
779                 trayIcon.setToolTip(tr("NeighborNote"));
780                 trayIcon.setContextMenu(trayMenu);
781                 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
782                 
783                 // 前回のタブを復元
784                 noteTableView.load(true);
785                 HashMap<Integer, String> tabs = new HashMap<Integer, String>();
786                 if (Global.getLastViewedTabs() != null) {
787                         tabs.putAll(Global.getLastViewedTabs());
788                 }
789                 
790                 Collection<String>              guids = tabs.values();
791                 Iterator<String>                guidIterator = guids.iterator();
792                 Collection<Integer>             indexes = tabs.keySet();
793                 Iterator<Integer>               indexIterator = indexes.iterator();
794                 noteDirty = new HashMap<Integer, Boolean>();
795                 
796                 while (guidIterator.hasNext()) {
797                         String guid = guidIterator.next();
798                         int tabIndex = indexIterator.next();
799                         
800                         currentNoteGuid = guid;
801                         noteDirty.put(tabIndex, false);
802                         if (!currentNoteGuid.trim().equals("")) {
803                                 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true, true, false, false, true);
804                                 if (currentNote != null) {
805                                         openTabEditor(guid, tabIndex);
806                                 }
807                         }
808                 }
809                 
810                 // タブが0個だったら作る
811                 if (tabBrowser.count() <= 0) {
812                         TabBrowse tab = new TabBrowse(conn, tabBrowser, cbObserver);
813                         browserWindow = tab.getBrowserWindow();
814                         tabBrowser.currentChanged.disconnect();
815                         int index = tabBrowser.addNewTab(tab, "");
816                         tabBrowser.currentChanged.connect(this, "tabWindowChanged(int)");
817                         tabWindows.put(index, tab);
818                         noteDirty.put(index, false);
819                         
820                         // 履歴記録のハッシュマップを初期化
821                         historyGuids.put(index, new ArrayList<String>());
822                         historyPosition.put(index, 0);
823                         fromHistory.put(index, false);
824                 }
825                 
826                 currentNoteGuid = Global.getLastViewedNoteGuid();
827                 if (currentNoteGuid.trim().equals("")) {
828                         currentNote = new Note();
829                 } else {
830                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
831                 }
832                 
833                 // タブのフォーカスをlastViewedTabIndexに移す
834                 if (tabBrowser.count() >= 2) {
835                         tabBrowser.setCurrentIndex(Global.getLastViewedTabIndex());
836                 }
837                 
838                 noteIndexUpdated(true);
839                 showColumns();
840                 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
841                 if (menuBar.showEditorBar.isChecked())
842                 showEditorButtons(browserWindow);
843                 tagIndexUpdated(true);
844                 savedSearchIndexUpdated();
845                 notebookIndexUpdated();
846                 updateQuotaBar();
847         setupSyncSignalListeners();        
848         setupBrowserSignalListeners();
849         setupIndexListeners();
850               
851         
852         tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
853         tagTree.showAllTags(true);
854
855                 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
856                 if (QSystemTrayIcon.isSystemTrayAvailable()) {
857                         setWindowIcon(appIcon);
858                         trayIcon.setIcon(appIcon);
859                         if (Global.showTrayIcon() || Global.minimizeOnClose())
860                                 trayIcon.show();
861                         else
862                                 trayIcon.hide();
863                 }
864         
865         scrollToGuid(currentNoteGuid);
866         if (Global.automaticLogin()) {
867                 remoteConnect();
868                 if (Global.isConnected)
869                         syncTimer();
870         }
871         setupFolderImports();
872         
873         loadStyleSheet();
874         restoreWindowState(true);
875         
876         if (Global.mimicEvernoteInterface) {
877                 notebookTree.selectGuid("");
878         }
879         
880         threadMonitorTimer = new QTimer();
881         threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
882         threadMonitorTimer.start(1000*10);  // Check for threads every 10 seconds;              
883         
884                 // ICHANGED たぶんこれはいらない
885                 // IFIXED ?
886                 /*
887                 historyGuids.add(currentNoteGuid);
888                 historyPosition = 1;
889                 */
890         
891         menuBar.blockSignals(true);
892         menuBar.narrowListView.blockSignals(true);
893         menuBar.wideListView.blockSignals(true);
894         if (Global.getListView() == Global.View_List_Narrow) { 
895                 menuBar.narrowListView.setChecked(true);
896         }
897         else{ 
898                 menuBar.wideListView.setChecked(true);
899         }
900         menuBar.blockSignals(false);
901         menuBar.narrowListView.blockSignals(false);
902         menuBar.wideListView.blockSignals(false);
903         
904                 // IFIXED
905                 // 上に同じコードがあるよね? とりあえずコメントアウト
906                 /*
907                  * if (Global.getListView() == Global.View_List_Wide) {
908                  * browserIndexSplitter.addWidget(noteTableView); // ICHANGED //
909                  * browserIndexSplitter.addWidget(tabBrowser);
910                  * browserIndexSplitter.addWidget(browserWindow); } else {
911                  * mainLeftRightSplitter.addWidget(noteTableView); // ICHANGED //
912                  * mainLeftRightSplitter.addWidget(tabBrowser);
913                  * mainLeftRightSplitter.addWidget(browserWindow); }
914                  */
915         
916                 messageTimer = new QTimer();
917                 messageTimer.timeout.connect(this, "clearMessage()");
918                 messageTimer.setInterval(1000*15);
919                 clearMessage();
920         
921         int sortCol = Global.getSortColumn();
922                 int sortOrder = Global.getSortOrder();
923                 noteTableView.proxyModel.blocked = true;
924                 // We sort the table twice to fix a bug.  For some reaosn the table won't sort properly if it is in narrow
925                 // list view and sorted descending on the date  created.  By sorting it twice it forces the proper sort.  Ugly.
926                 if (sortCol == 0 && sortOrder == 1 && Global.getListView() == Global.View_List_Narrow) 
927                         noteTableView.sortByColumn(sortCol, SortOrder.resolve(0));   
928                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
929                 noteTableView.proxyModel.blocked = false;
930                 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
931                 
932                 // Set the startup notebook
933         String defaultNotebook = Global.getStartupNotebook();
934         if (!defaultNotebook.equals("AllNotebooks") && !defaultNotebook.equals("")) {
935                 for (int k=0; k<listManager.getNotebookIndex().size(); k++) {
936                         if (listManager.getNotebookIndex().get(k).isDefaultNotebook()) {
937                                 notebookTree.clearSelection();
938                                 notebookTree.selectGuid(listManager.getNotebookIndex().get(k).getGuid());
939                                 notebookTree.selectionSignal.emit();
940                         }
941                 }
942         }
943                 
944                 if (Global.checkVersionUpgrade()) {
945                         // ICHANGED TODO とりあえず封印
946                         // checkForUpdates();
947                 }
948                 
949                 // ICHANGED
950                 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
951                         menuBar.noteAddNewTab.setEnabled(false);
952                 }
953         }
954         
955         
956         public void debugDirty() {
957                 List<Note> dirty = conn.getNoteTable().getDirty();
958                 logger.log(logger.LOW, "------ Dirty Notes List Begin ------");
959                 for (int i=0; i<dirty.size(); i++) {
960                         logger.log(logger.LOW, "GUID: " +dirty.get(i).getGuid() + " Title:" + dirty.get(i).getTitle());
961                 }
962                 logger.log(logger.LOW, "------ Dirty Notes List End ------");
963         }
964                 
965         // Main entry point
966         public static void main(String[] args) {
967                 log.setLevel(Level.FATAL);
968                 QApplication.initialize(args);
969                 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
970                 QSplashScreen splash = new QSplashScreen(pixmap);
971                 boolean showSplash;
972                 
973                 DatabaseConnection dbConn;
974
975         try {
976             initializeGlobalSettings(args);
977
978             showSplash = Global.isWindowVisible("SplashScreen");
979             if (showSplash)
980                 splash.show();
981
982             dbConn = setupDatabaseConnection();
983
984             // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
985             Global.getFileManager().purgeResDirectory(true);
986
987         } catch (InitializationException e) {
988             // Fatal
989             e.printStackTrace();
990             QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
991             return;
992         }
993         
994                 // Setup proxy crap
995                 String proxyUrl = Global.getProxyValue("url");
996                 String proxyPort = Global.getProxyValue("port");
997                 String proxyUserid = Global.getProxyValue("userid");
998                 String proxyPassword = Global.getProxyValue("password");
999                 boolean proxySet = false;
1000                 QNetworkProxy proxy = new QNetworkProxy();
1001                 proxy.setType(ProxyType.HttpProxy);
1002                 if (!proxyUrl.trim().equals("")) {
1003                         System.out.println("Proxy URL found: " +proxyUrl);
1004                         proxySet = true;
1005                         proxy.setHostName(proxyUrl);
1006                 }
1007                 if (!proxyPort.trim().equals("")) {
1008                         System.out.println("Proxy Port found: " +proxyPort);
1009                         proxySet = true;
1010                         proxy.setPort(Integer.parseInt(proxyPort));
1011                 }
1012                 if (!proxyUserid.trim().equals("")) {
1013                         System.out.println("Proxy Userid found: " +proxyUserid);
1014                         proxySet = true;
1015                         proxy.setUser(proxyUserid);
1016                 }
1017                 if (!proxyPassword.trim().equals("")) {
1018                         System.out.println("Proxy URL found: " +proxyPassword);
1019                         proxySet = true;
1020                         proxy.setPassword(proxyPassword);
1021                 }
1022                 if (proxySet) {
1023                         QNetworkProxy.setApplicationProxy(proxy);
1024                 }
1025                         
1026
1027         NeverNote application = new NeverNote(dbConn);
1028                 if (Global.syncOnly) {
1029                         System.out.println("Performing synchronization only.");
1030                         application.remoteConnect();
1031                         if (Global.isConnected) {
1032                                 application.syncRunner.syncNeeded = true;
1033                                 application.syncRunner.addWork("SYNC");
1034                                 application.syncRunner.addWork("STOP");
1035                                 while(!application.syncRunner.isIdle());
1036                                 application.closeNeverNote();
1037                         }
1038                         return;
1039                 }
1040
1041                 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
1042                 if (Global.startMinimized()) 
1043                         application.showMinimized();
1044                 else {
1045                         if (Global.wasWindowMaximized())
1046                                 application.showMaximized();
1047                         else
1048                                 application.show();
1049                 }
1050                 
1051                 if (showSplash)
1052                         splash.finish(application);
1053                 QApplication.exec();
1054                 System.out.println("Goodbye.");
1055                 QApplication.exit();
1056         }
1057
1058     /**
1059      * Open the internal database, or create if not present
1060      *
1061      * @throws InitializationException when opening the database fails, e.g. because another process has it locked
1062      */
1063     private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
1064         ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
1065         
1066         File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
1067         File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
1068                 // IFIXED resourceDatabaseNameになっていたので修正
1069                 File fi = Global.getFileManager().getDbDirFile(Global.indexDatabaseName + ".h2.db");
1070                 // ICHANGED
1071                 File fb = Global.getFileManager().getDbDirFile(Global.behaviorDatabaseName + ".h2.db");
1072                                 
1073                 if (!f.exists())
1074                         Global.setDatabaseUrl("");
1075                 if (!fr.exists())
1076                         Global.setResourceDatabaseUrl("");              
1077                 if (!fi.exists())
1078                         Global.setIndexDatabaseUrl(""); 
1079                 // ICHANGED
1080                 if (!fb.exists())
1081                         Global.setBehaviorDatabaseUrl("");
1082         
1083         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
1084             boolean goodCheck = false;
1085             while (!goodCheck) {
1086                 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
1087                 dialog.exec();
1088                 if (!dialog.okPressed())
1089                     System.exit(0);
1090                 Global.cipherPassword = dialog.getPassword();
1091                 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
1092                         Global.getDatabaseUserPassword(), Global.cipherPassword);
1093             }
1094         }
1095         // ICHANGED Global.getBehaviorDatabaserUrl()を追加
1096         DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), 
1097                         Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(), Global.getBehaviorDatabaseUrl(),
1098                         Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
1099        return dbConn;
1100     }
1101     
1102     // Encrypt the database upon shutdown
1103     private void encryptOnShutdown() {
1104         String dbPath= Global.getFileManager().getDbDirPath("");
1105         try {
1106                 
1107                 Statement st = conn.getConnection().createStatement();  
1108                 st.execute("shutdown");
1109                 st = conn.getResourceConnection().createStatement();
1110                 st.execute("shutdown");
1111                 st = conn.getIndexConnection().createStatement();
1112                 st.execute("shutdown");
1113                 // ICHANGED
1114                 st = conn.getBehaviorConnection().createStatement();
1115                 st.execute("shutdown");
1116                 
1117                 if (QMessageBox.question(this, tr("Are you sure"), 
1118                                 tr("Are you sure you wish to encrypt the database?"),
1119                                 QMessageBox.StandardButton.Yes, 
1120                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
1121                         ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
1122                         ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
1123                         ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
1124                         // ICHANGED
1125                         ChangeFileEncryption.execute(dbPath, "Behavior", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
1126                         
1127                         Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
1128                         Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
1129                         Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
1130                         // ICHANGED
1131                                 Global.setBehaviorDatabaseUrl(Global.getBehaviorDatabaseUrl() + ";CIPHER=" + encryptCipher);
1132
1133                         QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
1134                 }
1135         } catch (SQLException e) {
1136                         e.printStackTrace();
1137                 }       
1138     }
1139     
1140     // Decrypt the database upon shutdown
1141     private void decryptOnShutdown() {
1142         String dbPath= Global.getFileManager().getDbDirPath("");
1143         String dbName = "NeverNote";
1144         try {
1145                 Statement st = conn.getConnection().createStatement();  
1146                 st.execute("shutdown");
1147                 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
1148                         encryptCipher = "AES";
1149                 else
1150                         encryptCipher = "XTEA";
1151                 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure", 
1152                                 "Are you sure you wish to decrypt the database?"),
1153                                 QMessageBox.StandardButton.Yes, 
1154                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
1155
1156                         ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
1157                         Global.setDatabaseUrl("");
1158                         Global.setResourceDatabaseUrl("");
1159                         Global.setIndexDatabaseUrl("");
1160                         QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
1161                 }
1162                 } catch (SQLException e) {
1163                         e.printStackTrace();
1164                 }       
1165     }
1166     /**
1167      * Encrypt/Decrypt the local database
1168      **/
1169     public void doDatabaseEncrypt() {
1170         // The database is not currently encrypted
1171         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
1172                 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
1173                                 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
1174                                 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
1175                                 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
1176                                 "Do you wish to proceed?"),
1177                                 QMessageBox.StandardButton.Yes, 
1178                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1179                                 return;
1180                 }
1181                 DBEncryptDialog dialog = new DBEncryptDialog();
1182                 dialog.exec();
1183                 if (dialog.okPressed()) {
1184                         Global.cipherPassword = dialog.getPassword();
1185                         encryptOnShutdown  = true;
1186                         encryptCipher = dialog.getEncryptionMethod();
1187                 }
1188         } else {
1189             DBEncryptDialog dialog = new DBEncryptDialog();
1190             dialog.setWindowTitle(tr("Database Decryption"));
1191             dialog.hideEncryption();
1192             dialog.exec();
1193             if (dialog.okPressed()) {
1194                 if (!dialog.getPassword().equals(Global.cipherPassword)) {
1195                         QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
1196                         return;
1197                 }
1198                 decryptOnShutdown  = true;
1199                 encryptCipher = "";
1200             }
1201         }
1202         return;
1203     }
1204
1205         private static void initializeGlobalSettings(String[] args) throws InitializationException {
1206                 StartupConfig   startupConfig = new StartupConfig();
1207
1208         for (String arg : args) {
1209             String lower = arg.toLowerCase();
1210             if (lower.startsWith("--name="))
1211                startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
1212             if (lower.startsWith("--home="))
1213                startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
1214             if (lower.startsWith("--disable-viewing"))
1215                startupConfig.setDisableViewing(true);
1216             if (lower.startsWith("--sync-only=true"))
1217                 startupConfig.setSyncOnly(true);
1218         }
1219         Global.setup(startupConfig);
1220         
1221     }
1222
1223     // Exit point
1224         @Override
1225         public void closeEvent(QCloseEvent event) {     
1226                 if (Global.minimizeOnClose() && !closeAction) {
1227                         event.ignore();
1228                         hide();
1229                         return;
1230                 }
1231                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
1232                 waitCursor(true);
1233                 
1234                 if (currentNote != null & browserWindow != null) {
1235                         if (currentNote.getTitle() != null && browserWindow != null
1236                                         && !currentNote.getTitle().equals(browserWindow.getTitle()))
1237                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(),
1238                                                 browserWindow.getTitle());
1239                 }
1240                 
1241                 saveNote();
1242                 setMessage(tr("Beginning shutdown."));
1243                 
1244                 // Close down external windows
1245                 Collection<ExternalBrowse> windows = externalWindows.values();
1246                 Iterator<ExternalBrowse> iterator = windows.iterator();
1247                 while (iterator.hasNext()) {
1248                         ExternalBrowse browser = iterator.next();
1249                         browser.windowClosing.disconnect();
1250                         browser.close();
1251                 }
1252                 
1253                 // ICHANGED タブブラウザに対してクローズ処理を行う
1254                 Collection<TabBrowse> win = tabWindows.values();
1255                 Iterator<TabBrowse> it = win.iterator();
1256                 tabBrowser.currentChanged.disconnect();
1257                 tabBrowser.tabCloseRequested.disconnect();
1258                 while (it.hasNext()) {
1259                         TabBrowse browser = it.next();
1260                         browser.close();
1261                 }
1262                 
1263                 externalFileEditedSaver();
1264                 if (Global.isConnected && Global.synchronizeOnClose()) {
1265                         setMessage(tr("Performing synchronization before closing."));
1266                         syncRunner.syncNeeded = true;
1267                         syncRunner.addWork("SYNC");
1268                 } else {
1269                         syncRunner.keepRunning = false;
1270                 }
1271                 syncRunner.addWork("STOP");
1272                 setMessage("Closing Program.");
1273                 threadMonitorTimer.stop();
1274
1275                 thumbnailRunner.addWork("STOP");
1276                 indexRunner.addWork("STOP");
1277                 saveNote();
1278                 listManager.stop();
1279                 saveWindowState();
1280
1281                 if (tempFiles != null)
1282                         tempFiles.clear();
1283
1284                 browserWindow.noteSignal.tagsChanged.disconnect();
1285                 browserWindow.noteSignal.titleChanged.disconnect();
1286                 browserWindow.noteSignal.noteChanged.disconnect();
1287                 browserWindow.noteSignal.notebookChanged.disconnect();
1288                 browserWindow.noteSignal.createdDateChanged.disconnect();
1289                 browserWindow.noteSignal.alteredDateChanged.disconnect();
1290                 syncRunner.searchSignal.listChanged.disconnect();
1291                 syncRunner.tagSignal.listChanged.disconnect();
1292         syncRunner.notebookSignal.listChanged.disconnect();
1293         syncRunner.noteIndexSignal.listChanged.disconnect();
1294
1295                 if (isVisible())
1296                         Global.saveWindowVisible("toolBar", toolBar.isVisible());
1297                 saveNoteColumnPositions();
1298                 saveNoteIndexWidth();
1299                 
1300                 int width = notebookTree.columnWidth(0);
1301                 Global.setColumnWidth("notebookTreeName", width);
1302                 width = tagTree.columnWidth(0);
1303                 Global.setColumnWidth("tagTreeName", width);
1304                 
1305                 Global.saveWindowMaximized(isMaximized());
1306                 Global.saveCurrentNoteGuid(currentNoteGuid);
1307                 Global.saveLastViewedTabIndex(tabBrowser.currentIndex());
1308                 
1309                 // 開いていたタブ群をsettingsに保存しておく
1310                 Collection<TabBrowse>           tabBrowsers = tabWindows.values();
1311                 Iterator<TabBrowse>                     tabIterator = tabBrowsers.iterator();
1312                 Collection<Integer>                     tabIndexes = tabWindows.keySet();
1313                 Iterator<Integer>                       indexIterator = tabIndexes.iterator();
1314                 HashMap<Integer, String>        tabs = new HashMap<Integer, String>();
1315                 while (tabIterator.hasNext()) {
1316                         TabBrowse tab = tabIterator.next();
1317                         int index = indexIterator.next();
1318                         if (tab.getBrowserWindow() != null && tab.getBrowserWindow().getNote() != null) {
1319                                 String guid = tab.getBrowserWindow().getNote().getGuid();
1320                                 tabs.put(index, guid);
1321                         }
1322                 }
1323                 Global.saveLastViewedTabs(tabs);
1324                         
1325                 int sortCol = noteTableView.proxyModel.sortColumn();
1326                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1327                 Global.setSortColumn(sortCol);
1328                 Global.setSortOrder(sortOrder);
1329                 
1330                 hide();
1331                 trayIcon.hide();
1332                 Global.keepRunning = false;
1333                 try {
1334                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1335                         if (indexRunner.thread().isAlive())
1336                                 indexRunner.thread().join(50);
1337                         if (!indexRunner.thread().isAlive())
1338                                 logger.log(logger.MEDIUM, "Index thread has stopped");
1339                         else {
1340                                 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1341                                 indexRunner.thread().interrupt();
1342                         }
1343                 } catch (InterruptedException e1) {
1344                         e1.printStackTrace();
1345                 }
1346                 
1347                 if (!syncRunner.thread().isAlive()) {
1348                         logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1349                         if (syncRunner.thread().isAlive()) {
1350                                 System.out.println(tr("Synchronizing.  Please be patient."));
1351                                 for(;syncRunner.thread().isAlive();) {
1352                                         try {
1353                                                 wait(10);
1354                                         } catch (InterruptedException e) {
1355                                                 e.printStackTrace();
1356                                         }
1357                                 }
1358                         }
1359                         logger.log(logger.MEDIUM, "Sync thread has stopped");
1360                 }
1361
1362                 if (encryptOnShutdown) {
1363                         encryptOnShutdown();
1364                 }
1365                 if (decryptOnShutdown) {
1366                         decryptOnShutdown();
1367                 }
1368                 try {
1369                         Global.getFileManager().purgeResDirectory(false);
1370                 } catch (InitializationException e) {
1371                         System.out.println(tr("Empty res directory purge failed"));
1372                         e.printStackTrace();
1373                 }
1374                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1375         }
1376
1377
1378         private void closeNeverNote() {
1379                 closeAction = true;
1380                 close();
1381         }
1382         public void setMessage(String s) {
1383                 if (logger != null) 
1384                         logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1385                 else
1386                         System.out.println("*** ERROR *** " +s);
1387                 
1388                 if (statusBar != null) {
1389                         statusBar.show();
1390                         if (logger != null) 
1391                                 logger.log(logger.HIGH, "Message: " +s);
1392                         statusBar.showMessage(s);
1393                         if (emitLog != null)
1394                                 emitLog.add(s);
1395                 
1396                         if (messageTimer != null) {
1397                                 messageTimer.stop();
1398                                 messageTimer.setSingleShot(true);
1399                                 messageTimer.start();
1400                         }
1401                 }
1402                         
1403                 if (logger != null) 
1404                         logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1405         }
1406         
1407         private void clearMessage() {
1408                 statusBar.clearMessage();
1409                 statusBar.hide();
1410         }
1411                 
1412         private void waitCursor(boolean wait) {
1413                 if (wait) {
1414                         if (QApplication.overrideCursor() == null)
1415                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1416                 }
1417                 else {
1418                         if (QApplication.overrideCursor() != null)
1419                                 QApplication.restoreOverrideCursor();
1420                         else
1421                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.ArrowCursor));
1422                 }
1423                 listManager.refreshCounters();
1424         }
1425         
1426         private void setupIndexListeners() {
1427 //              indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1428 //              indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1429                 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1430                 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1431         }
1432         private void setupSyncSignalListeners() {
1433                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1434         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1435         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1436         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1437         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1438         
1439                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1440                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1441                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1442                 
1443                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1444                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1445                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1446                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1447                 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1448                 
1449                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1450         }
1451         
1452         private void setupBrowserSignalListeners() {
1453                 setupBrowserWindowListeners(browserWindow, true);
1454         }
1455
1456         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1457                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1458                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1459             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1460             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1461             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1462             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1463             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1464             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1465             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1466             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1467             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1468             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1469             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1470             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1471         browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1472         browser.unblockApplication.connect(this, "unblockApplication()");
1473             if (master) browser.focusLost.connect(this, "saveNote()");
1474             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1475             browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1476         }
1477
1478         //**************************************************
1479         //* Setup shortcuts
1480         //**************************************************
1481         private void setupShortcut(QShortcut action, String text) {
1482                 if (!Global.shortcutKeys.containsAction(text))
1483                         return;
1484                 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1485         }
1486         
1487         //***************************************************************
1488         //***************************************************************
1489         //* Settings and look & feel
1490         //***************************************************************
1491         //***************************************************************
1492         @SuppressWarnings("unused")
1493         private void settings() {
1494                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1495
1496                 saveNoteColumnPositions();
1497                 saveNoteIndexWidth();
1498                 showColumns();
1499         ConfigDialog settings = new ConfigDialog(this);
1500         String dateFormat = Global.getDateFormat();
1501         String timeFormat = Global.getTimeFormat();
1502         
1503                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1504                 indexTimer.start(indexTime);  // reset indexing timer
1505         
1506         settings.exec();
1507         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1508         indexRunner.indexNoteBody = Global.indexNoteBody();
1509         indexRunner.indexNoteTitle = Global.indexNoteTitle();
1510         indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1511         indexRunner.indexImageRecognition = Global.indexImageRecognition();
1512         if (Global.showTrayIcon() || Global.minimizeOnClose())
1513                 trayIcon.show();
1514         else
1515                 trayIcon.hide();
1516         showColumns();
1517         if (menuBar.showEditorBar.isChecked()){
1518                 // ICHANGED 
1519                 for(int i = 0; i < tabBrowser.count(); i++){
1520                         BrowserWindow browser = ((TabBrowse) tabBrowser.widget(i)).getBrowserWindow();
1521                         showEditorButtons(browser);
1522                 }
1523                 
1524         }
1525         
1526         // Reset the save timer
1527         if (Global.getAutoSaveInterval() > 0)
1528                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1529         else
1530                 saveTimer.stop();
1531         
1532         
1533         // Set special reloads
1534         if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1535                 conn.executeSql("Delete from LinkedNotebook");
1536                 conn.executeSql("delete from SharedNotebook");
1537                 conn.executeSql("Delete from Notebook where linked=true");
1538                 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1539                 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1540         }
1541
1542         // Reload user data
1543         noteCache.clear();
1544         readOnlyCache.clear();
1545         inkNoteCache.clear();
1546         noteIndexUpdated(true);
1547                 
1548         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1549         }
1550         // Restore things to the way they were
1551         private void restoreWindowState(boolean mainWindow) {
1552                 // We need to name things or this doesn't work.
1553                 setObjectName("NeverNote");
1554         restoreState(Global.restoreState(objectName()));
1555                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1556                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1557                 leftSplitter1.setObjectName("leftSplitter1");
1558                 // ICHANGED
1559                 rensoNoteListDock.setObjectName("rensoNoteListDock");
1560                 
1561                 // Restore the actual positions.
1562                 if (mainWindow)
1563                         restoreGeometry(Global.restoreGeometry(objectName()));
1564         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1565         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1566         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1567         // ICHANGED
1568         rensoNoteListDock.restoreGeometry(Global.restoreGeometry(rensoNoteListDock.objectName()));
1569        
1570         }
1571         // Save window positions for the next start
1572         private void saveWindowState() {
1573                 Global.saveGeometry(objectName(), saveGeometry());
1574                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1575                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1576                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1577                 Global.saveState(objectName(), saveState());
1578                 // ICHANGED
1579                 Global.saveGeometry(rensoNoteListDock.objectName(), rensoNoteListDock.saveGeometry());
1580         }    
1581         // Load the style sheet
1582         private void loadStyleSheet() {
1583                 String styleSheetName = "default.qss";
1584                 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1585                                 styleSheetName = "default-cleanlooks.qss";
1586                 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1587                 QFile file = new QFile(fileName);
1588                 
1589                 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1590                 if (!file.exists()) {
1591                         fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1592                         file = new QFile(fileName);
1593                 }
1594                 file.open(OpenModeFlag.ReadOnly);
1595                 String styleSheet = file.readAll().toString();
1596                 file.close();
1597                 setStyleSheet(styleSheet);
1598         }
1599         // Save column positions for the next time
1600         private void saveNoteColumnPositions() {
1601                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1602                 Global.setColumnPosition("noteTableCreationPosition", position);
1603                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1604                 Global.setColumnPosition("noteTableTagPosition", position);
1605                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1606                 Global.setColumnPosition("noteTableNotebookPosition", position);
1607                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1608                 Global.setColumnPosition("noteTableChangedPosition", position);
1609                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1610                 Global.setColumnPosition("noteTableAuthorPosition", position);
1611                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1612                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1613                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1614                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1615                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1616                 Global.setColumnPosition("noteTableTitlePosition", position);
1617                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1618                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1619                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1620                 Global.setColumnPosition("noteTableGuidPosition", position);
1621                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1622                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1623                 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1624                 Global.setColumnPosition("noteTablePinnedPosition", position);
1625
1626         }
1627         // Save column widths for the next time
1628         private void saveNoteIndexWidth() {
1629                 int width;
1630         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1631         Global.setColumnWidth("noteTableCreationPosition", width);
1632                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1633                 Global.setColumnWidth("noteTableChangedPosition", width);
1634                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1635                 Global.setColumnWidth("noteTableGuidPosition", width);
1636                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1637                 Global.setColumnWidth("noteTableNotebookPosition", width);
1638                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1639                 Global.setColumnWidth("noteTableTagPosition", width);
1640                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1641                 Global.setColumnWidth("noteTableTitlePosition", width);
1642                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1643                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1644                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1645                 Global.setColumnWidth("noteTableAuthorPosition", width);
1646                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1647                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1648                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1649                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1650                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1651                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1652                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1653                 Global.setColumnWidth("noteTableGuidPosition", width);
1654                 width = noteTableView.getColumnWidth(Global.noteTablePinnedPosition);
1655                 Global.setColumnWidth("noteTablePinnedPosition", width);
1656         }
1657         
1658         @SuppressWarnings("unused")
1659         private void toggleSearchWindow() {
1660                 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1661         searchLayout.toggleSearchField();
1662         menuBar.hideSearch.setChecked(searchField.isVisible());
1663         Global.saveWindowVisible("searchField", searchField.isVisible());
1664         logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1665     }   
1666         @SuppressWarnings("unused")
1667         private void toggleQuotaWindow() {
1668                 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1669         searchLayout.toggleQuotaBar();
1670         menuBar.hideQuota.setChecked(quotaBar.isVisible());
1671         Global.saveWindowVisible("quota", quotaBar.isVisible());
1672         logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1673     }   
1674         @SuppressWarnings("unused")
1675         private void toggleZoomWindow() {
1676                 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1677         searchLayout.toggleZoom();
1678         menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1679         Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1680         logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1681     }   
1682         
1683         
1684         
1685     //***************************************************************
1686     //***************************************************************
1687     //** These functions deal with Notebook menu items
1688     //***************************************************************
1689     //***************************************************************
1690     // Setup the tree containing the user's notebooks.
1691     private void initializeNotebookTree() {       
1692         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1693 //      notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1694         notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1695         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1696         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1697     }   
1698     // Listener when a notebook is selected
1699         private void notebookTreeSelection() {
1700                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1701                 noteTableView.proxyModel.blocked = true;
1702                 
1703                 clearTrashFilter();
1704                 clearAttributeFilter();
1705                 clearSavedSearchFilter();
1706                 if (Global.mimicEvernoteInterface) {
1707                         clearTagFilter();
1708                         //searchField.clear();
1709                         searchField.clearEditText();
1710                 }
1711                 menuBar.noteRestoreAction.setVisible(false);            
1712         menuBar.notebookEditAction.setEnabled(true);
1713         menuBar.notebookDeleteAction.setEnabled(true);
1714         menuBar.notebookPublishAction.setEnabled(true);
1715         menuBar.notebookShareAction.setEnabled(true);
1716         menuBar.notebookIconAction.setEnabled(true);
1717         menuBar.notebookStackAction.setEnabled(true);
1718         
1719                 // ICHANGED ゴミ箱から元の画面に戻す。連想ノートリストをONに。
1720                 if (!rensoNoteListDock.isEnabled()) {
1721                         rensoNoteListDock.setEnabled(true);
1722                 }
1723                 
1724         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1725         selectedNotebookGUIDs.clear();
1726                 String guid = "";
1727                 String stackName = "";
1728                 if (selections.size() > 0) {
1729                 guid = (selections.get(0).text(2));
1730                 stackName = selections.get(0).text(0);
1731         }
1732                 if (!Global.mimicEvernoteInterface) {
1733                         // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1734                         if (selections.size()==0) {
1735                                 selectedNotebookGUIDs.clear();
1736                                 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1737                                         selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1738                                 }
1739                                 menuBar.notebookEditAction.setEnabled(false);
1740                                 menuBar.notebookDeleteAction.setEnabled(false);
1741                                 menuBar.notebookStackAction.setEnabled(false);
1742                                 menuBar.notebookIconAction.setEnabled(false);
1743                         }
1744                 }
1745         if (!guid.equals("") && !guid.equals("STACK")) {
1746                 selectedNotebookGUIDs.add(guid);
1747                 menuBar.notebookIconAction.setEnabled(true);
1748         } else {
1749                 menuBar.notebookIconAction.setEnabled(true);
1750                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1751                                 Notebook book = listManager.getNotebookIndex().get(j);
1752                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1753                                         selectedNotebookGUIDs.add(book.getGuid());
1754                         }
1755         }
1756         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1757         listManager.loadNotesIndex();
1758         noteIndexUpdated(false);
1759         refreshEvernoteNote(true);
1760         listManager.refreshCounters = true;
1761         listManager.refreshCounters();
1762         if (selectedNotebookGUIDs.size() == 1) {
1763                 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1764                 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1765                 if (col != -1) {
1766                         noteTableView.proxyModel.blocked = true;
1767                         if (order == 1)
1768                                 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1769                         else
1770                                 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1771                 }
1772         }
1773         noteTableView.proxyModel.blocked = false;
1774                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1775
1776     }
1777     private void clearNotebookFilter() {
1778         notebookTree.blockSignals(true);
1779         notebookTree.clearSelection();
1780                 menuBar.noteRestoreAction.setVisible(false);
1781         menuBar.notebookEditAction.setEnabled(false);
1782         menuBar.notebookDeleteAction.setEnabled(false);
1783         selectedNotebookGUIDs.clear();
1784         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1785         notebookTree.blockSignals(false);
1786     }
1787         // Triggered when the notebook DB has been updated
1788         private void notebookIndexUpdated() {
1789                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1790         
1791                 // Get the possible icons
1792                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1793         notebookTree.setIcons(icons);
1794         
1795         if (selectedNotebookGUIDs == null)
1796                         selectedNotebookGUIDs = new ArrayList<String>();
1797                 List<Notebook> books = conn.getNotebookTable().getAll();
1798                 for (int i=books.size()-1; i>=0; i--) {
1799                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1800                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1801                                         books.remove(i);
1802                                         j=listManager.getArchiveNotebookIndex().size();
1803                                 }
1804                         }
1805                 }
1806                 
1807                 
1808                 listManager.countNotebookResults(listManager.getNoteIndex());
1809                 notebookTree.blockSignals(true);
1810         notebookTree.load(books, listManager.getLocalNotebooks());
1811         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1812                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1813                 if (!found)
1814                         selectedNotebookGUIDs.remove(i);
1815         }
1816         listManager.refreshCounters = true;
1817         listManager.refreshCounters();
1818         notebookTree.blockSignals(false);
1819         
1820                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1821     }
1822     // Show/Hide note information
1823         @SuppressWarnings("unused")
1824         private void toggleNotebookWindow() {
1825                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1826                 searchLayout.toggleNotebook();
1827         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1828         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1829         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1830     }   
1831         // Add a new notebook
1832         @SuppressWarnings("unused")
1833         private void addNotebook() {
1834                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1835                 NotebookEdit edit = new NotebookEdit();
1836                 edit.setNotebooks(listManager.getNotebookIndex());
1837                 edit.exec();
1838         
1839                 if (!edit.okPressed())
1840                         return;
1841         
1842                 Calendar currentTime = new GregorianCalendar();
1843                 Long l = new Long(currentTime.getTimeInMillis());
1844                 String randint = new String(Long.toString(l));
1845         
1846                 Notebook newBook = new Notebook();
1847                 newBook.setUpdateSequenceNum(0);
1848                 newBook.setGuid(randint);
1849                 newBook.setName(edit.getNotebook());
1850                 newBook.setServiceCreated(new Date().getTime());
1851                 newBook.setServiceUpdated(new Date().getTime());
1852                 newBook.setDefaultNotebook(false);
1853                 newBook.setPublished(false);
1854                 
1855                 listManager.getNotebookIndex().add(newBook);
1856                 if (edit.isLocal())
1857                         listManager.getLocalNotebooks().add(newBook.getGuid());
1858                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1859                 notebookIndexUpdated();
1860                 listManager.countNotebookResults(listManager.getNoteIndex());
1861 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1862                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1863         }
1864         // Edit an existing notebook
1865         @SuppressWarnings("unused")
1866         private void stackNotebook() {
1867                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1868                 StackNotebook edit = new StackNotebook();
1869                 
1870                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1871                 QTreeWidgetItem currentSelection;
1872                 for (int i=0; i<selections.size(); i++) {
1873                         currentSelection = selections.get(0);
1874                         String guid = currentSelection.text(2);
1875                         if (guid.equalsIgnoreCase("")) {
1876                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1877                                  return;
1878                         }
1879                         if (guid.equalsIgnoreCase("STACK")) {
1880                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1881                                  return;
1882                         }
1883                 }
1884
1885                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1886
1887                 
1888                 edit.exec();
1889         
1890                 if (!edit.okPressed())
1891                         return;
1892         
1893                 String stack = edit.getStackName();
1894                 
1895                 for (int i=0; i<selections.size(); i++) {
1896                         currentSelection = selections.get(i);
1897                         String guid = currentSelection.text(2);
1898                         listManager.updateNotebookStack(guid, stack);
1899                 }
1900                 notebookIndexUpdated();
1901                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1902         }
1903         // Edit an existing notebook
1904         @SuppressWarnings("unused")
1905         private void editNotebook() {
1906                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1907                 NotebookEdit edit = new NotebookEdit();
1908                 
1909                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1910                 QTreeWidgetItem currentSelection;
1911                 currentSelection = selections.get(0);
1912                 edit.setNotebook(currentSelection.text(0));
1913                 
1914                 String guid = currentSelection.text(2);
1915                 if (!guid.equalsIgnoreCase("STACK")) {
1916                         edit.setTitle(tr("Edit Notebook"));
1917                         edit.setNotebooks(listManager.getNotebookIndex());
1918                         edit.setLocalCheckboxEnabled(false);
1919                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1920                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1921                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1922                                         i=listManager.getNotebookIndex().size();
1923                                 }
1924                         }
1925                 } else {
1926                         edit.setTitle(tr("Edit Stack"));
1927                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1928                         edit.hideLocalCheckbox();
1929                         edit.hideDefaultCheckbox();
1930                 }
1931                 
1932                 edit.exec();
1933         
1934                 if (!edit.okPressed())
1935                         return;
1936         
1937                 
1938                 if (guid.equalsIgnoreCase("STACK")) {
1939                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1940                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1941                                 if (listManager.getNotebookIndex().get(j).getStack() != null && 
1942                                         listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1943                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1944                         }
1945                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1946                         currentSelection.setText(0, edit.getNotebook());
1947                         return;
1948                 }
1949                 
1950                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1951                 currentSelection.setText(0, edit.getNotebook());
1952                 
1953                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1954                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1955                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1956                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1957                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1958                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1959                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1960                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1961                                 }
1962                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1963                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1964                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1965                                         linkedNotebook.setShareName(edit.getNotebook());
1966                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1967                                 }
1968                                 i=listManager.getNotebookIndex().size();
1969                         }
1970                 }
1971                 
1972                 // Build a list of non-closed notebooks
1973                 List<Notebook> nbooks = new ArrayList<Notebook>();
1974                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1975                         boolean found=false;
1976                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1977                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1978                                         found = true;
1979                         }
1980                         if (!found)
1981                                 nbooks.add(listManager.getNotebookIndex().get(i));
1982                 }
1983                 
1984                 
1985                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1986                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1987                 browserWindow.setNotebookList(filteredBooks);
1988                 Iterator<String> set = externalWindows.keySet().iterator();
1989                 while(set.hasNext())
1990                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1991                 
1992                 // ICHANGED
1993                 Iterator<Integer>it = tabWindows.keySet().iterator();
1994                 while (it.hasNext()) {
1995                         tabWindows.get(it.next()).getBrowserWindow()
1996                                         .setNotebookList(filteredBooks);
1997                 }
1998                 
1999                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
2000         }
2001         // Publish a notebook
2002         @SuppressWarnings("unused")
2003         private void publishNotebook() {
2004                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
2005                 QTreeWidgetItem currentSelection;
2006                 currentSelection = selections.get(0);
2007                 String guid = currentSelection.text(2);
2008
2009                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
2010                         return;
2011                 
2012                 Notebook n = null;
2013                 int position = 0;
2014                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
2015                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
2016                                 n = listManager.getNotebookIndex().get(i);
2017                                 position = i;
2018                                 i = listManager.getNotebookIndex().size();
2019                         }
2020                 }
2021                 if (n == null)
2022                         return;
2023                 
2024                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
2025                 publish.exec();
2026                 
2027                 if (!publish.okClicked()) 
2028                         return;
2029                 
2030                 Publishing p = publish.getPublishing();
2031                 boolean isPublished = !publish.isStopPressed();
2032                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
2033                 n.setPublished(isPublished);
2034                 n.setPublishing(p);
2035                 listManager.getNotebookIndex().set(position, n);
2036                 notebookIndexUpdated();
2037         }
2038         // Publish a notebook
2039         @SuppressWarnings("unused")
2040         private void shareNotebook() {
2041                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
2042                 QTreeWidgetItem currentSelection;
2043                 currentSelection = selections.get(0);
2044                 String guid = currentSelection.text(2);
2045
2046                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
2047                         return;
2048                 
2049                 Notebook n = null;;
2050                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
2051                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
2052                                 n = listManager.getNotebookIndex().get(i);
2053                                 i = listManager.getNotebookIndex().size();
2054                         }
2055                 }
2056                                 
2057                 String authToken = null;
2058                 if (syncRunner.isConnected)
2059                         authToken = syncRunner.authToken;
2060                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
2061                 share.exec();
2062                 
2063         }
2064
2065         // Delete an existing notebook
2066         @SuppressWarnings("unused")
2067         private void deleteNotebook() {
2068                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
2069                 boolean stacksFound = false;
2070                 boolean notebooksFound = false;
2071                 boolean assigned = false;
2072                 // Check if any notes have this notebook
2073                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
2074         for (int i=0; i<selections.size(); i++) {
2075                 QTreeWidgetItem currentSelection;
2076                 currentSelection = selections.get(i);
2077                 String guid = currentSelection.text(2);
2078                 if (!guid.equalsIgnoreCase("STACK")) {
2079                         notebooksFound = true;
2080                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2081                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
2082                                 if (noteGuid.equals(guid)) {
2083                                         assigned = true;
2084                                         j=listManager.getNoteIndex().size();
2085                                         i=selections.size();
2086                                 }
2087                         }
2088                 } else {
2089                         stacksFound = true;
2090                 }
2091         }
2092                 if (assigned) {
2093                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
2094                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
2095                         return;
2096                 }
2097                 
2098                 if (conn.getNotebookTable().getAll().size() == 1) {
2099                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
2100                         return;
2101                 }
2102         
2103         // If all notebooks are clear, verify the delete
2104                 String msg1 = new String(tr("Delete selected notebooks?"));
2105                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
2106                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
2107                                 " not deleted unless selected?"));
2108                 String msg = "";
2109                 if (stacksFound && notebooksFound)
2110                         msg = msg3;
2111                 if (!stacksFound && notebooksFound)
2112                         msg = msg1;
2113                 if (stacksFound && !notebooksFound)
2114                         msg = msg2;
2115                 if (QMessageBox.question(this, tr("Confirmation"), msg,
2116                         QMessageBox.StandardButton.Yes, 
2117                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2118                         return;
2119                 }
2120                 
2121                 // If confirmed, delete the notebook
2122         for (int i=selections.size()-1; i>=0; i--) {
2123                 QTreeWidgetItem currentSelection;
2124                 currentSelection = selections.get(i);
2125                 String guid = currentSelection.text(2);
2126                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
2127                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
2128                         listManager.renameStack(currentSelection.text(0), "");
2129                 } else {
2130                         conn.getNotebookTable().expungeNotebook(guid, true);
2131                         listManager.deleteNotebook(guid);
2132                 }
2133         }
2134
2135                 notebookIndexUpdated();
2136 //        notebookTreeSelection();
2137 //        notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
2138 //        listManager.countNotebookResults(listManager.getNoteIndex());
2139         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
2140         }
2141         // A note's notebook has been updated
2142         @SuppressWarnings("unused")
2143         private void updateNoteNotebook(String guid, String notebookGuid) {
2144                 // ICHANGED 同じノートブックに入れられたノート間の履歴を登録
2145                 conn.getHistoryTable().addSameNotebookHistory(guid, notebookGuid);
2146                 
2147                 // Update the list manager
2148                 listManager.updateNoteNotebook(guid, notebookGuid);
2149                 listManager.countNotebookResults(listManager.getNoteIndex());
2150 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
2151                 
2152                 // Find the name of the notebook
2153                 String notebookName = null;
2154                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
2155                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
2156                                 notebookName = listManager.getNotebookIndex().get(i).getName();
2157                                 break;
2158                         }
2159                 }
2160                 
2161                 // If we found the name, update the browser window
2162                 if (notebookName != null) {
2163                         updateListNoteNotebook(guid, notebookName);
2164                         if (guid.equals(currentNoteGuid)) {
2165                                 int pos =  browserWindow.notebookBox.findText(notebookName);
2166                                 if (pos >=0)
2167                                         browserWindow.notebookBox.setCurrentIndex(pos);
2168                         }
2169                 }
2170                 
2171                 // If we're dealing with the current note, then we need to be sure and update the notebook there
2172                 if (guid.equals(currentNoteGuid)) {
2173                         if (currentNote != null) {
2174                                 currentNote.setNotebookGuid(notebookGuid);
2175                         }
2176                 }
2177         }
2178         // Open/close notebooks
2179         @SuppressWarnings("unused")
2180         private void closeNotebooks() {
2181                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
2182                 na.exec();
2183                 if (!na.okClicked())
2184                         return;
2185                 
2186                 waitCursor(true);
2187                 listManager.getArchiveNotebookIndex().clear();
2188                 
2189                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
2190                         String text = na.getClosedBookList().takeItem(i).text();
2191                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
2192                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
2193                                         Notebook n = listManager.getNotebookIndex().get(j);
2194                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
2195                                         listManager.getArchiveNotebookIndex().add(n);
2196                                         j=listManager.getNotebookIndex().size();
2197                                 }
2198                         }
2199                 }
2200                 
2201                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
2202                         String text = na.getOpenBookList().takeItem(i).text();
2203                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
2204                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
2205                                         Notebook n = listManager.getNotebookIndex().get(j);
2206                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
2207                                         j=listManager.getNotebookIndex().size();
2208                                 }
2209                         }
2210                 }
2211                 notebookTreeSelection();
2212                 listManager.loadNotesIndex();
2213                 notebookIndexUpdated();
2214                 noteIndexUpdated(false);
2215                 reloadTagTree(true);
2216 //              noteIndexUpdated(false);
2217                 
2218                 // Build a list of non-closed notebooks
2219                 List<Notebook> nbooks = new ArrayList<Notebook>();
2220                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
2221                         boolean found=false;
2222                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
2223                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
2224                                         found = true;
2225                         }
2226                         if (!found)
2227                                 nbooks.add(listManager.getNotebookIndex().get(i));
2228                 }
2229                 
2230                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
2231                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
2232                 browserWindow.setNotebookList(filteredBooks);
2233                 
2234                 // Update any external windows
2235                 Iterator<String> set = externalWindows.keySet().iterator();
2236                 while(set.hasNext())
2237                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
2238                 
2239                 // ICHANGED
2240                 // 全てのタブウィンドウを更新
2241                 Iterator<Integer> it = tabWindows.keySet().iterator();
2242                 while (it.hasNext()) {
2243                         tabWindows.get(it.next()).getBrowserWindow()
2244                                         .setNotebookList(filteredBooks);
2245                 }
2246                 
2247                 waitCursor(false);
2248         }
2249         // Change the notebook's icon
2250         @SuppressWarnings("unused")
2251         private void setNotebookIcon() {
2252                 boolean stackSelected = false;
2253                 boolean allNotebookSelected = false;
2254                 
2255                 QTreeWidgetItem currentSelection;
2256                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
2257                 if (selections.size() == 0)
2258                         return;
2259                 
2260                 currentSelection = selections.get(0);   
2261                 String guid = currentSelection.text(2);
2262                 if (guid.equalsIgnoreCase(""))
2263                         allNotebookSelected = true;
2264                 if (guid.equalsIgnoreCase("STACK"))
2265                         stackSelected = true;
2266
2267                 QIcon currentIcon = currentSelection.icon(0);
2268                 QIcon icon;
2269                 SetIcon dialog;
2270                 
2271                 if (!stackSelected && !allNotebookSelected) {
2272                         icon = conn.getNotebookTable().getIcon(guid);
2273                         if (icon == null) {
2274                                 dialog = new SetIcon(currentIcon, saveLastPath);
2275                                 dialog.setUseDefaultIcon(true);
2276                         } else {
2277                                 dialog = new SetIcon(icon, saveLastPath);
2278                                 dialog.setUseDefaultIcon(false);
2279                         }
2280                 } else {
2281                         if (stackSelected) {
2282                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
2283                         } else {
2284                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
2285                         }
2286                         if (icon == null) {
2287                                 dialog = new SetIcon(currentIcon, saveLastPath);
2288                                 dialog.setUseDefaultIcon(true);
2289                         } else {
2290                                 dialog = new SetIcon(icon, saveLastPath);
2291                                 dialog.setUseDefaultIcon(false);
2292                         }
2293                 }
2294                 dialog.exec();
2295                 if (dialog.okPressed()) {
2296                 saveLastPath = dialog.getPath();
2297
2298                         QIcon newIcon = dialog.getIcon();
2299                         if (stackSelected) {
2300                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
2301                                 if (newIcon == null) {
2302                                         newIcon = new QIcon(iconPath+"books2.png");
2303                                 }
2304                                 currentSelection.setIcon(0,newIcon);
2305                                 return;
2306                         }
2307                         if (allNotebookSelected) {
2308                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
2309                                 if (newIcon == null) {
2310                                         newIcon = new QIcon(iconPath+"notebook-green.png");
2311                                 }
2312                                 currentSelection.setIcon(0,newIcon);
2313                                 return;
2314                         }
2315                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
2316                         if (newIcon == null) {
2317                                 boolean isPublished = false;;
2318                                 boolean found = false;
2319                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
2320                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
2321                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
2322                                                 found = true;
2323                                         }
2324                                 }
2325                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
2326                         }
2327                         currentSelection.setIcon(0, newIcon);
2328                 }
2329         
2330         }
2331         
2332         
2333     //***************************************************************
2334     //***************************************************************
2335     //** These functions deal with Tag menu items
2336     //***************************************************************
2337     //***************************************************************
2338         // Add a new notebook
2339         @SuppressWarnings("unused")
2340         private void addTag() {
2341                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2342                 TagEdit edit = new TagEdit();
2343                 edit.setTagList(listManager.getTagIndex());
2344
2345                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2346                 QTreeWidgetItem currentSelection = null;
2347                 if (selections.size() > 0) {
2348                         currentSelection = selections.get(0);
2349                         edit.setParentTag(currentSelection.text(0));
2350                 }
2351
2352                 edit.exec();
2353         
2354                 if (!edit.okPressed())
2355                         return;
2356         
2357                 Calendar currentTime = new GregorianCalendar();
2358                 Long l = new Long(currentTime.getTimeInMillis());
2359                 String randint = new String(Long.toString(l));
2360         
2361                 Tag newTag = new Tag();
2362                 newTag.setUpdateSequenceNum(0);
2363                 newTag.setGuid(randint);
2364                 newTag.setName(edit.getTag());
2365                 if (edit.getParentTag().isChecked()) {
2366                         newTag.setParentGuid(currentSelection.text(2));
2367                         newTag.setParentGuidIsSet(true);
2368                         currentSelection.setExpanded(true);
2369                 }
2370                 conn.getTagTable().addTag(newTag, true);
2371                 listManager.getTagIndex().add(newTag);
2372                 reloadTagTree(true);
2373                 
2374                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2375         }
2376         @SuppressWarnings("unused")
2377         private void reloadTagTree() {
2378                 reloadTagTree(false);
2379         }
2380         private void reloadTagTree(boolean reload) {
2381                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2382                 tagIndexUpdated(reload);
2383                 boolean filter = false;
2384                 if (reload)
2385                         listManager.countTagResults(listManager.getNoteIndex());
2386                 if (notebookTree.selectedItems().size() > 0 
2387                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2388                                                   filter = true;
2389                 if (tagTree.selectedItems().size() > 0)
2390                         filter = true;
2391                 tagTree.showAllTags(!filter);
2392                 tagIndexUpdated(false);
2393                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2394         }
2395         // Edit an existing tag
2396         @SuppressWarnings("unused")
2397         private void editTag() {
2398                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2399                 TagEdit edit = new TagEdit();
2400                 edit.setTitle("Edit Tag");
2401                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2402                 QTreeWidgetItem currentSelection;
2403                 currentSelection = selections.get(0);
2404                 edit.setTag(currentSelection.text(0));
2405                 edit.setTagList(listManager.getTagIndex());
2406                 edit.exec();
2407         
2408                 if (!edit.okPressed())
2409                         return;
2410         
2411                 String guid = currentSelection.text(2);
2412                 currentSelection.setText(0,edit.getTag());
2413                 
2414                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2415                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2416                                 listManager.getTagIndex().get(i).setName(edit.getTag());
2417                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2418                                 updateListTagName(guid);
2419                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2420                                         browserWindow.setTag(getTagNamesForNote(currentNote));
2421                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2422                                 //return;
2423                         }
2424                 }
2425                 listManager.reloadNoteTagNames(guid, edit.getTag());
2426                 noteIndexUpdated(true);
2427                 refreshEvernoteNote(true);
2428                 browserWindow.setTag(getTagNamesForNote(currentNote));
2429                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2430         }
2431         // Delete an existing tag
2432         @SuppressWarnings("unused")
2433         private void deleteTag() {
2434                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2435                 
2436                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2437                         QMessageBox.StandardButton.Yes, 
2438                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2439                                                         return;
2440                 }
2441                 
2442                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2443         for (int i=selections.size()-1; i>=0; i--) {
2444                 QTreeWidgetItem currentSelection;
2445                 currentSelection = selections.get(i);                   
2446                 removeTagItem(currentSelection.text(2));
2447         }
2448         tagIndexUpdated(true);
2449         tagTreeSelection();
2450         listManager.countTagResults(listManager.getNoteIndex());
2451 //              tagTree.updateCounts(listManager.getTagCounter());
2452         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2453         }
2454         // Remove a tag tree item.  Go recursively down & remove the children too
2455         private void removeTagItem(String guid) {
2456         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
2457                 String parent = listManager.getTagIndex().get(j).getParentGuid();
2458                 if (parent != null && parent.equals(guid)) {            
2459                         //Remove this tag's children
2460                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
2461                 }
2462         }
2463         //Now, remove this tag
2464         removeListTagName(guid);
2465         conn.getTagTable().expungeTag(guid, true);                      
2466         for (int a=0; a<listManager.getTagIndex().size(); a++) {
2467                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2468                         listManager.getTagIndex().remove(a);
2469                         return;
2470                 }
2471         }
2472         }
2473         // Setup the tree containing the user's tags
2474     private void initializeTagTree() {
2475         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2476 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2477 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
2478         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2479         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2480         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2481     }
2482     // Listener when a tag is selected
2483         private void tagTreeSelection() {
2484         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2485                 
2486         clearTrashFilter();
2487         clearAttributeFilter();
2488         clearSavedSearchFilter();
2489         
2490                 menuBar.noteRestoreAction.setVisible(false);
2491                 
2492                 // ICHANGED ゴミ箱から元の画面に戻す。連想ノートリストをONに。
2493                 if (!rensoNoteListDock.isEnabled()) {
2494                         rensoNoteListDock.setEnabled(true);
2495                 }
2496                 
2497         List<QTreeWidgetItem> selections = tagTree.selectedItems();
2498         QTreeWidgetItem currentSelection;
2499         selectedTagGUIDs.clear();
2500         for (int i=0; i<selections.size(); i++) {
2501                 currentSelection = selections.get(i);
2502                 selectedTagGUIDs.add(currentSelection.text(2));
2503         }
2504         if (selections.size() > 0) {
2505                 menuBar.tagEditAction.setEnabled(true);
2506                 menuBar.tagDeleteAction.setEnabled(true);
2507                 menuBar.tagIconAction.setEnabled(true);
2508         }
2509         else {
2510                 menuBar.tagEditAction.setEnabled(false);
2511                 menuBar.tagDeleteAction.setEnabled(false);
2512                 menuBar.tagIconAction.setEnabled(true);
2513         }
2514         if (selections.size() > 1)
2515                 menuBar.tagMergeAction.setEnabled(true);
2516         else
2517                 menuBar.tagMergeAction.setEnabled(false);
2518         listManager.setSelectedTags(selectedTagGUIDs);
2519         listManager.loadNotesIndex();
2520         noteIndexUpdated(false);
2521         refreshEvernoteNote(true);
2522         listManager.refreshCounters = true;
2523         listManager.refreshCounters();
2524         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2525     }
2526     // trigger the tag index to be refreshed
2527     @SuppressWarnings("unused")
2528         private void tagIndexUpdated() {
2529         tagIndexUpdated(true);
2530     }
2531     private void tagIndexUpdated(boolean reload) {
2532         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2533                 if (selectedTagGUIDs == null)
2534                         selectedTagGUIDs = new ArrayList<String>();
2535                 if (reload)
2536                         listManager.reloadTagIndex();
2537
2538                 tagTree.blockSignals(true);
2539                 if (reload) {
2540                         tagTree.setIcons(conn.getTagTable().getAllIcons());
2541                         tagTree.load(listManager.getTagIndex());
2542                 }
2543
2544         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2545                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2546                 if (!found)
2547                         selectedTagGUIDs.remove(i);
2548         }
2549         tagTree.blockSignals(false);
2550         
2551                 browserWindow.setTag(getTagNamesForNote(currentNote));
2552         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2553     }   
2554     // Show/Hide note information
2555         @SuppressWarnings("unused")
2556         private void toggleTagWindow() {
2557                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2558         if (tagTree.isVisible())
2559                 tagTree.hide();
2560         else
2561                 tagTree.show();
2562         menuBar.hideTags.setChecked(tagTree.isVisible());
2563         Global.saveWindowVisible("tagTree", tagTree.isVisible());
2564         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2565     }   
2566         // A note's tags have been updated
2567         @SuppressWarnings("unused")
2568         private void updateNoteTags(String guid, List<String> tags) {
2569                 // Save any new tags.  We'll need them later.
2570                 List<String> newTags = new ArrayList<String>();
2571                 for (int i=0; i<tags.size(); i++) {
2572                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
2573                                 newTags.add(tags.get(i));
2574                 }
2575                 
2576                 listManager.saveNoteTags(guid, tags, true);
2577                 listManager.countTagResults(listManager.getNoteIndex());
2578                 StringBuffer names = new StringBuffer("");
2579                 for (int i=0; i<tags.size(); i++) {
2580                         names = names.append(tags.get(i));
2581                         if (i<tags.size()-1) {
2582                                 names.append(Global.tagDelimeter + " ");
2583                         }
2584                 }
2585                 browserWindow.setTag(names.toString());
2586                 
2587                 // ICHANGED
2588                 for (TabBrowse tab: tabWindows.values()) {
2589                         if (tab.getBrowserWindow().getNote().getGuid().equals(guid)) {
2590                                 int index = tabBrowser.indexOf(tab);
2591                                 noteDirty.put(index, true);
2592                                 break;
2593                         }
2594                 }
2595                 
2596                 // Now, we need to add any new tags to the tag tree
2597                 for (int i=0; i<newTags.size(); i++) 
2598                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2599         }
2600         // Get a string containing all tag names for a note
2601         private String getTagNamesForNote(Note n) {
2602                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2603                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2604                         return "";
2605                 StringBuffer buffer = new StringBuffer(100);
2606                 Vector<String> v = new Vector<String>();
2607                 List<String> guids = n.getTagGuids();
2608                 
2609                 if (guids == null) 
2610                         return "";
2611                 
2612                 for (int i=0; i<guids.size(); i++) {
2613                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2614                 }
2615                 Comparator<String> comparator = Collections.reverseOrder();
2616                 Collections.sort(v,comparator);
2617                 Collections.reverse(v);
2618                 
2619                 for (int i = 0; i<v.size(); i++) {
2620                         if (i>0) 
2621                                 buffer.append(", ");
2622                         buffer.append(v.get(i));
2623                 }
2624                 
2625                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2626                 return buffer.toString();
2627         }       
2628         // Tags were added via dropping notes from the note list
2629         @SuppressWarnings("unused")
2630         private void tagsAdded(String noteGuid, String tagGuid) {
2631                 String tagName = null;
2632                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2633                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2634                                 tagName = listManager.getTagIndex().get(i).getName();
2635                                 i=listManager.getTagIndex().size();
2636                         }
2637                 }
2638                 if (tagName == null)
2639                         return;
2640                 
2641                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2642                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2643                                 List<String> tagNames = new ArrayList<String>();
2644                                 tagNames.add(new String(tagName));
2645                                 Note n = listManager.getMasterNoteIndex().get(i);
2646                                 for (int j=0; j<n.getTagNames().size(); j++) {
2647                                         tagNames.add(new String(n.getTagNames().get(j)));
2648                                 }
2649                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2650                                 if (n.getGuid().equals(currentNoteGuid)) {
2651                                         Collections.sort(tagNames);
2652                                         String display = "";
2653                                         for (int j=0; j<tagNames.size(); j++) {
2654                                                 display = display+tagNames.get(j);
2655                                                 if (j+2<tagNames.size()) 
2656                                                         display = display+Global.tagDelimeter+" ";
2657                                         }
2658                                         browserWindow.setTag(display);
2659                                 }
2660                                 i=listManager.getMasterNoteIndex().size();
2661                         }
2662                 }
2663                 
2664                 
2665                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2666         }
2667         private void clearTagFilter() {
2668                 tagTree.blockSignals(true);
2669                 tagTree.clearSelection();
2670                 menuBar.noteRestoreAction.setVisible(false);
2671                 menuBar.tagEditAction.setEnabled(false);
2672                 menuBar.tagMergeAction.setEnabled(false);
2673                 menuBar.tagDeleteAction.setEnabled(false);
2674                 menuBar.tagIconAction.setEnabled(false);
2675                 selectedTagGUIDs.clear();
2676         listManager.setSelectedTags(selectedTagGUIDs);
2677         tagTree.blockSignals(false);
2678         }
2679         // Change the icon for a tag
2680         @SuppressWarnings("unused")
2681         private void setTagIcon() {
2682                 QTreeWidgetItem currentSelection;
2683                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2684                 if (selections.size() == 0)
2685                         return;
2686                 
2687                 currentSelection = selections.get(0);   
2688                 String guid = currentSelection.text(2);
2689
2690                 QIcon currentIcon = currentSelection.icon(0);
2691                 QIcon icon = conn.getTagTable().getIcon(guid);
2692                 SetIcon dialog;
2693                 if (icon == null) {
2694                         dialog = new SetIcon(currentIcon, saveLastPath);
2695                         dialog.setUseDefaultIcon(true);
2696                 } else {
2697                         dialog = new SetIcon(icon, saveLastPath);
2698                         dialog.setUseDefaultIcon(false);
2699                 }
2700                 dialog.exec();
2701                 if (dialog.okPressed()) {
2702                 saveLastPath = dialog.getPath();
2703                         QIcon newIcon = dialog.getIcon();
2704                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2705                         if (newIcon == null) 
2706                                 newIcon = new QIcon(iconPath+"tag.png");
2707                         currentSelection.setIcon(0, newIcon);
2708                 }
2709         
2710         }
2711         // Merge tags
2712         @SuppressWarnings("unused")
2713         private void mergeTags() {
2714                 List<Tag> tags = new ArrayList<Tag>();
2715                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2716                 for (int i=0; i<selections.size(); i++) {
2717                         Tag record = new Tag();
2718                         record.setGuid(selections.get(i).text(2));
2719                         record.setName(selections.get(i).text(0));
2720                         tags.add(record);
2721                 }
2722
2723                 TagMerge mergeDialog = new TagMerge(tags);
2724                 mergeDialog.exec();
2725                 if (!mergeDialog.okClicked())
2726                         return;
2727                 String newGuid = mergeDialog.getNewTagGuid();
2728                 
2729                 for (int i=0; i<tags.size(); i++) {
2730                         if (!tags.get(i).getGuid().equals(newGuid)) {
2731                                 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2732                                 for (int j=0; j<noteGuids.size(); j++) {
2733                                         String noteGuid = noteGuids.get(j);
2734                                         conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2735                                         if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2736                                                 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid, true);
2737                                 }
2738                         }
2739                 }
2740                 listManager.reloadIndexes();
2741         }
2742         
2743     //***************************************************************
2744     //***************************************************************
2745     //** These functions deal with Saved Search menu items
2746     //***************************************************************
2747     //***************************************************************
2748         // Add a new notebook
2749         @SuppressWarnings("unused")
2750         private void addSavedSearch() {
2751                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2752                 SavedSearchEdit edit = new SavedSearchEdit();
2753                 edit.setSearchList(listManager.getSavedSearchIndex());
2754                 edit.exec();
2755         
2756                 if (!edit.okPressed())
2757                         return;
2758         
2759                 Calendar currentTime = new GregorianCalendar();         
2760                 Long l = new Long(currentTime.getTimeInMillis());
2761                 String randint = new String(Long.toString(l));
2762         
2763                 SavedSearch search = new SavedSearch();
2764                 search.setUpdateSequenceNum(0);
2765                 search.setGuid(randint);
2766                 search.setName(edit.getName());
2767                 search.setQuery(edit.getQuery());
2768                 search.setFormat(QueryFormat.USER);
2769                 listManager.getSavedSearchIndex().add(search);
2770                 conn.getSavedSearchTable().addSavedSearch(search, true);
2771                 savedSearchIndexUpdated();
2772                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2773         }
2774         // Edit an existing tag
2775         @SuppressWarnings("unused")
2776         private void editSavedSearch() {
2777                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2778                 SavedSearchEdit edit = new SavedSearchEdit();
2779                 edit.setTitle(tr("Edit Search"));
2780                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2781                 QTreeWidgetItem currentSelection;
2782                 currentSelection = selections.get(0);
2783                 String guid = currentSelection.text(1);
2784                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2785                 edit.setName(currentSelection.text(0));
2786                 edit.setQuery(s.getQuery());
2787                 edit.setSearchList(listManager.getSavedSearchIndex());
2788                 edit.exec();
2789         
2790                 if (!edit.okPressed())
2791                         return;
2792         
2793                 List<SavedSearch> list = listManager.getSavedSearchIndex();
2794                 SavedSearch search = null;
2795                 boolean found = false;
2796                 for (int i=0; i<list.size(); i++) {
2797                         search = list.get(i);
2798                         if (search.getGuid().equals(guid)) {
2799                                 i=list.size();
2800                                 found = true;
2801                         }
2802                 }
2803                 if (!found)
2804                         return;
2805                 search.setName(edit.getName());
2806                 search.setQuery(edit.getQuery());
2807                 conn.getSavedSearchTable().updateSavedSearch(search, true);
2808                 savedSearchIndexUpdated();
2809                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2810         }
2811         // Delete an existing tag
2812         @SuppressWarnings("unused")
2813         private void deleteSavedSearch() {
2814                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2815                 
2816                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2817                         QMessageBox.StandardButton.Yes, 
2818                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2819                                                         return;
2820                 }
2821                 
2822                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2823         for (int i=selections.size()-1; i>=0; i--) {
2824                 QTreeWidgetItem currentSelection;
2825                 currentSelection = selections.get(i);
2826                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2827                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2828                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2829                                 listManager.getSavedSearchIndex().remove(j);
2830                                 j=listManager.getSavedSearchIndex().size()+1;
2831                         }
2832                 }
2833                 selections.remove(i);
2834         }
2835         savedSearchIndexUpdated();
2836         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2837         }
2838     // Setup the tree containing the user's tags
2839     private void initializeSavedSearchTree() {
2840         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2841         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2842         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2843     }
2844     // Listener when a tag is selected
2845     @SuppressWarnings("unused")
2846         private void savedSearchTreeSelection() {
2847         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2848
2849         clearNotebookFilter();
2850         clearTagFilter();
2851         clearTrashFilter();
2852         clearAttributeFilter();
2853         
2854         String currentGuid = selectedSavedSearchGUID;
2855         menuBar.savedSearchEditAction.setEnabled(true);
2856         menuBar.savedSearchDeleteAction.setEnabled(true);
2857         menuBar.savedSearchIconAction.setEnabled(true);
2858         
2859                 // ICHANGED ゴミ箱から元の画面に戻す。連想ノートリストをONに。
2860                 if (!rensoNoteListDock.isEnabled()) {
2861                         rensoNoteListDock.setEnabled(true);
2862                 }
2863                 
2864         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2865         QTreeWidgetItem currentSelection;
2866         selectedSavedSearchGUID = "";
2867         for (int i=0; i<selections.size(); i++) {
2868                 currentSelection = selections.get(i);
2869                 if (currentSelection.text(1).equals(currentGuid)) {
2870                         currentSelection.setSelected(false);
2871                 } else {
2872                         selectedSavedSearchGUID = currentSelection.text(1);
2873                 }
2874 //              i = selections.size() +1;
2875         }
2876         
2877         // There is the potential for no notebooks to be selected if this 
2878         // happens then we make it look like all notebooks were selecetd.
2879         // If that happens, just select the "all notebooks"
2880         if (selections.size()==0) {
2881                 clearSavedSearchFilter();
2882         }
2883         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2884         
2885         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2886     }
2887     private void clearSavedSearchFilter() {
2888         menuBar.savedSearchEditAction.setEnabled(false);
2889         menuBar.savedSearchDeleteAction.setEnabled(false);
2890         menuBar.savedSearchIconAction.setEnabled(false);
2891         savedSearchTree.blockSignals(true);
2892         savedSearchTree.clearSelection();
2893         savedSearchTree.blockSignals(false);
2894         selectedSavedSearchGUID = "";
2895         searchField.setEditText("");
2896         searchPerformed = false;
2897         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2898     }
2899     // trigger the tag index to be refreshed
2900         private void savedSearchIndexUpdated() { 
2901                 if (selectedSavedSearchGUID == null)
2902                         selectedSavedSearchGUID = new String();
2903                 savedSearchTree.blockSignals(true);
2904                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2905         savedSearchTree.load(listManager.getSavedSearchIndex());
2906         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2907         savedSearchTree.blockSignals(false);
2908     }
2909     // trigger when the saved search selection changes
2910     @SuppressWarnings("unused")
2911         private void updateSavedSearchSelection() {
2912                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2913                 
2914         menuBar.savedSearchEditAction.setEnabled(true);
2915         menuBar.savedSearchDeleteAction.setEnabled(true);
2916         menuBar.savedSearchIconAction.setEnabled(true);
2917         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2918
2919         if (selections.size() > 0) {
2920                 menuBar.savedSearchEditAction.setEnabled(true);
2921                 menuBar.savedSearchDeleteAction.setEnabled(true);
2922                 menuBar.savedSearchIconAction.setEnabled(true);
2923                 selectedSavedSearchGUID = selections.get(0).text(1);
2924                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2925                 searchField.setEditText(s.getQuery());
2926         } else { 
2927                 menuBar.savedSearchEditAction.setEnabled(false);
2928                 menuBar.savedSearchDeleteAction.setEnabled(false);
2929                 menuBar.savedSearchIconAction.setEnabled(false);
2930                 selectedSavedSearchGUID = "";
2931                 searchField.setEditText("");
2932         }
2933         searchFieldChanged();
2934         
2935                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2936
2937         
2938     }
2939     // Show/Hide note information
2940         @SuppressWarnings("unused")
2941         private void toggleSavedSearchWindow() {
2942                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2943         if (savedSearchTree.isVisible())
2944                 savedSearchTree.hide();
2945         else
2946                 savedSearchTree.show();
2947         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2948                                 
2949                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2950         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2951     }
2952         // Change the icon for a saved search
2953         @SuppressWarnings("unused")
2954         private void setSavedSearchIcon() {
2955                 QTreeWidgetItem currentSelection;
2956                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2957                 if (selections.size() == 0)
2958                         return;
2959                 
2960                 currentSelection = selections.get(0);   
2961                 String guid = currentSelection.text(1);
2962
2963                 QIcon currentIcon = currentSelection.icon(0);
2964                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2965                 SetIcon dialog;
2966                 if (icon == null) {
2967                         dialog = new SetIcon(currentIcon, saveLastPath);
2968                         dialog.setUseDefaultIcon(true);
2969                 } else {
2970                         dialog = new SetIcon(icon, saveLastPath);
2971                         dialog.setUseDefaultIcon(false);
2972                 }
2973                 dialog.exec();
2974                 if (dialog.okPressed()) {
2975                 saveLastPath = dialog.getPath();
2976                         QIcon newIcon = dialog.getIcon();
2977                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2978                         if (newIcon == null) 
2979                                 newIcon = new QIcon(iconPath+"search.png");
2980                         currentSelection.setIcon(0, newIcon);
2981                 }
2982         
2983         }
2984         
2985         
2986         
2987         
2988     //***************************************************************
2989     //***************************************************************
2990     //** These functions deal with Help menu & tool menu items
2991     //***************************************************************
2992     //***************************************************************
2993         // Show database status
2994         @SuppressWarnings("unused")
2995         private void databaseStatus() {
2996                 waitCursor(true);
2997                 indexRunner.interrupt = true;
2998                 int dirty = conn.getNoteTable().getDirtyCount();
2999                 int unindexed = conn.getNoteTable().getUnindexedCount();
3000                 DatabaseStatus status = new DatabaseStatus();
3001                 status.setUnsynchronized(dirty);
3002                 status.setUnindexed(unindexed);
3003                 status.setNoteCount(conn.getNoteTable().getNoteCount());
3004                 status.setNotebookCount(listManager.getNotebookIndex().size());
3005                 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
3006                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
3007                 status.setTagCount(listManager.getTagIndex().size());
3008                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
3009                 status.setWordCount(conn.getWordsTable().getWordCount());
3010                 waitCursor(false);
3011                 status.exec();
3012         }
3013         // Compact the database
3014         @SuppressWarnings("unused")
3015         private void compactDatabase() {
3016         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
3017                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
3018                                 "but please be aware that depending upon the size of your database this can be time consuming " +
3019                                 "and NeighborNote will be unresponsive until it is complete.  Do you wish to continue?"),
3020       &n