OSDN Git Service

75018a474db65d9bcd493d650525ac0d627f7947
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / gui / RensoNoteList.java
1 /*
2  * This file is part of NeighborNote
3  * Copyright 2013 Yuki Takahashi
4  * 
5  * This file may be licensed under the terms of of the
6  * GNU General Public License Version 2 (the ``GPL'').
7  *
8  * Software distributed under the License is distributed
9  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10  * express or implied. See the GPL for the specific language
11  * governing rights and limitations.
12  *
13  * You should have received a copy of the GPL along with this
14  * program. If not, go to http://www.gnu.org/licenses/gpl.html
15  * or write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18 */
19
20 // ICHANGED
21 package cx.fbn.nevernote.gui;
22
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Set;
28
29 import com.evernote.edam.type.Note;
30 import com.trolltech.qt.QThread;
31 import com.trolltech.qt.core.QSize;
32 import com.trolltech.qt.core.Qt.MouseButton;
33 import com.trolltech.qt.gui.QAction;
34 import com.trolltech.qt.gui.QApplication;
35 import com.trolltech.qt.gui.QContextMenuEvent;
36 import com.trolltech.qt.gui.QListWidget;
37 import com.trolltech.qt.gui.QListWidgetItem;
38 import com.trolltech.qt.gui.QMenu;
39
40 import cx.fbn.nevernote.Global;
41 import cx.fbn.nevernote.NeverNote;
42 import cx.fbn.nevernote.sql.DatabaseConnection;
43 import cx.fbn.nevernote.threads.ENRelatedNotesRunner;
44 import cx.fbn.nevernote.threads.SyncRunner;
45 import cx.fbn.nevernote.utilities.ApplicationLogger;
46 import cx.fbn.nevernote.utilities.Pair;
47
48 public class RensoNoteList extends QListWidget {
49         private final DatabaseConnection conn;
50         private final ApplicationLogger logger;
51         private final HashMap<QListWidgetItem, String> rensoNoteListItems;
52         private final List<RensoNoteListItem> rensoNoteListTrueItems;
53         private String rensoNotePressedItemGuid;
54         private final QAction openNewTabAction;
55         private final QAction starAction;
56         private final QAction unstarAction;
57         private final QAction excludeNoteAction;
58         private final NeverNote parent;
59         private final QMenu menu;
60         private HashMap<String, Integer> mergedHistory;                         // マージされた操作履歴
61         private final SyncRunner syncRunner;
62         private final ENRelatedNotesRunner enRelatedNotesRunner;
63         private final QThread enRelatedNotesThread;
64         private final HashMap<String, List<String>> enRelatedNotesCache;        // Evernote関連ノートのキャッシュ<guid, 関連ノートリスト>
65         private String guid;
66         private int allPointSum;
67
68         public RensoNoteList(DatabaseConnection c, NeverNote p, SyncRunner syncRunner) {
69                 logger = new ApplicationLogger("rensoNoteList.log");
70                 logger.log(logger.HIGH, "Setting up rensoNoteList");
71                 allPointSum = 0;
72
73                 this.conn = c;
74                 this.parent = p;
75                 this.syncRunner = syncRunner;
76                 
77                 this.guid = new String();
78                 mergedHistory = new HashMap<String, Integer>();
79                 enRelatedNotesCache = new HashMap<String, List<String>>();
80                 this.enRelatedNotesRunner = new ENRelatedNotesRunner(this.syncRunner, logger);
81                 this.enRelatedNotesRunner.enRelatedNotesSignal.getENRelatedNotesFinished.connect(this, "enRelatedNotesComplete()");
82                 this.enRelatedNotesThread = new QThread(enRelatedNotesRunner, "ENRelatedNotes Thread");
83                 this.getEnRelatedNotesThread().start();
84                 
85                 rensoNoteListItems = new HashMap<QListWidgetItem, String>();
86                 rensoNoteListTrueItems = new ArrayList<RensoNoteListItem>();
87                 
88                 this.itemPressed.connect(this, "rensoNoteItemPressed(QListWidgetItem)");
89                 
90                 // コンテキストメニュー作成
91                 menu = new QMenu(this);
92                 // 新しいタブで開くアクション生成
93                 openNewTabAction = new QAction(tr("Open in New Tab"), this);
94                 openNewTabAction.setToolTip(tr("Open this note in new tab"));
95                 openNewTabAction.triggered.connect(parent, "openNewTabFromRNL()");
96                 // スターをつけるアクション生成
97                 starAction = new QAction(tr("Add Star"), this);
98                 starAction.setToolTip(tr("Add Star to this item"));
99                 starAction.triggered.connect(parent, "starNote()");
100                 // スターを外すアクション生成
101                 unstarAction = new QAction(tr("Remove Star"), this);
102                 unstarAction.setToolTip(tr("Remove Star from this item"));
103                 unstarAction.triggered.connect(parent, "unstarNote()");
104                 // このノートを除外するアクション生成
105                 excludeNoteAction = new QAction(tr("Exclude"), this);
106                 excludeNoteAction.setToolTip(tr("Exclude this note from RensoNoteList"));
107                 excludeNoteAction.triggered.connect(parent, "excludeNote()");
108                 // コンテキストメニューに登録
109                 menu.addAction(openNewTabAction);
110                 menu.addAction(excludeNoteAction);
111                 menu.aboutToHide.connect(this, "contextMenuHidden()");
112                 
113                 logger.log(logger.HIGH, "rensoNoteList setup complete");
114         }
115
116         // 連想ノートリストをリフレッシュ
117         public void refreshRensoNoteList(String guid) {
118                 logger.log(logger.HIGH, "Entering RensoNoteList.refreshRensoNoteList");
119
120                 this.clear();
121                 rensoNoteListItems.clear();
122                 rensoNoteListTrueItems.clear();
123                 mergedHistory = new HashMap<String, Integer>();
124
125                 if (!this.isEnabled()) {
126                         return;
127                 }
128                 if (guid == null || guid.equals("")) {
129                         return;
130                 }
131                 
132                 this.guid = guid;
133                 // すでにEvernote関連ノートがキャッシュされているか確認
134                 boolean isCached;
135                 isCached = enRelatedNotesCache.containsKey(guid);
136                 if (!isCached) {        // キャッシュ無し
137                         // Evernoteの関連ノートを別スレッドで取得させる
138                         enRelatedNotesRunner.addGuid(guid);
139                 } else {                        // キャッシュ有り
140                         List<String> relatedNoteGuids = enRelatedNotesCache.get(guid);
141                         addENRelatedNotes(relatedNoteGuids);
142                 }
143                 
144                 calculateHistory(guid);
145                 repaintRensoNoteList(false);
146
147                 logger.log(logger.HIGH, "Leaving RensoNoteList.refreshRensoNoteList");
148         }
149         
150         // 操作履歴をデータベースから取得してノートごとの関連度を算出、その後mergedHistoryに追加
151         private void calculateHistory(String guid) {
152                 // browseHistory<guid, 回数(ポイント)>
153                 HashMap<String, Integer> browseHistory = conn.getHistoryTable().getBehaviorHistory("browse", guid);
154                 addWeight(browseHistory, Global.getBrowseWeight());
155                 mergedHistory = mergeHistory(browseHistory, mergedHistory);
156                 
157                 // copy&pasteHistory<guid, 回数(ポイント)>
158                 HashMap<String, Integer> copyAndPasteHistory = conn.getHistoryTable().getBehaviorHistory("copy & paste", guid);
159                 addWeight(copyAndPasteHistory, Global.getCopyPasteWeight());
160                 mergedHistory = mergeHistory(copyAndPasteHistory, mergedHistory);
161                 
162                 // addNewNoteHistory<guid, 回数(ポイント)>
163                 HashMap<String, Integer> addNewNoteHistory = conn.getHistoryTable().getBehaviorHistory("addNewNote", guid);
164                 addWeight(addNewNoteHistory, Global.getAddNewNoteWeight());
165                 mergedHistory = mergeHistory(addNewNoteHistory, mergedHistory);
166                 
167                 // rensoItemClickHistory<guid, 回数(ポイント)>
168                 HashMap<String, Integer> rensoItemClickHistory = conn.getHistoryTable().getBehaviorHistory("rensoItemClick", guid);
169                 addWeight(rensoItemClickHistory, Global.getRensoItemClickWeight());
170                 mergedHistory = mergeHistory(rensoItemClickHistory, mergedHistory);
171                 
172                 // sameTagHistory<guid, 回数(ポイント)>
173                 HashMap<String, Integer> sameTagHistory = conn.getHistoryTable().getBehaviorHistory("sameTag", guid);
174                 addWeight(sameTagHistory, Global.getSameTagWeight());
175                 mergedHistory = mergeHistory(sameTagHistory, mergedHistory);
176                 
177                 // sameNotebookNoteHistory<guid, 回数(ポイント)>
178                 HashMap<String, Integer> sameNotebookHistory = conn.getHistoryTable().getBehaviorHistory("sameNotebook", guid);
179                 addWeight(sameNotebookHistory, Global.getSameNotebookWeight());
180                 mergedHistory = mergeHistory(sameNotebookHistory, mergedHistory);
181         }
182         
183         // 操作回数に重み付けする
184         private void addWeight(HashMap<String, Integer> history, int weight){
185                 Set<String> keySet = history.keySet();
186                 Iterator<String> hist_iterator = keySet.iterator();
187                 while(hist_iterator.hasNext()){
188                         String key = hist_iterator.next();
189                         history.put(key, history.get(key) * weight);
190                 }
191         }
192         
193         // 連想ノートリストを再描画
194         private void repaintRensoNoteList(boolean needClear) {
195                 if (needClear) {
196                         this.clear();
197                         rensoNoteListItems.clear();
198                         rensoNoteListTrueItems.clear();
199                 }
200                 
201                 if (!this.isEnabled()) {
202                         return;
203                 }
204                 
205                 // すべての関連ポイントの合計を取得(関連度のパーセント算出に利用)
206                 allPointSum = 0;
207                 for (int p : mergedHistory.values()) {
208                         allPointSum += p;
209                 }
210                 
211                 addRensoNoteList(mergedHistory);
212         }
213         
214         // 引数1と引数2をマージしたハッシュマップを返す
215         private HashMap<String, Integer> mergeHistory(HashMap<String, Integer> History1, HashMap<String, Integer> History2){
216                 HashMap<String, Integer> mergedHistory = new HashMap<String, Integer>();
217                 
218                 mergedHistory.putAll(History1);
219                 
220                 Set<String> keySet = History2.keySet();
221                 Iterator<String> hist2_iterator = keySet.iterator();
222                 while(hist2_iterator.hasNext()){
223                         String key = hist2_iterator.next();
224                         if(mergedHistory.containsKey(key)){
225                                 mergedHistory.put(key, mergedHistory.get(key) + History2.get(key));
226                         }else {
227                                 mergedHistory.put(key, History2.get(key));
228                         }
229                 }
230
231                 return mergedHistory;
232         }
233         
234         // 連想ノートリストにハッシュマップのデータを追加
235         private void addRensoNoteList(HashMap<String, Integer> History){
236                 String currentNoteGuid = new String(parent.getCurrentNoteGuid());
237                 
238                 // スター付きノートとスター無しノートを分ける
239                 HashMap<String, Integer> staredNotes = new HashMap<String, Integer>();  // スター付きノートのマップ
240                 HashMap<String, Integer> normalNotes = new HashMap<String, Integer>();  // スター無しノートのマップ
241                 for (String nextGuid: History.keySet()) {
242                         int relationPoint = History.get(nextGuid);
243                         boolean isStared = conn.getStaredTable().existNote(currentNoteGuid, nextGuid);
244                         if (isStared) {
245                                 staredNotes.put(nextGuid, relationPoint);
246                         } else {
247                                 normalNotes.put(nextGuid, relationPoint);
248                         }
249                 }
250                 
251                 // 連想ノートリストアイテムの最大表示数まで繰り返す
252                 for (int i = 0; i < Global.getRensoListItemMaximum(); i++) {
253                         // スター付きノートがあれば先に処理する
254                         HashMap<String, Integer> tmpMap = new HashMap<String, Integer>();
255                         if (!staredNotes.isEmpty()) {
256                                 tmpMap = staredNotes;
257                         }else if (!normalNotes.isEmpty()) {
258                                 tmpMap = normalNotes;
259                         }
260                         
261                         // 操作回数が多い順に取り出して連想ノートリストに追加する
262                         if (!tmpMap.isEmpty()) {
263                                 int maxNum = -1;
264                                 String maxGuid = new String();
265                                 
266                                 for (String nextGuid: tmpMap.keySet()) {
267                                         int relationPoint = tmpMap.get(nextGuid);
268                                         
269                                         // 最大ノート探索する
270                                         if (relationPoint > maxNum) {
271                                                 maxNum = relationPoint;
272                                                 maxGuid = nextGuid;
273                                         }
274                                 }
275                                 
276                                 // 次の最大値探索で邪魔なので最大値をHashMapから削除
277                                 tmpMap.remove(maxGuid);
278         
279                                 // 関連度最大のノートがアクティブか確認
280                                 Note maxNote = conn.getNoteTable().getNote(maxGuid, true, false, false, false, true);
281                                 boolean isNoteActive = false;
282                                 if(maxNote != null) {
283                                         isNoteActive = maxNote.isActive();
284                                 }
285                                 
286                                 // 存在していて、かつ関連度0でなければノート情報を取得して連想ノートリストに追加
287                                 if (isNoteActive && maxNum > 0) {
288                                         // スター付きか確認
289                                         boolean isStared;
290                                         isStared = conn.getStaredTable().existNote(currentNoteGuid, maxGuid);
291                                         
292                                         QListWidgetItem item = new QListWidgetItem();
293                                         RensoNoteListItem myItem = new RensoNoteListItem(maxNote, maxNum, isStared, allPointSum, conn, this);
294                                         item.setSizeHint(new QSize(0, 90));
295                                         this.addItem(item);
296                                         this.setItemWidget(item, myItem);
297                                         rensoNoteListItems.put(item, maxGuid);
298                                         rensoNoteListTrueItems.add(myItem);
299                                 } else {
300                                         break;
301                                 }
302                         }
303                 }
304         }
305
306         // リストのアイテムから対象ノートのguidを取得
307         public String getNoteGuid(QListWidgetItem item) {
308                 return rensoNoteListItems.get(item);
309         }
310         
311         // 関連ノートリストの右クリックメニュー
312         @Override
313         public void contextMenuEvent(QContextMenuEvent event){
314                 if (rensoNotePressedItemGuid == null || rensoNotePressedItemGuid.equals("")) {
315                         return;
316                 }
317                 
318                 // STAR, UNSTARがあれば、一度消す
319                 List<QAction> menuActions = new ArrayList<QAction>(menu.actions());
320                 if (menuActions.contains(starAction)) {
321                         menu.removeAction(starAction);
322                 }
323                 if (menuActions.contains(unstarAction)) {
324                         menu.removeAction(unstarAction);
325                 }
326                 
327                 // 対象アイテムがスター付きなら「UNSTAR」、スター無しなら「STAR」を追加
328                 String currentNoteGuid = parent.getCurrentNoteGuid();
329                 boolean isExist = conn.getStaredTable().existNote(currentNoteGuid, rensoNotePressedItemGuid);
330                 if (isExist) {
331                         menu.insertAction(excludeNoteAction, unstarAction);
332                 } else {
333                         menu.insertAction(excludeNoteAction, starAction);
334                 }
335                 
336                 // コンテキストメニューを表示
337                 menu.exec(event.globalPos());
338                 
339                 rensoNotePressedItemGuid = null;
340         }
341         
342         // コンテキストメニューが表示されているかどうか
343         public boolean isContextMenuVisible() {
344                 return menu.isVisible();
345         }
346         
347         // コンテキストメニューが閉じられた時
348         @SuppressWarnings("unused")
349         private void contextMenuHidden() {
350                 for (int i = 0; i < rensoNoteListTrueItems.size(); i++) {
351                         RensoNoteListItem item = rensoNoteListTrueItems.get(i);
352                         item.setDefaultBackground();
353                 }
354         }
355         
356         // ユーザが連想ノートリストのアイテムを選択した時の処理
357         @SuppressWarnings("unused")
358         private void rensoNoteItemPressed(QListWidgetItem current) {
359                 rensoNotePressedItemGuid = null;
360                 // 右クリックだったときの処理
361                 if (QApplication.mouseButtons().isSet(MouseButton.RightButton)) {
362                         rensoNotePressedItemGuid = getNoteGuid(current);
363                 }
364         }
365         
366         // Evernoteの関連ノートの取得が完了
367         @SuppressWarnings("unused")
368         private void enRelatedNotesComplete() {
369                 Pair<String, List<String>> enRelatedNoteGuidPair = enRelatedNotesRunner.getENRelatedNoteGuids();        // <元ノートguid, 関連ノートguidリスト>
370                 
371                 if (enRelatedNoteGuidPair == null) {
372                         return;
373                 }
374                 
375                 String sourceGuid = enRelatedNoteGuidPair.getFirst();
376                 List<String> enRelatedNoteGuids = enRelatedNoteGuidPair.getSecond();
377                 
378                 
379                 if (sourceGuid != null && !sourceGuid.equals("") && enRelatedNoteGuids != null) {       // Evernote関連ノートがnullでなければ
380                         // まずキャッシュに追加
381                         enRelatedNotesCache.put(sourceGuid, enRelatedNoteGuids);
382                         
383                         if (!enRelatedNoteGuids.isEmpty()) {    // Evernote関連ノートが存在していて
384                                 if (sourceGuid.equals(this.guid)) {     // 取得したデータが今開いているノートの関連ノートなら
385                                         // mergedHistoryにEvernote関連ノートを追加してから再描画
386                                         addENRelatedNotes(enRelatedNoteGuids);
387                                         repaintRensoNoteList(true);
388                                 }
389                         }
390                 }
391         }
392         
393         // Evernote関連ノートの関連度情報をmergedHistoryに追加
394         private void addENRelatedNotes(List<String> relatedNoteGuids) {
395                 // Evernote関連ノート<guid, 関連ポイント>
396                 HashMap<String, Integer> enRelatedNotes = new HashMap<String, Integer>();
397                 
398                 for (String relatedGuid : relatedNoteGuids) {
399                         enRelatedNotes.put(relatedGuid, Global.getENRelatedNotesWeight());
400                 }
401                 
402                 mergedHistory = mergeHistory(enRelatedNotes, mergedHistory);
403         }
404         
405         // Evernoteの関連ノート取得スレッドを終了させる
406         public boolean stopThread() {
407                 if (enRelatedNotesRunner.addStop()) {
408                         return true;
409                 }
410                 return false;
411         }
412
413         public QThread getEnRelatedNotesThread() {
414                 return enRelatedNotesThread;
415         }
416 }