OSDN Git Service

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