OSDN Git Service

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