4b5e9d432502be0539bfac32720696778122ca3e
[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 java.awt.BorderLayout;
24 import java.awt.event.ActionEvent;
25 import java.awt.event.ActionListener;
26 import java.awt.event.MouseEvent;
27 import java.awt.event.MouseListener;
28 import java.awt.event.MouseMotionListener;
29 import java.awt.event.MouseWheelEvent;
30 import java.awt.event.MouseWheelListener;
31 import java.util.List;
32
33 import javax.swing.JPanel;
34 import javax.swing.JPopupMenu;
35 import javax.swing.SwingUtilities;
36 import javax.swing.Timer;
37 import javax.swing.ToolTipManager;
38
39 import jalview.datamodel.AlignmentAnnotation;
40 import jalview.datamodel.Sequence;
41 import jalview.datamodel.SequenceGroup;
42 import jalview.datamodel.SequenceI;
43 import jalview.gui.SeqPanel.MousePos;
44 import jalview.io.SequenceAnnotationReport;
45 import jalview.util.MessageManager;
46 import jalview.util.Platform;
47 import jalview.viewmodel.AlignmentViewport;
48 import jalview.viewmodel.ViewportRanges;
49
50 /**
51  * This panel hosts alignment sequence ids and responds to mouse clicks on them,
52  * as well as highlighting ids matched by a search from the Find menu.
53  * 
54  * @author $author$
55  * @version $Revision$
56  */
57 public class IdPanel extends JPanel
58         implements MouseListener, MouseMotionListener, MouseWheelListener
59 {
60   private IdCanvas idCanvas;
61
62   protected AlignmentViewport av;
63
64   protected AlignmentPanel alignPanel;
65
66   ScrollThread scrollThread = null;
67
68   int offy;
69
70   // int width;
71   int lastid = -1;
72
73   boolean mouseDragging = false;
74
75   private final SequenceAnnotationReport seqAnnotReport;
76
77   /**
78    * Creates a new IdPanel object.
79    * 
80    * @param av
81    * @param parent
82    */
83   public IdPanel(AlignViewport av, AlignmentPanel parent)
84   {
85     this.av = av;
86     alignPanel = parent;
87     setIdCanvas(new IdCanvas(av));
88     seqAnnotReport = new SequenceAnnotationReport(true);
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    * On (re-)entering the panel, stop any scrolling
255    * 
256    * @param e
257    */
258   @Override
259   public void mouseEntered(MouseEvent e)
260   {
261     stopScrolling();
262   }
263
264   /**
265    * Interrupts the scroll thread if one is running
266    */
267   void stopScrolling()
268   {
269     if (scrollThread != null)
270     {
271       scrollThread.stopScrolling();
272       scrollThread = null;
273     }
274   }
275
276   /**
277    * DOCUMENT ME!
278    * 
279    * @param e
280    *          DOCUMENT ME!
281    */
282   @Override
283   public void mouseExited(MouseEvent e)
284   {
285     if (av.getWrapAlignment())
286     {
287       return;
288     }
289
290     if (mouseDragging)
291     {
292       /*
293        * on mouse drag above or below the panel, start 
294        * scrolling if there are more sequences to show
295        */
296       ViewportRanges ranges = av.getRanges();
297       if (e.getY() < 0 && ranges.getStartSeq() > 0)
298       {
299         startScrolling(true);
300       }
301       else if (e.getY() >= getHeight()
302               && ranges.getEndSeq() <= av.getAlignment().getHeight())
303       {
304         startScrolling(false);
305       }
306     }
307   }
308
309   /**
310    * Starts scrolling either up or down
311    * 
312    * @param up
313    */
314   void startScrolling(boolean up)
315   {
316     scrollThread = new ScrollThread(up);
317     if (Platform.isJS())
318     {
319       /*
320        * for JalviewJS using Swing Timer
321        */
322       Timer t = new Timer(20, new ActionListener()
323       {
324         @Override
325         public void actionPerformed(ActionEvent e)
326         {
327           if (scrollThread != null)
328           {
329             // if (!scrollOnce() {t.stop();}) gives compiler error :-(
330             scrollThread.scrollOnce();
331           }
332         }
333       });
334       t.addActionListener(new ActionListener()
335       {
336         @Override
337         public void actionPerformed(ActionEvent e)
338         {
339           if (scrollThread == null)
340           {
341             // IdPanel.stopScrolling called
342             t.stop();
343           }
344         }
345       });
346       t.start();
347     }
348     else
349     /**
350      * Java only
351      * 
352      * @j2sIgnore
353      */
354     {
355       scrollThread.start();
356     }
357   }
358
359   /**
360    * Respond to a mouse press. Does nothing for (left) double-click as this is
361    * handled by mouseClicked().
362    * 
363    * Right mouse down - construct and show context menu.
364    * 
365    * Ctrl-down or Shift-down - add to or expand current selection group if there
366    * is one.
367    * 
368    * Mouse down - select this sequence.
369    * 
370    * @param e
371    */
372   @Override
373   public void mousePressed(MouseEvent e)
374   {
375     if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e))
376     {
377       return;
378     }
379
380     MousePos pos = alignPanel.getSeqPanel().findMousePosition(e);
381     
382     if (e.isPopupTrigger()) // Mac reports this in mousePressed
383     {
384       showPopupMenu(e, pos);
385       return;
386     }
387
388     /*
389      * defer right-mouse click handling to mouseReleased on Windows
390      * (where isPopupTrigger() will answer true)
391      * NB isRightMouseButton is also true for Cmd-click on Mac
392      */
393     if (Platform.isWinRightButton(e))
394     {
395       return;
396     }
397
398     if ((av.getSelectionGroup() == null)
399             || (!jalview.util.Platform.isControlDown(e) && !e.isShiftDown()
400                     && av.getSelectionGroup() != null))
401     {
402       av.setSelectionGroup(new SequenceGroup());
403       av.getSelectionGroup().setStartRes(0);
404       av.getSelectionGroup().setEndRes(av.getAlignment().getWidth() - 1);
405     }
406
407     if (e.isShiftDown() && (lastid != -1))
408     {
409       selectSeqs(lastid, pos.seqIndex);
410     }
411     else
412     {
413       selectSeq(pos.seqIndex);
414     }
415
416     av.isSelectionGroupChanged(true);
417
418     alignPanel.paintAlignment(false, false);
419   }
420
421   /**
422    * Build and show the popup-menu at the right-click mouse position
423    * 
424    * @param e
425    */
426   void showPopupMenu(MouseEvent e, MousePos pos)
427   {
428     if (pos.isOverAnnotation())
429     {
430       showAnnotationMenu(e, pos);
431       return;
432     }
433
434     Sequence sq = (Sequence) av.getAlignment().getSequenceAt(pos.seqIndex);
435     if (sq != null)
436     {
437       PopupMenu pop = new PopupMenu(alignPanel, sq,
438               Preferences.getGroupURLLinks());
439       pop.show(this, e.getX(), e.getY());
440     }
441   }
442
443   /**
444    * On right mouse click on a Consensus annotation label, shows a limited popup
445    * menu, with options to configure the consensus calculation and rendering.
446    * 
447    * @param e
448    * @param pos
449    * @see AnnotationLabels#showPopupMenu(MouseEvent)
450    */
451   void showAnnotationMenu(MouseEvent e, MousePos pos)
452   {
453     if (pos.annotationIndex == -1)
454     {
455       return;
456     }
457     AlignmentAnnotation[] anns = this.av.getAlignment()
458             .getAlignmentAnnotation();
459     if (anns == null || pos.annotationIndex >= anns.length)
460     {
461       return;
462     }
463     AlignmentAnnotation ann = anns[pos.annotationIndex];
464     if (!ann.label.contains("Consensus"))
465     {
466       return;
467     }
468
469     JPopupMenu pop = new JPopupMenu(
470             MessageManager.getString("label.annotations"));
471     AnnotationLabels.addConsensusMenuOptions(this.alignPanel, ann, pop);
472     pop.show(this, e.getX(), e.getY());
473   }
474
475   /**
476    * Toggle whether the sequence is part of the current selection group.
477    * 
478    * @param seq
479    */
480   void selectSeq(int seq)
481   {
482     lastid = seq;
483
484     SequenceI pickedSeq = av.getAlignment().getSequenceAt(seq);
485     av.getSelectionGroup().addOrRemove(pickedSeq, false);
486   }
487
488   /**
489    * Add contiguous rows of the alignment to the current selection group. Does
490    * nothing if there is no selection group.
491    * 
492    * @param start
493    * @param end
494    */
495   void selectSeqs(int start, int end)
496   {
497     if (av.getSelectionGroup() == null)
498     {
499       return;
500     }
501
502     if (end >= av.getAlignment().getHeight())
503     {
504       end = av.getAlignment().getHeight() - 1;
505     }
506
507     lastid = start;
508
509     if (end < start)
510     {
511       int tmp = start;
512       start = end;
513       end = tmp;
514       lastid = end;
515     }
516
517     for (int i = start; i <= end; i++)
518     {
519       av.getSelectionGroup().addSequence(av.getAlignment().getSequenceAt(i),
520               false);
521     }
522   }
523
524   /**
525    * Respond to mouse released. Refreshes the display and triggers broadcast of
526    * the new selection group to any listeners.
527    * 
528    * @param e
529    */
530   @Override
531   public void mouseReleased(MouseEvent e)
532   {
533     if (scrollThread != null)
534     {
535       stopScrolling();
536     }
537     MousePos pos = alignPanel.getSeqPanel().findMousePosition(e);
538
539     mouseDragging = false;
540     PaintRefresher.Refresh(this, av.getSequenceSetId());
541     // always send selection message when mouse is released
542     av.sendSelection();
543
544     if (e.isPopupTrigger()) // Windows reports this in mouseReleased
545     {
546       showPopupMenu(e, pos);
547     }
548   }
549
550   /**
551    * Highlight sequence ids that match the given list, and if necessary scroll
552    * to the start sequence of the list.
553    * 
554    * @param list
555    */
556   public void highlightSearchResults(List<SequenceI> list)
557   {
558     getIdCanvas().setHighlighted(list);
559
560     if (list == null || list.isEmpty())
561     {
562       return;
563     }
564
565     int index = av.getAlignment().findIndex(list.get(0));
566
567     // do we need to scroll the panel?
568     if ((av.getRanges().getStartSeq() > index)
569             || (av.getRanges().getEndSeq() < index))
570     {
571       av.getRanges().setStartSeq(index);
572     }
573   }
574
575   public IdCanvas getIdCanvas()
576   {
577     return idCanvas;
578   }
579
580   public void setIdCanvas(IdCanvas idCanvas)
581   {
582     this.idCanvas = idCanvas;
583   }
584
585   /**
586    * Performs scrolling of the visible alignment up or down, adding newly
587    * visible sequences to the current selection
588    */
589   class ScrollThread extends Thread
590   {
591     private boolean running = false;
592
593     private boolean up;
594
595     /**
596      * Constructor for a thread that scrolls either up or down
597      * 
598      * @param up
599      */
600     public ScrollThread(boolean up)
601     {
602       this.up = up;
603       setName("IdPanel$ScrollThread$" + String.valueOf(up));
604     }
605
606     /**
607      * Sets a flag to stop the scrolling
608      */
609     public void stopScrolling()
610     {
611       running = false;
612     }
613
614     /**
615      * Scrolls the alignment either up or down, one row at a time, adding newly
616      * visible sequences to the current selection. Speed is limited to a maximum
617      * of ten rows per second. The thread exits when the end of the alignment is
618      * reached or a flag is set to stop it by a call to stopScrolling.
619      */
620     @Override
621     public void run()
622     {
623       running = true;
624
625       while (running)
626       {
627         running = scrollOnce();
628         try
629         {
630           Thread.sleep(100);
631         } catch (Exception ex)
632         {
633         }
634       }
635       IdPanel.this.scrollThread = null;
636     }
637
638     /**
639      * Scrolls one row up or down. Answers true if a scroll could be done, false
640      * if not (top or bottom of alignment reached).
641      */
642     boolean scrollOnce()
643     {
644       ViewportRanges ranges = IdPanel.this.av.getRanges();
645       if (ranges.scrollUp(up))
646       {
647         int toSeq = up ? ranges.getStartSeq() : ranges.getEndSeq();
648         int fromSeq = toSeq < lastid ? lastid - 1 : lastid + 1;
649         IdPanel.this.selectSeqs(fromSeq, toSeq);
650         lastid = toSeq;
651         alignPanel.paintAlignment(false, false);
652         return true;
653       }
654
655       return false;
656     }
657   }
658 }