Merge branch 'bug/JAL-2791exportFilteredFeature' into merge/JAL-2791
[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.SequenceFeature;
26 import jalview.datamodel.SequenceGroup;
27 import jalview.datamodel.SequenceI;
28 import jalview.gui.SeqPanel.MousePos;
29 import jalview.io.SequenceAnnotationReport;
30 import jalview.util.MessageManager;
31 import jalview.util.Platform;
32 import jalview.viewmodel.AlignmentViewport;
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.running = false;
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
372     /*
373      *  build a new links menu based on the current links
374      *  and any non-positional features
375      */
376     List<SequenceFeature> features = null;
377     if (sq != null)
378     {
379     List<String> nlinks = Preferences.sequenceUrlLinks.getLinksForMenu();
380       features = sq.getFeatures().getNonPositionalFeatures();
381     for (SequenceFeature sf : features)
382     {
383       if (sf.links != null)
384       {
385         nlinks.addAll(sf.links);
386       }
387     }
388     }
389
390     PopupMenu pop = new PopupMenu(alignPanel, sq, features,
391             Preferences.getGroupURLLinks());
392     pop.show(this, e.getX(), e.getY());
393   }
394
395   /**
396    * On right mouse click on a Consensus annotation label, shows a limited popup
397    * menu, with options to configure the consensus calculation and rendering.
398    * 
399    * @param e
400    * @param pos
401    * @see AnnotationLabels#showPopupMenu(MouseEvent)
402    */
403   void showAnnotationMenu(MouseEvent e, MousePos pos)
404   {
405     if (pos.annotationIndex == -1)
406     {
407       return;
408     }
409     AlignmentAnnotation[] anns = this.av.getAlignment()
410             .getAlignmentAnnotation();
411     if (anns == null || pos.annotationIndex >= anns.length)
412     {
413       return;
414     }
415     AlignmentAnnotation ann = anns[pos.annotationIndex];
416     if (!ann.label.contains("Consensus"))
417     {
418       return;
419     }
420
421     JPopupMenu pop = new JPopupMenu(
422             MessageManager.getString("label.annotations"));
423     AnnotationLabels.addConsensusMenuOptions(this.alignPanel, ann, pop);
424     pop.show(this, e.getX(), e.getY());
425   }
426
427   /**
428    * Toggle whether the sequence is part of the current selection group.
429    * 
430    * @param seq
431    */
432   void selectSeq(int seq)
433   {
434     lastid = seq;
435
436     SequenceI pickedSeq = av.getAlignment().getSequenceAt(seq);
437     av.getSelectionGroup().addOrRemove(pickedSeq, false);
438   }
439
440   /**
441    * Add contiguous rows of the alignment to the current selection group. Does
442    * nothing if there is no selection group.
443    * 
444    * @param start
445    * @param end
446    */
447   void selectSeqs(int start, int end)
448   {
449     if (av.getSelectionGroup() == null)
450     {
451       return;
452     }
453
454     if (end >= av.getAlignment().getHeight())
455     {
456       end = av.getAlignment().getHeight() - 1;
457     }
458
459     lastid = start;
460
461     if (end < start)
462     {
463       int tmp = start;
464       start = end;
465       end = tmp;
466       lastid = end;
467     }
468
469     for (int i = start; i <= end; i++)
470     {
471       av.getSelectionGroup().addSequence(av.getAlignment().getSequenceAt(i),
472               false);
473     }
474   }
475
476   /**
477    * Respond to mouse released. Refreshes the display and triggers broadcast of
478    * the new selection group to any listeners.
479    * 
480    * @param e
481    */
482   @Override
483   public void mouseReleased(MouseEvent e)
484   {
485     if (scrollThread != null)
486     {
487       scrollThread.running = false;
488     }
489     MousePos pos = alignPanel.getSeqPanel().findMousePosition(e);
490
491     mouseDragging = false;
492     PaintRefresher.Refresh(this, av.getSequenceSetId());
493     // always send selection message when mouse is released
494     av.sendSelection();
495
496     if (e.isPopupTrigger()) // Windows reports this in mouseReleased
497     {
498       showPopupMenu(e, pos);
499     }
500   }
501
502   /**
503    * Highlight sequence ids that match the given list, and if necessary scroll
504    * to the start sequence of the list.
505    * 
506    * @param list
507    */
508   public void highlightSearchResults(List<SequenceI> list)
509   {
510     getIdCanvas().setHighlighted(list);
511
512     if (list == null)
513     {
514       return;
515     }
516
517     int index = av.getAlignment().findIndex(list.get(0));
518
519     // do we need to scroll the panel?
520     if ((av.getRanges().getStartSeq() > index)
521             || (av.getRanges().getEndSeq() < index))
522     {
523       av.getRanges().setStartSeq(index);
524     }
525   }
526
527   public IdCanvas getIdCanvas()
528   {
529     return idCanvas;
530   }
531
532   public void setIdCanvas(IdCanvas idCanvas)
533   {
534     this.idCanvas = idCanvas;
535   }
536
537   // this class allows scrolling off the bottom of the visible alignment
538   class ScrollThread extends Thread
539   {
540     boolean running = false;
541
542     boolean up = true;
543
544     public ScrollThread(boolean up)
545     {
546       this.up = up;
547       start();
548     }
549
550     public void stopScrolling()
551     {
552       running = false;
553     }
554
555     @Override
556     public void run()
557     {
558       running = true;
559
560       while (running)
561       {
562         if (av.getRanges().scrollUp(up))
563         {
564           // scroll was ok, so add new sequence to selection
565           int seq = av.getRanges().getStartSeq();
566
567           if (!up)
568           {
569             seq = av.getRanges().getEndSeq();
570           }
571
572           if (seq < lastid)
573           {
574             selectSeqs(lastid - 1, seq);
575           }
576           else if (seq > lastid)
577           {
578             selectSeqs(lastid + 1, seq);
579           }
580
581           lastid = seq;
582         }
583         else
584         {
585           running = false;
586         }
587
588         alignPanel.paintAlignment(false, false);
589
590         try
591         {
592           Thread.sleep(100);
593         } catch (Exception ex)
594         {
595         }
596       }
597     }
598   }
599 }