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