JAL-2792 JAL-3187 linked features (if shown) in Feature details submenu
[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.AlignmentAnnotation;
24 import jalview.datamodel.Sequence;
25 import jalview.datamodel.SequenceGroup;
26 import jalview.datamodel.SequenceI;
27 import jalview.gui.SeqPanel.MousePos;
28 import jalview.io.SequenceAnnotationReport;
29 import jalview.util.MessageManager;
30 import jalview.util.Platform;
31 import jalview.viewmodel.AlignmentViewport;
32 import jalview.viewmodel.ViewportRanges;
33
34 import java.awt.BorderLayout;
35 import java.awt.event.MouseEvent;
36 import java.awt.event.MouseListener;
37 import java.awt.event.MouseMotionListener;
38 import java.awt.event.MouseWheelEvent;
39 import java.awt.event.MouseWheelListener;
40 import java.util.List;
41
42 import javax.swing.JPanel;
43 import javax.swing.JPopupMenu;
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
55         implements MouseListener, 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    * Responds to mouse movement by setting tooltip text for the sequence id
99    * under the mouse (or possibly annotation label, when in wrapped mode)
100    * 
101    * @param e
102    */
103   @Override
104   public void mouseMoved(MouseEvent e)
105   {
106     SeqPanel sp = alignPanel.getSeqPanel();
107     MousePos pos = sp.findMousePosition(e);
108     if (pos.isOverAnnotation())
109     {
110       /*
111        * mouse is over an annotation label in wrapped mode
112        */
113       AlignmentAnnotation[] anns = av.getAlignment()
114               .getAlignmentAnnotation();
115       AlignmentAnnotation annotation = anns[pos.annotationIndex];
116       setToolTipText(AnnotationLabels.getTooltip(annotation));
117       alignPanel.alignFrame.setStatus(
118               AnnotationLabels.getStatusMessage(annotation, anns));
119     }
120     else
121     {
122       int seq = Math.max(0, pos.seqIndex);
123       if (seq < av.getAlignment().getHeight())
124       {
125         SequenceI sequence = av.getAlignment().getSequenceAt(seq);
126         StringBuilder tip = new StringBuilder(64);
127         tip.append(sequence.getDisplayId(true)).append(" ");
128         seqAnnotReport.createTooltipAnnotationReport(tip, sequence,
129                 av.isShowDBRefs(), av.isShowNPFeats(), sp.seqCanvas.fr);
130         setToolTipText(JvSwingUtils.wrapTooltip(true, tip.toString()));
131
132         StringBuilder text = new StringBuilder();
133         text.append("Sequence ").append(String.valueOf(seq + 1))
134                 .append(" ID: ")
135                 .append(sequence.getName());
136         alignPanel.alignFrame.setStatus(text.toString());
137       }
138     }
139   }
140
141   /**
142    * Responds to a mouse drag by selecting the sequences under the dragged
143    * region.
144    * 
145    * @param e
146    */
147   @Override
148   public void mouseDragged(MouseEvent e)
149   {
150     mouseDragging = true;
151
152     MousePos pos = alignPanel.getSeqPanel().findMousePosition(e);
153     if (pos.isOverAnnotation())
154     {
155       // mouse is over annotation label in wrapped mode
156       return;
157     }
158
159     int seq = Math.max(0, pos.seqIndex);
160
161     if (seq < lastid)
162     {
163       selectSeqs(lastid - 1, seq);
164     }
165     else if (seq > lastid)
166     {
167       selectSeqs(lastid + 1, seq);
168     }
169
170     lastid = seq;
171     alignPanel.paintAlignment(false, false);
172   }
173
174   /**
175    * Response to the mouse wheel by scrolling the alignment panel.
176    */
177   @Override
178   public void mouseWheelMoved(MouseWheelEvent e)
179   {
180     e.consume();
181     double wheelRotation = e.getPreciseWheelRotation();
182     if (wheelRotation > 0)
183     {
184       if (e.isShiftDown())
185       {
186         av.getRanges().scrollRight(true);
187       }
188       else
189       {
190         av.getRanges().scrollUp(false);
191       }
192     }
193     else if (wheelRotation < 0)
194     {
195       if (e.isShiftDown())
196       {
197         av.getRanges().scrollRight(false);
198       }
199       else
200       {
201         av.getRanges().scrollUp(true);
202       }
203     }
204   }
205
206   /**
207    * Handle a mouse click event. Currently only responds to a double-click. The
208    * action is to try to open a browser window at a URL that searches for the
209    * selected sequence id. The search URL is configured in Preferences |
210    * Connections | URL link from Sequence ID. For example:
211    * 
212    * http://www.ebi.ac.uk/ebisearch/search.ebi?db=allebi&query=$SEQUENCE_ID$
213    * 
214    * @param e
215    */
216   @Override
217   public void mouseClicked(MouseEvent e)
218   {
219     /*
220      * Ignore single click. Ignore 'left' click followed by 'right' click (user
221      * selects a row then its pop-up menu).
222      */
223     if (e.getClickCount() < 2 || SwingUtilities.isRightMouseButton(e))
224     {
225       // reinstate isRightMouseButton check to ignore mouse-related popup events
226       // note - this does nothing on default MacBookPro force-trackpad config!
227       return;
228     }
229
230     MousePos pos = alignPanel.getSeqPanel().findMousePosition(e);
231     int seq = pos.seqIndex;
232     if (pos.isOverAnnotation() || seq < 0)
233     {
234       return;
235     }
236
237     String id = av.getAlignment().getSequenceAt(seq).getName();
238     String url = Preferences.sequenceUrlLinks.getPrimaryUrl(id);
239
240     try
241     {
242       jalview.util.BrowserLauncher.openURL(url);
243     } catch (Exception ex)
244     {
245       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
246               MessageManager.getString("label.web_browser_not_found_unix"),
247               MessageManager.getString("label.web_browser_not_found"),
248               JvOptionPane.WARNING_MESSAGE);
249       ex.printStackTrace();
250     }
251   }
252
253   /**
254    * DOCUMENT ME!
255    * 
256    * @param e
257    *          DOCUMENT ME!
258    */
259   @Override
260   public void mouseEntered(MouseEvent e)
261   {
262     if (scrollThread != null)
263     {
264       scrollThread.stopScrolling();
265     }
266   }
267
268   /**
269    * DOCUMENT ME!
270    * 
271    * @param e
272    *          DOCUMENT ME!
273    */
274   @Override
275   public void mouseExited(MouseEvent e)
276   {
277     if (av.getWrapAlignment())
278     {
279       return;
280     }
281
282     if (mouseDragging && (e.getY() < 0)
283             && (av.getRanges().getStartSeq() > 0))
284     {
285       scrollThread = new ScrollThread(true);
286     }
287
288     if (mouseDragging && (e.getY() >= getHeight())
289             && (av.getAlignment().getHeight() > av.getRanges().getEndSeq()))
290     {
291       scrollThread = new ScrollThread(false);
292     }
293   }
294
295   /**
296    * Respond to a mouse press. Does nothing for (left) double-click as this is
297    * handled by mouseClicked().
298    * 
299    * Right mouse down - construct and show context menu.
300    * 
301    * Ctrl-down or Shift-down - add to or expand current selection group if there
302    * is one.
303    * 
304    * Mouse down - select this sequence.
305    * 
306    * @param e
307    */
308   @Override
309   public void mousePressed(MouseEvent e)
310   {
311     if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e))
312     {
313       return;
314     }
315
316     MousePos pos = alignPanel.getSeqPanel().findMousePosition(e);
317     
318     if (e.isPopupTrigger()) // Mac reports this in mousePressed
319     {
320       showPopupMenu(e, pos);
321       return;
322     }
323
324     /*
325      * defer right-mouse click handling to mouseReleased on Windows
326      * (where isPopupTrigger() will answer true)
327      * NB isRightMouseButton is also true for Cmd-click on Mac
328      */
329     if (SwingUtilities.isRightMouseButton(e) && !Platform.isAMac())
330     {
331       return;
332     }
333
334     if ((av.getSelectionGroup() == null)
335             || (!jalview.util.Platform.isControlDown(e) && !e.isShiftDown()
336                     && av.getSelectionGroup() != null))
337     {
338       av.setSelectionGroup(new SequenceGroup());
339       av.getSelectionGroup().setStartRes(0);
340       av.getSelectionGroup().setEndRes(av.getAlignment().getWidth() - 1);
341     }
342
343     if (e.isShiftDown() && (lastid != -1))
344     {
345       selectSeqs(lastid, pos.seqIndex);
346     }
347     else
348     {
349       selectSeq(pos.seqIndex);
350     }
351
352     av.isSelectionGroupChanged(true);
353
354     alignPanel.paintAlignment(false, false);
355   }
356
357   /**
358    * Build and show the popup-menu at the right-click mouse position
359    * 
360    * @param e
361    */
362   void showPopupMenu(MouseEvent e, MousePos pos)
363   {
364     if (pos.isOverAnnotation())
365     {
366       showAnnotationMenu(e, pos);
367       return;
368     }
369
370     Sequence sq = (Sequence) av.getAlignment().getSequenceAt(pos.seqIndex);
371     if (sq != null)
372     {
373       PopupMenu pop = new PopupMenu(alignPanel, sq,
374               Preferences.getGroupURLLinks());
375       pop.show(this, e.getX(), e.getY());
376     }
377   }
378
379   /**
380    * On right mouse click on a Consensus annotation label, shows a limited popup
381    * menu, with options to configure the consensus calculation and rendering.
382    * 
383    * @param e
384    * @param pos
385    * @see AnnotationLabels#showPopupMenu(MouseEvent)
386    */
387   void showAnnotationMenu(MouseEvent e, MousePos pos)
388   {
389     if (pos.annotationIndex == -1)
390     {
391       return;
392     }
393     AlignmentAnnotation[] anns = this.av.getAlignment()
394             .getAlignmentAnnotation();
395     if (anns == null || pos.annotationIndex >= anns.length)
396     {
397       return;
398     }
399     AlignmentAnnotation ann = anns[pos.annotationIndex];
400     if (!ann.label.contains("Consensus"))
401     {
402       return;
403     }
404
405     JPopupMenu pop = new JPopupMenu(
406             MessageManager.getString("label.annotations"));
407     AnnotationLabels.addConsensusMenuOptions(this.alignPanel, ann, pop);
408     pop.show(this, e.getX(), e.getY());
409   }
410
411   /**
412    * Toggle whether the sequence is part of the current selection group.
413    * 
414    * @param seq
415    */
416   void selectSeq(int seq)
417   {
418     lastid = seq;
419
420     SequenceI pickedSeq = av.getAlignment().getSequenceAt(seq);
421     av.getSelectionGroup().addOrRemove(pickedSeq, false);
422   }
423
424   /**
425    * Add contiguous rows of the alignment to the current selection group. Does
426    * nothing if there is no selection group.
427    * 
428    * @param start
429    * @param end
430    */
431   void selectSeqs(int start, int end)
432   {
433     if (av.getSelectionGroup() == null)
434     {
435       return;
436     }
437
438     if (end >= av.getAlignment().getHeight())
439     {
440       end = av.getAlignment().getHeight() - 1;
441     }
442
443     lastid = start;
444
445     if (end < start)
446     {
447       int tmp = start;
448       start = end;
449       end = tmp;
450       lastid = end;
451     }
452
453     for (int i = start; i <= end; i++)
454     {
455       av.getSelectionGroup().addSequence(av.getAlignment().getSequenceAt(i),
456               false);
457     }
458   }
459
460   /**
461    * Respond to mouse released. Refreshes the display and triggers broadcast of
462    * the new selection group to any listeners.
463    * 
464    * @param e
465    */
466   @Override
467   public void mouseReleased(MouseEvent e)
468   {
469     if (scrollThread != null)
470     {
471       scrollThread.stopScrolling();
472     }
473     MousePos pos = alignPanel.getSeqPanel().findMousePosition(e);
474
475     mouseDragging = false;
476     PaintRefresher.Refresh(this, av.getSequenceSetId());
477     // always send selection message when mouse is released
478     av.sendSelection();
479
480     if (e.isPopupTrigger()) // Windows reports this in mouseReleased
481     {
482       showPopupMenu(e, pos);
483     }
484   }
485
486   /**
487    * Highlight sequence ids that match the given list, and if necessary scroll
488    * to the start sequence of the list.
489    * 
490    * @param list
491    */
492   public void highlightSearchResults(List<SequenceI> list)
493   {
494     getIdCanvas().setHighlighted(list);
495
496     if (list == null || list.isEmpty())
497     {
498       return;
499     }
500
501     int index = av.getAlignment().findIndex(list.get(0));
502
503     // do we need to scroll the panel?
504     if ((av.getRanges().getStartSeq() > index)
505             || (av.getRanges().getEndSeq() < index))
506     {
507       av.getRanges().setStartSeq(index);
508     }
509   }
510
511   public IdCanvas getIdCanvas()
512   {
513     return idCanvas;
514   }
515
516   public void setIdCanvas(IdCanvas idCanvas)
517   {
518     this.idCanvas = idCanvas;
519   }
520
521   /**
522    * Performs scrolling of the visible alignment up or down, adding newly
523    * visible sequences to the current selection
524    */
525   class ScrollThread extends Thread
526   {
527     private boolean running = false;
528
529     private boolean up;
530
531     /**
532      * Constructor for a thread that scrolls either up or down
533      * 
534      * @param up
535      */
536     public ScrollThread(boolean up)
537     {
538       this.up = up;
539       setName("IdPanel$ScrollThread$" + String.valueOf(up));
540       start();
541     }
542
543     /**
544      * Sets a flag to stop the scrolling
545      */
546     public void stopScrolling()
547     {
548       running = false;
549     }
550
551     /**
552      * Scrolls the alignment either up or down, one row at a time, adding newly
553      * visible sequences to the current selection. Speed is limited to a maximum
554      * of ten rows per second. The thread exits when the end of the alignment is
555      * reached or a flag is set to stop it.
556      */
557     @Override
558     public void run()
559     {
560       running = true;
561
562       while (running)
563       {
564         ViewportRanges ranges = IdPanel.this.av.getRanges();
565         if (ranges.scrollUp(up))
566         {
567           int toSeq = up ? ranges.getStartSeq() : ranges.getEndSeq();
568           int fromSeq = toSeq < lastid ? lastid - 1 : lastid + 1;
569           IdPanel.this.selectSeqs(fromSeq, toSeq);
570
571           lastid = toSeq;
572         }
573         else
574         {
575           /*
576            * scroll did nothing - reached limit of visible alignment
577            */
578           running = false;
579         }
580
581         alignPanel.paintAlignment(false, false);
582
583         try
584         {
585           Thread.sleep(100);
586         } catch (Exception ex)
587         {
588         }
589       }
590     }
591   }
592 }