JAL-2282 Force double-clicking to use sequence_id cases and not accession_id
[jalview.git] / src / jalview / gui / IdPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.datamodel.Sequence;
24 import jalview.datamodel.SequenceFeature;
25 import jalview.datamodel.SequenceGroup;
26 import jalview.datamodel.SequenceI;
27 import jalview.io.SequenceAnnotationReport;
28 import jalview.util.MessageManager;
29 import jalview.util.Platform;
30 import jalview.util.UrlLink;
31 import jalview.viewmodel.AlignmentViewport;
32
33 import java.awt.BorderLayout;
34 import java.awt.event.MouseEvent;
35 import java.awt.event.MouseListener;
36 import java.awt.event.MouseMotionListener;
37 import java.awt.event.MouseWheelEvent;
38 import java.awt.event.MouseWheelListener;
39 import java.util.List;
40 import java.util.Vector;
41
42 import javax.swing.JOptionPane;
43 import javax.swing.JPanel;
44 import javax.swing.SwingUtilities;
45 import javax.swing.ToolTipManager;
46
47 /**
48  * This panel hosts alignment sequence ids and responds to mouse clicks on them,
49  * as well as highlighting ids matched by a search from the Find menu.
50  * 
51  * @author $author$
52  * @version $Revision$
53  */
54 public class IdPanel extends JPanel implements MouseListener,
55         MouseMotionListener, MouseWheelListener
56 {
57   private IdCanvas idCanvas;
58
59   protected AlignmentViewport av;
60
61   protected AlignmentPanel alignPanel;
62
63   ScrollThread scrollThread = null;
64
65   String linkImageURL;
66
67   int offy;
68
69   // int width;
70   int lastid = -1;
71
72   boolean mouseDragging = false;
73
74   private final SequenceAnnotationReport seqAnnotReport;
75
76   /**
77    * Creates a new IdPanel object.
78    * 
79    * @param av
80    * @param parent
81    */
82   public IdPanel(AlignViewport av, AlignmentPanel parent)
83   {
84     this.av = av;
85     alignPanel = parent;
86     setIdCanvas(new IdCanvas(av));
87     linkImageURL = getClass().getResource("/images/link.gif").toString();
88     seqAnnotReport = new SequenceAnnotationReport(linkImageURL);
89     setLayout(new BorderLayout());
90     add(getIdCanvas(), BorderLayout.CENTER);
91     addMouseListener(this);
92     addMouseMotionListener(this);
93     addMouseWheelListener(this);
94     ToolTipManager.sharedInstance().registerComponent(this);
95   }
96
97   /**
98    * Respond to mouse movement by constructing tooltip text for the sequence id
99    * under the mouse.
100    * 
101    * @param e
102    *          DOCUMENT ME!
103    */
104   @Override
105   public void mouseMoved(MouseEvent e)
106   {
107     SeqPanel sp = alignPanel.getSeqPanel();
108     int seq = Math.max(0, sp.findSeq(e));
109     if (seq > -1 && seq < av.getAlignment().getHeight())
110     {
111       SequenceI sequence = av.getAlignment().getSequenceAt(seq);
112       StringBuffer tip = new StringBuffer(64);
113       seqAnnotReport.createSequenceAnnotationReport(tip, sequence,
114               av.isShowDBRefs(), av.isShowNPFeats(),
115               sp.seqCanvas.fr.getMinMax());
116       setToolTipText(JvSwingUtils.wrapTooltip(true,
117               sequence.getDisplayId(true) + " " + tip.toString()));
118     }
119   }
120
121   /**
122    * Responds to a mouse drag by selecting the sequences under the dragged
123    * region.
124    * 
125    * @param e
126    */
127   @Override
128   public void mouseDragged(MouseEvent e)
129   {
130     mouseDragging = true;
131
132     int seq = Math.max(0, alignPanel.getSeqPanel().findSeq(e));
133
134     if (seq < lastid)
135     {
136       selectSeqs(lastid - 1, seq);
137     }
138     else if (seq > lastid)
139     {
140       selectSeqs(lastid + 1, seq);
141     }
142
143     lastid = seq;
144     alignPanel.paintAlignment(true);
145   }
146
147   /**
148    * Response to the mouse wheel by scrolling the alignment panel.
149    */
150   @Override
151   public void mouseWheelMoved(MouseWheelEvent e)
152   {
153     e.consume();
154     if (e.getWheelRotation() > 0)
155     {
156       if (e.isShiftDown())
157       {
158         alignPanel.scrollRight(true);
159       }
160       else
161       {
162         alignPanel.scrollUp(false);
163       }
164     }
165     else
166     {
167       if (e.isShiftDown())
168       {
169         alignPanel.scrollRight(false);
170       }
171       else
172       {
173         alignPanel.scrollUp(true);
174       }
175     }
176   }
177
178   /**
179    * Handle a mouse click event. Currently only responds to a double-click. The
180    * action is to try to open a browser window at a URL that searches for the
181    * selected sequence id. The search URL is configured in Preferences |
182    * Connections | URL link from Sequence ID. For example:
183    * 
184    * http://www.ebi.ac.uk/ebisearch/search.ebi?db=allebi&query=$SEQUENCE_ID$
185    * 
186    * @param e
187    */
188   @Override
189   public void mouseClicked(MouseEvent e)
190   {
191     /*
192      * Ignore single click. Ignore 'left' click followed by 'right' click (user
193      * selects a row then its pop-up menu).
194      */
195     if (e.getClickCount() < 2 || SwingUtilities.isRightMouseButton(e))
196     {
197       // reinstate isRightMouseButton check to ignore mouse-related popup events
198       // note - this does nothing on default MacBookPro force-trackpad config!
199       return;
200     }
201
202     Vector links = Preferences.sequenceURLLinks;
203     if (links == null || links.size() < 1)
204     {
205       return;
206     }
207
208     int seq = alignPanel.getSeqPanel().findSeq(e);
209     String url = null;
210     int i = 0;
211     String id = av.getAlignment().getSequenceAt(seq).getName();
212     while (url == null && i < links.size())
213     {
214       // DEFAULT LINK IS FIRST IN THE LINK LIST
215       // BUT IF ITS A REGEX AND DOES NOT MATCH THE NEXT ONE WILL BE TRIED
216       url = links.elementAt(i++).toString();
217       jalview.util.UrlLink urlLink = null;
218       try
219       {
220         urlLink = new UrlLink(url);
221       } catch (Exception foo)
222       {
223         jalview.bin.Cache.log.error("Exception for URLLink '" + url + "'",
224                 foo);
225         url = null;
226         continue;
227       }
228       ;
229
230       if (urlLink.usesSeqId())
231       {
232         // this URL requires an accession id, not the name of a sequence
233         url = null;
234         continue;
235       }
236
237       if (!urlLink.isValid())
238       {
239         jalview.bin.Cache.log.error(urlLink.getInvalidMessage());
240         url = null;
241         continue;
242       }
243
244       String urls[] = urlLink.makeUrls(id, true);
245       if (urls == null || urls[0] == null || urls[0].length() < 4)
246       {
247         url = null;
248         continue;
249       }
250       // just take first URL made from regex
251       url = urls[1];
252     }
253     try
254     {
255       jalview.util.BrowserLauncher.openURL(url);
256     } catch (Exception ex)
257     {
258       JOptionPane.showInternalMessageDialog(Desktop.desktop,
259               MessageManager.getString("label.web_browser_not_found_unix"),
260               MessageManager.getString("label.web_browser_not_found"),
261               JOptionPane.WARNING_MESSAGE);
262       ex.printStackTrace();
263     }
264   }
265
266   /**
267    * DOCUMENT ME!
268    * 
269    * @param e
270    *          DOCUMENT ME!
271    */
272   @Override
273   public void mouseEntered(MouseEvent e)
274   {
275     if (scrollThread != null)
276     {
277       scrollThread.running = false;
278     }
279   }
280
281   /**
282    * DOCUMENT ME!
283    * 
284    * @param e
285    *          DOCUMENT ME!
286    */
287   @Override
288   public void mouseExited(MouseEvent e)
289   {
290     if (av.getWrapAlignment())
291     {
292       return;
293     }
294
295     if (mouseDragging && (e.getY() < 0) && (av.getStartSeq() > 0))
296     {
297       scrollThread = new ScrollThread(true);
298     }
299
300     if (mouseDragging && (e.getY() >= getHeight())
301             && (av.getAlignment().getHeight() > av.getEndSeq()))
302     {
303       scrollThread = new ScrollThread(false);
304     }
305   }
306
307   /**
308    * Respond to a mouse press. Does nothing for (left) double-click as this is
309    * handled by mouseClicked().
310    * 
311    * Right mouse down - construct and show context menu.
312    * 
313    * Ctrl-down or Shift-down - add to or expand current selection group if there
314    * is one.
315    * 
316    * Mouse down - select this sequence.
317    * 
318    * @param e
319    */
320   @Override
321   public void mousePressed(MouseEvent e)
322   {
323     if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e))
324     {
325       return;
326     }
327
328     if (e.isPopupTrigger()) // Mac reports this in mousePressed
329     {
330       showPopupMenu(e);
331       return;
332     }
333
334     /*
335      * defer right-mouse click handling to mouseReleased on Windows
336      * (where isPopupTrigger() will answer true)
337      * NB isRightMouseButton is also true for Cmd-click on Mac
338      */
339     if (SwingUtilities.isRightMouseButton(e) && !Platform.isAMac())
340     {
341       return;
342     }
343
344     if ((av.getSelectionGroup() == null)
345             || (!jalview.util.Platform.isControlDown(e) && !e.isShiftDown() && av
346                     .getSelectionGroup() != null))
347     {
348       av.setSelectionGroup(new SequenceGroup());
349       av.getSelectionGroup().setStartRes(0);
350       av.getSelectionGroup().setEndRes(av.getAlignment().getWidth() - 1);
351     }
352
353     int seq = alignPanel.getSeqPanel().findSeq(e);
354     if (e.isShiftDown() && (lastid != -1))
355     {
356       selectSeqs(lastid, seq);
357     }
358     else
359     {
360       selectSeq(seq);
361     }
362
363     av.isSelectionGroupChanged(true);
364
365     alignPanel.paintAlignment(true);
366   }
367
368   /**
369    * Build and show the popup-menu at the right-click mouse position
370    * 
371    * @param e
372    */
373   void showPopupMenu(MouseEvent e)
374   {
375     int seq2 = alignPanel.getSeqPanel().findSeq(e);
376     Sequence sq = (Sequence) av.getAlignment().getSequenceAt(seq2);
377     // build a new links menu based on the current links + any non-positional
378     // features
379     Vector<String> nlinks = new Vector<String>(Preferences.sequenceURLLinks);
380     SequenceFeature sfs[] = sq == null ? null : sq.getSequenceFeatures();
381     if (sfs != null)
382     {
383       for (SequenceFeature sf : sfs)
384       {
385         if (sf.begin == sf.end && sf.begin == 0)
386         {
387           if (sf.links != null && sf.links.size() > 0)
388           {
389             for (int l = 0, lSize = sf.links.size(); l < lSize; l++)
390             {
391               nlinks.addElement(sf.links.elementAt(l));
392             }
393           }
394         }
395       }
396     }
397
398     PopupMenu pop = new PopupMenu(alignPanel, sq, nlinks,
399             Preferences.getGroupURLLinks());
400     pop.show(this, e.getX(), e.getY());
401   }
402
403   /**
404    * Toggle whether the sequence is part of the current selection group.
405    * 
406    * @param seq
407    */
408   void selectSeq(int seq)
409   {
410     lastid = seq;
411
412     SequenceI pickedSeq = av.getAlignment().getSequenceAt(seq);
413     av.getSelectionGroup().addOrRemove(pickedSeq, true);
414   }
415
416   /**
417    * Add contiguous rows of the alignment to the current selection group. Does
418    * nothing if there is no selection group.
419    * 
420    * @param start
421    * @param end
422    */
423   void selectSeqs(int start, int end)
424   {
425     if (av.getSelectionGroup() == null)
426     {
427       return;
428     }
429
430     if (end >= av.getAlignment().getHeight())
431     {
432       end = av.getAlignment().getHeight() - 1;
433     }
434
435     lastid = start;
436
437     if (end < start)
438     {
439       int tmp = start;
440       start = end;
441       end = tmp;
442       lastid = end;
443     }
444
445     for (int i = start; i <= end; i++)
446     {
447       av.getSelectionGroup().addSequence(
448               av.getAlignment().getSequenceAt(i), i == end);
449     }
450   }
451
452   /**
453    * Respond to mouse released. Refreshes the display and triggers broadcast of
454    * the new selection group to any listeners.
455    * 
456    * @param e
457    */
458   @Override
459   public void mouseReleased(MouseEvent e)
460   {
461     if (scrollThread != null)
462     {
463       scrollThread.running = false;
464     }
465
466     mouseDragging = false;
467     PaintRefresher.Refresh(this, av.getSequenceSetId());
468     // always send selection message when mouse is released
469     av.sendSelection();
470
471     if (e.isPopupTrigger()) // Windows reports this in mouseReleased
472     {
473       showPopupMenu(e);
474     }
475   }
476
477   /**
478    * Highlight sequence ids that match the given list, and if necessary scroll
479    * to the start sequence of the list.
480    * 
481    * @param list
482    */
483   public void highlightSearchResults(List<SequenceI> list)
484   {
485     getIdCanvas().setHighlighted(list);
486
487     if (list == null)
488     {
489       return;
490     }
491
492     int index = av.getAlignment().findIndex(list.get(0));
493
494     // do we need to scroll the panel?
495     if ((av.getStartSeq() > index) || (av.getEndSeq() < index))
496     {
497       alignPanel.setScrollValues(av.getStartRes(), index);
498     }
499   }
500
501   public IdCanvas getIdCanvas()
502   {
503     return idCanvas;
504   }
505
506   public void setIdCanvas(IdCanvas idCanvas)
507   {
508     this.idCanvas = idCanvas;
509   }
510
511   // this class allows scrolling off the bottom of the visible alignment
512   class ScrollThread extends Thread
513   {
514     boolean running = false;
515
516     boolean up = true;
517
518     public ScrollThread(boolean up)
519     {
520       this.up = up;
521       start();
522     }
523
524     public void stopScrolling()
525     {
526       running = false;
527     }
528
529     @Override
530     public void run()
531     {
532       running = true;
533
534       while (running)
535       {
536         if (alignPanel.scrollUp(up))
537         {
538           // scroll was ok, so add new sequence to selection
539           int seq = av.getStartSeq();
540
541           if (!up)
542           {
543             seq = av.getEndSeq();
544           }
545
546           if (seq < lastid)
547           {
548             selectSeqs(lastid - 1, seq);
549           }
550           else if (seq > lastid)
551           {
552             selectSeqs(lastid + 1, seq);
553           }
554
555           lastid = seq;
556         }
557         else
558         {
559           running = false;
560         }
561
562         alignPanel.paintAlignment(false);
563
564         try
565         {
566           Thread.sleep(100);
567         } catch (Exception ex)
568         {
569         }
570       }
571     }
572   }
573 }