OSDN Git Service

検索ボックスをツールバー右側に移動&改良した
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / NeverNote.java
1 /*
2   * This file is part of NixNote/NeighborNote 
3  * Copyright 2009 Randy Baumgarte
4  * Copyright 2013 Yuki Takahashi
5  * 
6  * This file may be licensed under the terms of of the
7  * GNU General Public License Version 2 (the ``GPL'').
8  *
9  * Software distributed under the License is distributed
10  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
11  * express or implied. See the GPL for the specific language
12  * governing rights and limitations.
13  *
14  * You should have received a copy of the GPL along with this
15  * program. If not, go to http://www.gnu.org/licenses/gpl.html
16  * or write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19 */
20 package cx.fbn.nevernote;
21 import java.awt.Desktop;
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.FileNotFoundException;
25 import java.io.FileOutputStream;
26 import java.net.Authenticator;
27 import java.net.PasswordAuthentication;
28 import java.security.MessageDigest;
29 import java.security.NoSuchAlgorithmException;
30 import java.sql.Connection;
31 import java.sql.DriverManager;
32 import java.sql.SQLException;
33 import java.sql.Statement;
34 import java.text.SimpleDateFormat;
35 import java.util.ArrayList;
36 import java.util.Calendar;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.Comparator;
40 import java.util.Date;
41 import java.util.GregorianCalendar;
42 import java.util.HashMap;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.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                 String guid = "";
1642                 String stackName = "";
1643                 if (selections.size() > 0) {
1644                 guid = (selections.get(0).text(2));
1645                 stackName = selections.get(0).text(0);
1646         }
1647                 if (!Global.mimicEvernoteInterface) {
1648                         // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1649                         if (selections.size()==0) {
1650                                 selectedNotebookGUIDs.clear();
1651                                 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1652                                         selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1653                                 }
1654                                 menuBar.notebookEditAction.setEnabled(false);
1655                                 menuBar.notebookDeleteAction.setEnabled(false);
1656                                 menuBar.notebookStackAction.setEnabled(false);
1657                                 menuBar.notebookIconAction.setEnabled(false);
1658                         }
1659                 }
1660         if (!guid.equals("") && !guid.equals("STACK")) {
1661                 selectedNotebookGUIDs.add(guid);
1662                 menuBar.notebookIconAction.setEnabled(true);
1663         } else {
1664                 menuBar.notebookIconAction.setEnabled(true);
1665                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1666                                 Notebook book = listManager.getNotebookIndex().get(j);
1667                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1668                                         selectedNotebookGUIDs.add(book.getGuid());
1669                         }
1670         }
1671         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1672         listManager.loadNotesIndex();
1673         noteIndexUpdated(false);
1674         refreshEvernoteNote(true);
1675         listManager.refreshCounters = true;
1676         listManager.refreshCounters();
1677         if (selectedNotebookGUIDs.size() == 1) {
1678                 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1679                 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1680                 if (col != -1) {
1681                         noteTableView.proxyModel.blocked = true;
1682                         if (order == 1)
1683                                 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1684                         else
1685                                 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1686                 }
1687         }
1688         noteTableView.proxyModel.blocked = false;
1689                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1690
1691     }
1692     private void clearNotebookFilter() {
1693         notebookTree.blockSignals(true);
1694         notebookTree.clearSelection();
1695                 menuBar.noteRestoreAction.setVisible(false);
1696         menuBar.notebookEditAction.setEnabled(false);
1697         menuBar.notebookDeleteAction.setEnabled(false);
1698         selectedNotebookGUIDs.clear();
1699         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1700         notebookTree.blockSignals(false);
1701     }
1702         // Triggered when the notebook DB has been updated
1703         private void notebookIndexUpdated() {
1704                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1705         
1706                 // Get the possible icons
1707                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1708         notebookTree.setIcons(icons);
1709         
1710         if (selectedNotebookGUIDs == null)
1711                         selectedNotebookGUIDs = new ArrayList<String>();
1712                 List<Notebook> books = conn.getNotebookTable().getAll();
1713                 for (int i=books.size()-1; i>=0; i--) {
1714                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1715                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1716                                         books.remove(i);
1717                                         j=listManager.getArchiveNotebookIndex().size();
1718                                 }
1719                         }
1720                 }
1721                 
1722                 
1723                 listManager.countNotebookResults(listManager.getNoteIndex());
1724                 notebookTree.blockSignals(true);
1725         notebookTree.load(books, listManager.getLocalNotebooks());
1726         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1727                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1728                 if (!found)
1729                         selectedNotebookGUIDs.remove(i);
1730         }
1731         listManager.refreshCounters = true;
1732         listManager.refreshCounters();
1733         notebookTree.blockSignals(false);
1734         
1735                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1736     }
1737     // Show/Hide note information
1738         @SuppressWarnings("unused")
1739         private void toggleNotebookWindow() {
1740                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1741                 zoomLayout.toggleNotebook();
1742         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1743         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1744         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1745     }   
1746         // Add a new notebook
1747         @SuppressWarnings("unused")
1748         private void addNotebook() {
1749                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1750                 NotebookEdit edit = new NotebookEdit();
1751                 edit.setNotebooks(listManager.getNotebookIndex());
1752                 edit.exec();
1753         
1754                 if (!edit.okPressed())
1755                         return;
1756         
1757                 Calendar currentTime = new GregorianCalendar();
1758                 Long l = new Long(currentTime.getTimeInMillis());
1759                 String randint = new String(Long.toString(l));
1760         
1761                 Notebook newBook = new Notebook();
1762                 newBook.setUpdateSequenceNum(0);
1763                 newBook.setGuid(randint);
1764                 newBook.setName(edit.getNotebook());
1765                 newBook.setServiceCreated(new Date().getTime());
1766                 newBook.setServiceUpdated(new Date().getTime());
1767                 newBook.setDefaultNotebook(false);
1768                 newBook.setPublished(false);
1769                 
1770                 listManager.getNotebookIndex().add(newBook);
1771                 if (edit.isLocal())
1772                         listManager.getLocalNotebooks().add(newBook.getGuid());
1773                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1774                 notebookIndexUpdated();
1775                 listManager.countNotebookResults(listManager.getNoteIndex());
1776 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1777                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1778         }
1779         // Edit an existing notebook
1780         @SuppressWarnings("unused")
1781         private void stackNotebook() {
1782                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1783                 StackNotebook edit = new StackNotebook();
1784                 
1785                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1786                 QTreeWidgetItem currentSelection;
1787                 for (int i=0; i<selections.size(); i++) {
1788                         currentSelection = selections.get(0);
1789                         String guid = currentSelection.text(2);
1790                         if (guid.equalsIgnoreCase("")) {
1791                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1792                                  return;
1793                         }
1794                         if (guid.equalsIgnoreCase("STACK")) {
1795                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1796                                  return;
1797                         }
1798                 }
1799
1800                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1801
1802                 
1803                 edit.exec();
1804         
1805                 if (!edit.okPressed())
1806                         return;
1807         
1808                 String stack = edit.getStackName();
1809                 
1810                 for (int i=0; i<selections.size(); i++) {
1811                         currentSelection = selections.get(i);
1812                         String guid = currentSelection.text(2);
1813                         listManager.updateNotebookStack(guid, stack);
1814                 }
1815                 notebookIndexUpdated();
1816                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1817         }
1818         // Edit an existing notebook
1819         @SuppressWarnings("unused")
1820         private void editNotebook() {
1821                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1822                 NotebookEdit edit = new NotebookEdit();
1823                 
1824                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1825                 QTreeWidgetItem currentSelection;
1826                 currentSelection = selections.get(0);
1827                 edit.setNotebook(currentSelection.text(0));
1828                 
1829                 String guid = currentSelection.text(2);
1830                 if (!guid.equalsIgnoreCase("STACK")) {
1831                         edit.setTitle(tr("Edit Notebook"));
1832                         edit.setNotebooks(listManager.getNotebookIndex());
1833                         edit.setLocalCheckboxEnabled(false);
1834                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1835                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1836                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1837                                         i=listManager.getNotebookIndex().size();
1838                                 }
1839                         }
1840                 } else {
1841                         edit.setTitle(tr("Edit Stack"));
1842                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1843                         edit.hideLocalCheckbox();
1844                         edit.hideDefaultCheckbox();
1845                 }
1846                 
1847                 edit.exec();
1848         
1849                 if (!edit.okPressed())
1850                         return;
1851         
1852                 
1853                 if (guid.equalsIgnoreCase("STACK")) {
1854                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1855                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1856                                 if (listManager.getNotebookIndex().get(j).getStack() != null && 
1857                                         listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1858                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1859                         }
1860                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1861                         currentSelection.setText(0, edit.getNotebook());
1862                         return;
1863                 }
1864                 
1865                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1866                 currentSelection.setText(0, edit.getNotebook());
1867                 
1868                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1869                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1870                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1871                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1872                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1873                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1874                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1875                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1876                                 }
1877                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1878                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1879                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1880                                         linkedNotebook.setShareName(edit.getNotebook());
1881                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1882                                 }
1883                                 i=listManager.getNotebookIndex().size();
1884                         }
1885                 }
1886                 
1887                 // Build a list of non-closed notebooks
1888                 List<Notebook> nbooks = new ArrayList<Notebook>();
1889                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1890                         boolean found=false;
1891                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1892                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1893                                         found = true;
1894                         }
1895                         if (!found)
1896                                 nbooks.add(listManager.getNotebookIndex().get(i));
1897                 }
1898                 
1899                 
1900                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1901                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1902                 browserWindow.setNotebookList(filteredBooks);
1903                 Iterator<String> set = externalWindows.keySet().iterator();
1904                 while(set.hasNext())
1905                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1906                 
1907                 Iterator<Integer>it = tabWindows.keySet().iterator();
1908                 while (it.hasNext()) {
1909                         tabWindows.get(it.next()).getBrowserWindow()
1910                                         .setNotebookList(filteredBooks);
1911                 }
1912                 
1913                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1914         }
1915         // Publish a notebook
1916         @SuppressWarnings("unused")
1917         private void publishNotebook() {
1918                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1919                 QTreeWidgetItem currentSelection;
1920                 currentSelection = selections.get(0);
1921                 String guid = currentSelection.text(2);
1922
1923                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1924                         return;
1925                 
1926                 Notebook n = null;
1927                 int position = 0;
1928                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1929                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1930                                 n = listManager.getNotebookIndex().get(i);
1931                                 position = i;
1932                                 i = listManager.getNotebookIndex().size();
1933                         }
1934                 }
1935                 if (n == null)
1936                         return;
1937                 
1938                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1939                 publish.exec();
1940                 
1941                 if (!publish.okClicked()) 
1942                         return;
1943                 
1944                 Publishing p = publish.getPublishing();
1945                 boolean isPublished = !publish.isStopPressed();
1946                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1947                 n.setPublished(isPublished);
1948                 n.setPublishing(p);
1949                 listManager.getNotebookIndex().set(position, n);
1950                 notebookIndexUpdated();
1951         }
1952         // Publish a notebook
1953         @SuppressWarnings("unused")
1954         private void shareNotebook() {
1955                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1956                 QTreeWidgetItem currentSelection;
1957                 currentSelection = selections.get(0);
1958                 String guid = currentSelection.text(2);
1959
1960                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1961                         return;
1962                 
1963                 Notebook n = null;;
1964                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1965                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1966                                 n = listManager.getNotebookIndex().get(i);
1967                                 i = listManager.getNotebookIndex().size();
1968                         }
1969                 }
1970                                 
1971                 String authToken = null;
1972                 if (syncRunner.isConnected)
1973                         authToken = syncRunner.authToken;
1974                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1975                 share.exec();
1976                 
1977         }
1978
1979         // Delete an existing notebook
1980         @SuppressWarnings("unused")
1981         private void deleteNotebook() {
1982                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1983                 boolean stacksFound = false;
1984                 boolean notebooksFound = false;
1985                 boolean assigned = false;
1986                 // Check if any notes have this notebook
1987                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1988         for (int i=0; i<selections.size(); i++) {
1989                 QTreeWidgetItem currentSelection;
1990                 currentSelection = selections.get(i);
1991                 String guid = currentSelection.text(2);
1992                 if (!guid.equalsIgnoreCase("STACK")) {
1993                         notebooksFound = true;
1994                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1995                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1996                                 if (noteGuid.equals(guid)) {
1997                                         assigned = true;
1998                                         j=listManager.getNoteIndex().size();
1999                                         i=selections.size();
2000                                 }
2001                         }
2002                 } else {
2003                         stacksFound = true;
2004                 }
2005         }
2006                 if (assigned) {
2007                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
2008                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
2009                         return;
2010                 }
2011                 
2012                 if (conn.getNotebookTable().getAll().size() == 1) {
2013                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
2014                         return;
2015                 }
2016         
2017         // If all notebooks are clear, verify the delete
2018                 String msg1 = new String(tr("Delete selected notebooks?"));
2019                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
2020                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
2021                                 " not deleted unless selected?"));
2022                 String msg = "";
2023                 if (stacksFound && notebooksFound)
2024                         msg = msg3;
2025                 if (!stacksFound && notebooksFound)
2026                         msg = msg1;
2027                 if (stacksFound && !notebooksFound)
2028                         msg = msg2;
2029                 if (QMessageBox.question(this, tr("Confirmation"), msg,
2030                         QMessageBox.StandardButton.Yes, 
2031                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2032                         return;
2033                 }
2034                 
2035                 // If confirmed, delete the notebook
2036         for (int i=selections.size()-1; i>=0; i--) {
2037                 QTreeWidgetItem currentSelection;
2038                 currentSelection = selections.get(i);
2039                 String guid = currentSelection.text(2);
2040                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
2041                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
2042                         listManager.renameStack(currentSelection.text(0), "");
2043                 } else {
2044                         conn.getNotebookTable().expungeNotebook(guid, true);
2045                         listManager.deleteNotebook(guid);
2046                 }
2047         }
2048
2049                 notebookIndexUpdated();
2050 //        notebookTreeSelection();
2051 //        notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
2052 //        listManager.countNotebookResults(listManager.getNoteIndex());
2053         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
2054         }
2055         // A note's notebook has been updated
2056         @SuppressWarnings("unused")
2057         private void updateNoteNotebook(String guid, String notebookGuid) {
2058                 // 同じノートブックに入れられたノート間の履歴を登録
2059                 conn.getHistoryTable().addSameNotebookHistory(guid, notebookGuid);
2060                 
2061                 // Update the list manager
2062                 listManager.updateNoteNotebook(guid, notebookGuid);
2063                 listManager.countNotebookResults(listManager.getNoteIndex());
2064 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
2065                 
2066                 // Find the name of the notebook
2067                 String notebookName = null;
2068                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
2069                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
2070                                 notebookName = listManager.getNotebookIndex().get(i).getName();
2071                                 break;
2072                         }
2073                 }
2074                 
2075                 // If we found the name, update the browser window
2076                 if (notebookName != null) {
2077                         updateListNoteNotebook(guid, notebookName);
2078                         if (guid.equals(currentNoteGuid)) {
2079                                 int pos =  browserWindow.notebookBox.findText(notebookName);
2080                                 if (pos >=0)
2081                                         browserWindow.notebookBox.setCurrentIndex(pos);
2082                         }
2083                 }
2084                 
2085                 // If we're dealing with the current note, then we need to be sure and update the notebook there
2086                 if (guid.equals(currentNoteGuid)) {
2087                         if (currentNote != null) {
2088                                 currentNote.setNotebookGuid(notebookGuid);
2089                         }
2090                 }
2091         }
2092         // Open/close notebooks
2093         @SuppressWarnings("unused")
2094         private void closeNotebooks() {
2095                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
2096                 na.exec();
2097                 if (!na.okClicked())
2098                         return;
2099                 
2100                 waitCursor(true);
2101                 listManager.getArchiveNotebookIndex().clear();
2102                 
2103                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
2104                         String text = na.getClosedBookList().takeItem(i).text();
2105                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
2106                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
2107                                         Notebook n = listManager.getNotebookIndex().get(j);
2108                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
2109                                         listManager.getArchiveNotebookIndex().add(n);
2110                                         j=listManager.getNotebookIndex().size();
2111                                 }
2112                         }
2113                 }
2114                 
2115                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
2116                         String text = na.getOpenBookList().takeItem(i).text();
2117                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
2118                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
2119                                         Notebook n = listManager.getNotebookIndex().get(j);
2120                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
2121                                         j=listManager.getNotebookIndex().size();
2122                                 }
2123                         }
2124                 }
2125                 notebookTreeSelection();
2126                 listManager.loadNotesIndex();
2127                 notebookIndexUpdated();
2128                 noteIndexUpdated(false);
2129                 reloadTagTree(true);
2130 //              noteIndexUpdated(false);
2131                 
2132                 // Build a list of non-closed notebooks
2133                 List<Notebook> nbooks = new ArrayList<Notebook>();
2134                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
2135                         boolean found=false;
2136                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
2137                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
2138                                         found = true;
2139                         }
2140                         if (!found)
2141                                 nbooks.add(listManager.getNotebookIndex().get(i));
2142                 }
2143                 
2144                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
2145                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
2146                 browserWindow.setNotebookList(filteredBooks);
2147                 
2148                 // Update any external windows
2149                 Iterator<String> set = externalWindows.keySet().iterator();
2150                 while(set.hasNext())
2151                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
2152                 
2153                 // 全てのタブウィンドウを更新
2154                 Iterator<Integer> it = tabWindows.keySet().iterator();
2155                 while (it.hasNext()) {
2156                         tabWindows.get(it.next()).getBrowserWindow()
2157                                         .setNotebookList(filteredBooks);
2158                 }
2159                 
2160                 waitCursor(false);
2161         }
2162         // Change the notebook's icon
2163         @SuppressWarnings("unused")
2164         private void setNotebookIcon() {
2165                 boolean stackSelected = false;
2166                 boolean allNotebookSelected = false;
2167                 
2168                 QTreeWidgetItem currentSelection;
2169                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
2170                 if (selections.size() == 0)
2171                         return;
2172                 
2173                 currentSelection = selections.get(0);   
2174                 String guid = currentSelection.text(2);
2175                 if (guid.equalsIgnoreCase(""))
2176                         allNotebookSelected = true;
2177                 if (guid.equalsIgnoreCase("STACK"))
2178                         stackSelected = true;
2179
2180                 QIcon currentIcon = currentSelection.icon(0);
2181                 QIcon icon;
2182                 SetIcon dialog;
2183                 
2184                 if (!stackSelected && !allNotebookSelected) {
2185                         icon = conn.getNotebookTable().getIcon(guid);
2186                         if (icon == null) {
2187                                 dialog = new SetIcon(currentIcon, saveLastPath);
2188                                 dialog.setUseDefaultIcon(true);
2189                         } else {
2190                                 dialog = new SetIcon(icon, saveLastPath);
2191                                 dialog.setUseDefaultIcon(false);
2192                         }
2193                 } else {
2194                         if (stackSelected) {
2195                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
2196                         } else {
2197                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
2198                         }
2199                         if (icon == null) {
2200                                 dialog = new SetIcon(currentIcon, saveLastPath);
2201                                 dialog.setUseDefaultIcon(true);
2202                         } else {
2203                                 dialog = new SetIcon(icon, saveLastPath);
2204                                 dialog.setUseDefaultIcon(false);
2205                         }
2206                 }
2207                 dialog.exec();
2208                 if (dialog.okPressed()) {
2209                 saveLastPath = dialog.getPath();
2210
2211                         QIcon newIcon = dialog.getIcon();
2212                         if (stackSelected) {
2213                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
2214                                 if (newIcon == null) {
2215                                         newIcon = new QIcon(iconPath+"books2.png");
2216                                 }
2217                                 currentSelection.setIcon(0,newIcon);
2218                                 return;
2219                         }
2220                         if (allNotebookSelected) {
2221                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
2222                                 if (newIcon == null) {
2223                                         newIcon = new QIcon(iconPath+"notebook-green.png");
2224                                 }
2225                                 currentSelection.setIcon(0,newIcon);
2226                                 return;
2227                         }
2228                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
2229                         if (newIcon == null) {
2230                                 boolean isPublished = false;;
2231                                 boolean found = false;
2232                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
2233                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
2234                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
2235                                                 found = true;
2236                                         }
2237                                 }
2238                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
2239                         }
2240                         currentSelection.setIcon(0, newIcon);
2241                 }
2242         
2243         }
2244         
2245         
2246     //***************************************************************
2247     //***************************************************************
2248     //** These functions deal with Tag menu items
2249     //***************************************************************
2250     //***************************************************************
2251         // Add a new notebook
2252         @SuppressWarnings("unused")
2253         private void addTag() {
2254                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2255                 TagEdit edit = new TagEdit();
2256                 edit.setTagList(listManager.getTagIndex());
2257
2258                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2259                 QTreeWidgetItem currentSelection = null;
2260                 if (selections.size() > 0) {
2261                         currentSelection = selections.get(0);
2262                         edit.setParentTag(currentSelection.text(0));
2263                 }
2264
2265                 edit.exec();
2266         
2267                 if (!edit.okPressed())
2268                         return;
2269         
2270                 Calendar currentTime = new GregorianCalendar();
2271                 Long l = new Long(currentTime.getTimeInMillis());
2272                 String randint = new String(Long.toString(l));
2273         
2274                 Tag newTag = new Tag();
2275                 newTag.setUpdateSequenceNum(0);
2276                 newTag.setGuid(randint);
2277                 newTag.setName(edit.getTag());
2278                 if (edit.getParentTag().isChecked()) {
2279                         newTag.setParentGuid(currentSelection.text(2));
2280                         newTag.setParentGuidIsSet(true);
2281                         currentSelection.setExpanded(true);
2282                 }
2283                 conn.getTagTable().addTag(newTag, true);
2284                 listManager.getTagIndex().add(newTag);
2285                 reloadTagTree(true);
2286                 
2287                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2288         }
2289         @SuppressWarnings("unused")
2290         private void reloadTagTree() {
2291                 reloadTagTree(false);
2292         }
2293         private void reloadTagTree(boolean reload) {
2294                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2295                 tagIndexUpdated(reload);
2296                 boolean filter = false;
2297                 if (reload)
2298                         listManager.countTagResults(listManager.getNoteIndex());
2299                 if (notebookTree.selectedItems().size() > 0 
2300                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2301                                                   filter = true;
2302                 if (tagTree.selectedItems().size() > 0)
2303                         filter = true;
2304                 tagTree.showAllTags(!filter);
2305                 tagIndexUpdated(false);
2306                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2307         }
2308         // Edit an existing tag
2309         @SuppressWarnings("unused")
2310         private void editTag() {
2311                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2312                 TagEdit edit = new TagEdit();
2313                 edit.setTitle("Edit Tag");
2314                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2315                 QTreeWidgetItem currentSelection;
2316                 currentSelection = selections.get(0);
2317                 edit.setTag(currentSelection.text(0));
2318                 edit.setTagList(listManager.getTagIndex());
2319                 edit.exec();
2320         
2321                 if (!edit.okPressed())
2322                         return;
2323         
2324                 String guid = currentSelection.text(2);
2325                 currentSelection.setText(0,edit.getTag());
2326                 
2327                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2328                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2329                                 listManager.getTagIndex().get(i).setName(edit.getTag());
2330                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2331                                 updateListTagName(guid);
2332                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2333                                         browserWindow.setTag(getTagNamesForNote(currentNote));
2334                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2335                                 //return;
2336                         }
2337                 }
2338                 listManager.reloadNoteTagNames(guid, edit.getTag());
2339                 noteIndexUpdated(true);
2340                 refreshEvernoteNote(true);
2341                 browserWindow.setTag(getTagNamesForNote(currentNote));
2342                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2343         }
2344         // Delete an existing tag
2345         @SuppressWarnings("unused")
2346         private void deleteTag() {
2347                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2348                 
2349                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2350                         QMessageBox.StandardButton.Yes, 
2351                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2352                                                         return;
2353                 }
2354                 
2355                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2356         for (int i=selections.size()-1; i>=0; i--) {
2357                 QTreeWidgetItem currentSelection;
2358                 currentSelection = selections.get(i);                   
2359                 removeTagItem(currentSelection.text(2));
2360         }
2361         tagIndexUpdated(true);
2362         tagTreeSelection();
2363         listManager.countTagResults(listManager.getNoteIndex());
2364 //              tagTree.updateCounts(listManager.getTagCounter());
2365         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2366         }
2367         // Remove a tag tree item.  Go recursively down & remove the children too
2368         private void removeTagItem(String guid) {
2369         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
2370                 String parent = listManager.getTagIndex().get(j).getParentGuid();
2371                 if (parent != null && parent.equals(guid)) {            
2372                         //Remove this tag's children
2373                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
2374                 }
2375         }
2376         //Now, remove this tag
2377         removeListTagName(guid);
2378         conn.getTagTable().expungeTag(guid, true);                      
2379         for (int a=0; a<listManager.getTagIndex().size(); a++) {
2380                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2381                         listManager.getTagIndex().remove(a);
2382                         return;
2383                 }
2384         }
2385         }
2386         // Setup the tree containing the user's tags
2387     private void initializeTagTree() {
2388         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2389 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2390 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
2391         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2392         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2393         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2394     }
2395     // Listener when a tag is selected
2396         private void tagTreeSelection() {
2397         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2398                 
2399         clearTrashFilter();
2400         clearAttributeFilter();
2401         clearSavedSearchFilter();
2402         
2403                 menuBar.noteRestoreAction.setVisible(false);
2404                 
2405                 // ゴミ箱から元の画面に戻す。連想ノートリストをONに。
2406                 if (!rensoNoteListDock.isEnabled()) {
2407                         rensoNoteListDock.setEnabled(true);
2408                 }
2409                 
2410         List<QTreeWidgetItem> selections = tagTree.selectedItems();
2411         QTreeWidgetItem currentSelection;
2412         selectedTagGUIDs.clear();
2413         for (int i=0; i<selections.size(); i++) {
2414                 currentSelection = selections.get(i);
2415                 selectedTagGUIDs.add(currentSelection.text(2));
2416         }
2417         if (selections.size() > 0) {
2418                 menuBar.tagEditAction.setEnabled(true);
2419                 menuBar.tagDeleteAction.setEnabled(true);
2420                 menuBar.tagIconAction.setEnabled(true);
2421         }
2422         else {
2423                 menuBar.tagEditAction.setEnabled(false);
2424                 menuBar.tagDeleteAction.setEnabled(false);
2425                 menuBar.tagIconAction.setEnabled(true);
2426         }
2427         if (selections.size() > 1)
2428                 menuBar.tagMergeAction.setEnabled(true);
2429         else
2430                 menuBar.tagMergeAction.setEnabled(false);
2431         listManager.setSelectedTags(selectedTagGUIDs);
2432         listManager.loadNotesIndex();
2433         noteIndexUpdated(false);
2434         refreshEvernoteNote(true);
2435         listManager.refreshCounters = true;
2436         listManager.refreshCounters();
2437         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2438     }
2439     // trigger the tag index to be refreshed
2440     @SuppressWarnings("unused")
2441         private void tagIndexUpdated() {
2442         tagIndexUpdated(true);
2443     }
2444     private void tagIndexUpdated(boolean reload) {
2445         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2446                 if (selectedTagGUIDs == null)
2447                         selectedTagGUIDs = new ArrayList<String>();
2448                 if (reload)
2449                         listManager.reloadTagIndex();
2450
2451                 tagTree.blockSignals(true);
2452                 if (reload) {
2453                         tagTree.setIcons(conn.getTagTable().getAllIcons());
2454                         tagTree.load(listManager.getTagIndex());
2455                 }
2456
2457         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2458                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2459                 if (!found)
2460                         selectedTagGUIDs.remove(i);
2461         }
2462         tagTree.blockSignals(false);
2463         
2464                 browserWindow.setTag(getTagNamesForNote(currentNote));
2465         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2466     }   
2467     // Show/Hide note information
2468         @SuppressWarnings("unused")
2469         private void toggleTagWindow() {
2470                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2471         if (tagTree.isVisible())
2472                 tagTree.hide();
2473         else
2474                 tagTree.show();
2475         menuBar.hideTags.setChecked(tagTree.isVisible());
2476         Global.saveWindowVisible("tagTree", tagTree.isVisible());
2477         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2478     }   
2479         // A note's tags have been updated
2480         @SuppressWarnings("unused")
2481         private void updateNoteTags(String guid, List<String> tags) {
2482                 // Save any new tags.  We'll need them later.
2483                 List<String> newTags = new ArrayList<String>();
2484                 for (int i=0; i<tags.size(); i++) {
2485                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
2486                                 newTags.add(tags.get(i));
2487                 }
2488                 
2489                 listManager.saveNoteTags(guid, tags, true);
2490                 listManager.countTagResults(listManager.getNoteIndex());
2491                 StringBuffer names = new StringBuffer("");
2492                 for (int i=0; i<tags.size(); i++) {
2493                         names = names.append(tags.get(i));
2494                         if (i<tags.size()-1) {
2495                                 names.append(Global.tagDelimeter + " ");
2496                         }
2497                 }
2498                 browserWindow.setTag(names.toString());
2499                 
2500                 for (TabBrowse tab: tabWindows.values()) {
2501                         if (tab.getBrowserWindow().getNote().getGuid().equals(guid)) {
2502                                 int index = tabBrowser.indexOf(tab);
2503                                 noteDirty.put(index, true);
2504                                 break;
2505                         }
2506                 }
2507                 
2508                 // Now, we need to add any new tags to the tag tree
2509                 for (int i=0; i<newTags.size(); i++) 
2510                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2511         }
2512         // Get a string containing all tag names for a note
2513         private String getTagNamesForNote(Note n) {
2514                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2515                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2516                         return "";
2517                 StringBuffer buffer = new StringBuffer(100);
2518                 Vector<String> v = new Vector<String>();
2519                 List<String> guids = n.getTagGuids();
2520                 
2521                 if (guids == null) 
2522                         return "";
2523                 
2524                 for (int i=0; i<guids.size(); i++) {
2525                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2526                 }
2527                 Comparator<String> comparator = Collections.reverseOrder();
2528                 Collections.sort(v,comparator);
2529                 Collections.reverse(v);
2530                 
2531                 for (int i = 0; i<v.size(); i++) {
2532                         if (i>0) 
2533                                 buffer.append(", ");
2534                         buffer.append(v.get(i));
2535                 }
2536                 
2537                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2538                 return buffer.toString();
2539         }       
2540         // Tags were added via dropping notes from the note list
2541         @SuppressWarnings("unused")
2542         private void tagsAdded(String noteGuid, String tagGuid) {
2543                 String tagName = null;
2544                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2545                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2546                                 tagName = listManager.getTagIndex().get(i).getName();
2547                                 i=listManager.getTagIndex().size();
2548                         }
2549                 }
2550                 if (tagName == null)
2551                         return;
2552                 
2553                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2554                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2555                                 List<String> tagNames = new ArrayList<String>();
2556                                 tagNames.add(new String(tagName));
2557                                 Note n = listManager.getMasterNoteIndex().get(i);
2558                                 for (int j=0; j<n.getTagNames().size(); j++) {
2559                                         tagNames.add(new String(n.getTagNames().get(j)));
2560                                 }
2561                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2562                                 if (n.getGuid().equals(currentNoteGuid)) {
2563                                         Collections.sort(tagNames);
2564                                         String display = "";
2565                                         for (int j=0; j<tagNames.size(); j++) {
2566                                                 display = display+tagNames.get(j);
2567                                                 if (j+2<tagNames.size()) 
2568                                                         display = display+Global.tagDelimeter+" ";
2569                                         }
2570                                         browserWindow.setTag(display);
2571                                 }
2572                                 i=listManager.getMasterNoteIndex().size();
2573                         }
2574                 }
2575                 
2576                 
2577                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2578         }
2579         private void clearTagFilter() {
2580                 tagTree.blockSignals(true);
2581                 tagTree.clearSelection();
2582                 menuBar.noteRestoreAction.setVisible(false);
2583                 menuBar.tagEditAction.setEnabled(false);
2584                 menuBar.tagMergeAction.setEnabled(false);
2585                 menuBar.tagDeleteAction.setEnabled(false);
2586                 menuBar.tagIconAction.setEnabled(false);
2587                 selectedTagGUIDs.clear();
2588         listManager.setSelectedTags(selectedTagGUIDs);
2589         tagTree.blockSignals(false);
2590         }
2591         // Change the icon for a tag
2592         @SuppressWarnings("unused")
2593         private void setTagIcon() {
2594                 QTreeWidgetItem currentSelection;
2595                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2596                 if (selections.size() == 0)
2597                         return;
2598                 
2599                 currentSelection = selections.get(0);   
2600                 String guid = currentSelection.text(2);
2601
2602                 QIcon currentIcon = currentSelection.icon(0);
2603                 QIcon icon = conn.getTagTable().getIcon(guid);
2604                 SetIcon dialog;
2605                 if (icon == null) {
2606                         dialog = new SetIcon(currentIcon, saveLastPath);
2607                         dialog.setUseDefaultIcon(true);
2608                 } else {
2609                         dialog = new SetIcon(icon, saveLastPath);
2610                         dialog.setUseDefaultIcon(false);
2611                 }
2612                 dialog.exec();
2613                 if (dialog.okPressed()) {
2614                 saveLastPath = dialog.getPath();
2615                         QIcon newIcon = dialog.getIcon();
2616                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2617                         if (newIcon == null) 
2618                                 newIcon = new QIcon(iconPath+"tag.png");
2619                         currentSelection.setIcon(0, newIcon);
2620                 }
2621         
2622         }
2623         // Merge tags
2624         @SuppressWarnings("unused")
2625         private void mergeTags() {
2626                 List<Tag> tags = new ArrayList<Tag>();
2627                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2628                 for (int i=0; i<selections.size(); i++) {
2629                         Tag record = new Tag();
2630                         record.setGuid(selections.get(i).text(2));
2631                         record.setName(selections.get(i).text(0));
2632                         tags.add(record);
2633                 }
2634
2635                 TagMerge mergeDialog = new TagMerge(tags);
2636                 mergeDialog.exec();
2637                 if (!mergeDialog.okClicked())
2638                         return;
2639                 String newGuid = mergeDialog.getNewTagGuid();
2640                 
2641                 for (int i=0; i<tags.size(); i++) {
2642                         if (!tags.get(i).getGuid().equals(newGuid)) {
2643                                 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2644                                 for (int j=0; j<noteGuids.size(); j++) {
2645                                         String noteGuid = noteGuids.get(j);
2646                                         conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2647                                         if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2648                                                 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid, true);
2649                                 }
2650                         }
2651                 }
2652                 listManager.reloadIndexes();
2653         }
2654         
2655     //***************************************************************
2656     //***************************************************************
2657     //** These functions deal with Saved Search menu items
2658     //***************************************************************
2659     //***************************************************************
2660         // Add a new notebook
2661         @SuppressWarnings("unused")
2662         private void addSavedSearch() {
2663                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2664                 SavedSearchEdit edit = new SavedSearchEdit();
2665                 edit.setSearchList(listManager.getSavedSearchIndex());
2666                 edit.exec();
2667         
2668                 if (!edit.okPressed())
2669                         return;
2670         
2671                 Calendar currentTime = new GregorianCalendar();         
2672                 Long l = new Long(currentTime.getTimeInMillis());
2673                 String randint = new String(Long.toString(l));
2674         
2675                 SavedSearch search = new SavedSearch();
2676                 search.setUpdateSequenceNum(0);
2677