OSDN Git Service

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