JAL-3072 SeqPanel.stopScrolling on mouse up in scale or annotation panel
[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.viewmodel.AlignmentViewport;
31 import jalview.viewmodel.ViewportRanges;
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
41 import javax.swing.JPanel;
42 import javax.swing.SwingUtilities;
43 import javax.swing.ToolTipManager;
44
45 /**
46  * This panel hosts alignment sequence ids and responds to mouse clicks on them,
47  * as well as highlighting ids matched by a search from the Find menu.
48  * 
49  * @author $author$
50  * @version $Revision$
51  */
52 public class IdPanel extends JPanel
53         implements MouseListener, MouseMotionListener, MouseWheelListener
54 {
55   private IdCanvas idCanvas;
56
57   protected AlignmentViewport av;
58
59   protected AlignmentPanel alignPanel;
60
61   ScrollThread scrollThread = null;
62
63   String linkImageURL;
64
65   int offy;
66
67   // int width;
68   int lastid = -1;
69
70   boolean mouseDragging = false;
71
72   private final SequenceAnnotationReport seqAnnotReport;
73
74   /**
75    * Creates a new IdPanel object.
76    * 
77    * @param av
78    * @param parent
79    */
80   public IdPanel(AlignViewport av, AlignmentPanel parent)
81   {
82     this.av = av;
83     alignPanel = parent;
84     setIdCanvas(new IdCanvas(av));
85     linkImageURL = getClass().getResource("/images/link.gif").toString();
86     seqAnnotReport = new SequenceAnnotationReport(linkImageURL);
87     setLayout(new BorderLayout());
88     add(getIdCanvas(), BorderLayout.CENTER);
89     addMouseListener(this);
90     addMouseMotionListener(this);
91     addMouseWheelListener(this);
92     ToolTipManager.sharedInstance().registerComponent(this);
93   }
94
95   /**
96    * Respond to mouse movement by constructing tooltip text for the sequence id
97    * under the mouse.
98    * 
99    * @param e
100    *          DOCUMENT ME!
101    */
102   @Override
103   public void mouseMoved(MouseEvent e)
104   {
105     SeqPanel sp = alignPanel.getSeqPanel();
106     int seq = Math.max(0, sp.findSeq(e));
107     if (seq > -1 && seq < av.getAlignment().getHeight())
108     {
109       SequenceI sequence = av.getAlignment().getSequenceAt(seq);
110       StringBuilder tip = new StringBuilder(64);
111       seqAnnotReport.createTooltipAnnotationReport(tip, sequence,
112               av.isShowDBRefs(), av.isShowNPFeats(), sp.seqCanvas.fr);
113       setToolTipText(JvSwingUtils.wrapTooltip(true,
114               sequence.getDisplayId(true) + " " + tip.toString()));
115     }
116   }
117
118   /**
119    * Responds to a mouse drag by selecting the sequences under the dragged
120    * region.
121    * 
122    * @param e
123    */
124   @Override
125   public void mouseDragged(MouseEvent e)
126   {
127     mouseDragging = true;
128
129     int seq = Math.max(0, alignPanel.getSeqPanel().findSeq(e));
130
131     if (seq < lastid)
132     {
133       selectSeqs(lastid - 1, seq);
134     }
135     else if (seq > lastid)
136     {
137       selectSeqs(lastid + 1, seq);
138     }
139
140     lastid = seq;
141     alignPanel.paintAlignment(false, false);
142   }
143
144   /**
145    * Response to the mouse wheel by scrolling the alignment panel.
146    */
147   @Override
148   public void mouseWheelMoved(MouseWheelEvent e)
149   {
150     e.consume();
151     double wheelRotation = e.getPreciseWheelRotation();
152     if (wheelRotation > 0)
153     {
154       if (e.isShiftDown())
155       {
156         av.getRanges().scrollRight(true);
157       }
158       else
159       {
160         av.getRanges().scrollUp(false);
161       }
162     }
163     else if (wheelRotation < 0)
164     {
165       if (e.isShiftDown())
166       {
167         av.getRanges().scrollRight(false);
168       }
169       else
170       {
171         av.getRanges().scrollUp(true);
172       }
173     }
174   }
175
176   /**
177    * Handle a mouse click event. Currently only responds to a double-click. The
178    * action is to try to open a browser window at a URL that searches for the
179    * selected sequence id. The search URL is configured in Preferences |
180    * Connections | URL link from Sequence ID. For example:
181    * 
182    * http://www.ebi.ac.uk/ebisearch/search.ebi?db=allebi&query=$SEQUENCE_ID$
183    * 
184    * @param e
185    */
186   @Override
187   public void mouseClicked(MouseEvent e)
188   {
189     /*
190      * Ignore single click. Ignore 'left' click followed by 'right' click (user
191      * selects a row then its pop-up menu).
192      */
193     if (e.getClickCount() < 2 || SwingUtilities.isRightMouseButton(e))
194     {
195       // reinstate isRightMouseButton check to ignore mouse-related popup events
196       // note - this does nothing on default MacBookPro force-trackpad config!
197       return;
198     }
199
200     int seq = alignPanel.getSeqPanel().findSeq(e);
201     String id = av.getAlignment().getSequenceAt(seq).getName();
202     String url = Preferences.sequenceUrlLinks.getPrimaryUrl(id);
203
204     try
205     {
206       jalview.util.BrowserLauncher.openURL(url);
207     } catch (Exception ex)
208     {
209       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
210               MessageManager.getString("label.web_browser_not_found_unix"),
211               MessageManager.getString("label.web_browser_not_found"),
212               JvOptionPane.WARNING_MESSAGE);
213       ex.printStackTrace();
214     }
215   }
216
217   /**
218    * DOCUMENT ME!
219    * 
220    * @param e
221    *          DOCUMENT ME!
222    */
223   @Override
224   public void mouseEntered(MouseEvent e)
225   {
226     if (scrollThread != null)
227     {
228       scrollThread.stopScrolling();
229     }
230   }
231
232   /**
233    * DOCUMENT ME!
234    * 
235    * @param e
236    *          DOCUMENT ME!
237    */
238   @Override
239   public void mouseExited(MouseEvent e)
240   {
241     if (av.getWrapAlignment())
242     {
243       return;
244     }
245
246     if (mouseDragging && (e.getY() < 0)
247             && (av.getRanges().getStartSeq() > 0))
248     {
249       scrollThread = new ScrollThread(true);
250     }
251
252     if (mouseDragging && (e.getY() >= getHeight())
253             && (av.getAlignment().getHeight() > av.getRanges().getEndSeq()))
254     {
255       scrollThread = new ScrollThread(false);
256     }
257   }
258
259   /**
260    * Respond to a mouse press. Does nothing for (left) double-click as this is
261    * handled by mouseClicked().
262    * 
263    * Right mouse down - construct and show context menu.
264    * 
265    * Ctrl-down or Shift-down - add to or expand current selection group if there
266    * is one.
267    * 
268    * Mouse down - select this sequence.
269    * 
270    * @param e
271    */
272   @Override
273   public void mousePressed(MouseEvent e)
274   {
275     if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e))
276     {
277       return;
278     }
279
280     if (e.isPopupTrigger()) // Mac reports this in mousePressed
281     {
282       showPopupMenu(e);
283       return;
284     }
285
286     /*
287      * defer right-mouse click handling to mouseReleased on Windows
288      * (where isPopupTrigger() will answer true)
289      * NB isRightMouseButton is also true for Cmd-click on Mac
290      */
291     if (SwingUtilities.isRightMouseButton(e) && !Platform.isAMac())
292     {
293       return;
294     }
295
296     if ((av.getSelectionGroup() == null)
297             || (!jalview.util.Platform.isControlDown(e) && !e.isShiftDown()
298                     && av.getSelectionGroup() != null))
299     {
300       av.setSelectionGroup(new SequenceGroup());
301       av.getSelectionGroup().setStartRes(0);
302       av.getSelectionGroup().setEndRes(av.getAlignment().getWidth() - 1);
303     }
304
305     int seq = alignPanel.getSeqPanel().findSeq(e);
306     if (e.isShiftDown() && (lastid != -1))
307     {
308       selectSeqs(lastid, seq);
309     }
310     else
311     {
312       selectSeq(seq);
313     }
314
315     av.isSelectionGroupChanged(true);
316
317     alignPanel.paintAlignment(false, false);
318   }
319
320   /**
321    * Build and show the popup-menu at the right-click mouse position
322    * 
323    * @param e
324    */
325   void showPopupMenu(MouseEvent e)
326   {
327     int seq2 = alignPanel.getSeqPanel().findSeq(e);
328     Sequence sq = (Sequence) av.getAlignment().getSequenceAt(seq2);
329
330     /*
331      *  build a new links menu based on the current links
332      *  and any non-positional features
333      */
334     List<String> nlinks = Preferences.sequenceUrlLinks.getLinksForMenu();
335     List<SequenceFeature> features = sq.getFeatures().getNonPositionalFeatures();
336     for (SequenceFeature sf : features)
337     {
338       if (sf.links != null)
339       {
340         for (String link : sf.links)
341         {
342           nlinks.add(link);
343         }
344       }
345     }
346
347     PopupMenu pop = new PopupMenu(alignPanel, sq, features,
348             Preferences.getGroupURLLinks());
349     pop.show(this, e.getX(), e.getY());
350   }
351
352   /**
353    * Toggle whether the sequence is part of the current selection group.
354    * 
355    * @param seq
356    */
357   void selectSeq(int seq)
358   {
359     lastid = seq;
360
361     SequenceI pickedSeq = av.getAlignment().getSequenceAt(seq);
362     av.getSelectionGroup().addOrRemove(pickedSeq, true);
363   }
364
365   /**
366    * Add contiguous rows of the alignment to the current selection group. Does
367    * nothing if there is no selection group.
368    * 
369    * @param start
370    * @param end
371    */
372   void selectSeqs(int start, int end)
373   {
374     if (av.getSelectionGroup() == null)
375     {
376       return;
377     }
378
379     if (end >= av.getAlignment().getHeight())
380     {
381       end = av.getAlignment().getHeight() - 1;
382     }
383
384     lastid = start;
385
386     if (end < start)
387     {
388       int tmp = start;
389       start = end;
390       end = tmp;
391       lastid = end;
392     }
393
394     for (int i = start; i <= end; i++)
395     {
396       av.getSelectionGroup().addSequence(av.getAlignment().getSequenceAt(i),
397               i == end);
398     }
399   }
400
401   /**
402    * Respond to mouse released. Refreshes the display and triggers broadcast of
403    * the new selection group to any listeners.
404    * 
405    * @param e
406    */
407   @Override
408   public void mouseReleased(MouseEvent e)
409   {
410     if (scrollThread != null)
411     {
412       scrollThread.stopScrolling();
413     }
414
415     mouseDragging = false;
416     PaintRefresher.Refresh(this, av.getSequenceSetId());
417     // always send selection message when mouse is released
418     av.sendSelection();
419
420     if (e.isPopupTrigger()) // Windows reports this in mouseReleased
421     {
422       showPopupMenu(e);
423     }
424   }
425
426   /**
427    * Highlight sequence ids that match the given list, and if necessary scroll
428    * to the start sequence of the list.
429    * 
430    * @param list
431    */
432   public void highlightSearchResults(List<SequenceI> list)
433   {
434     getIdCanvas().setHighlighted(list);
435
436     if (list == null)
437     {
438       return;
439     }
440
441     int index = av.getAlignment().findIndex(list.get(0));
442
443     // do we need to scroll the panel?
444     if ((av.getRanges().getStartSeq() > index)
445             || (av.getRanges().getEndSeq() < index))
446     {
447       av.getRanges().setStartSeq(index);
448     }
449   }
450
451   public IdCanvas getIdCanvas()
452   {
453     return idCanvas;
454   }
455
456   public void setIdCanvas(IdCanvas idCanvas)
457   {
458     this.idCanvas = idCanvas;
459   }
460
461   /**
462    * Performs scrolling of the visible alignment up or down, adding newly
463    * visible sequences to the current selection
464    */
465   class ScrollThread extends Thread
466   {
467     private boolean running = false;
468
469     private boolean up;
470
471     /**
472      * Constructor for a thread that scrolls either up or down
473      * 
474      * @param up
475      */
476     public ScrollThread(boolean up)
477     {
478       this.up = up;
479       setName("IdPanel$ScrollThread$" + String.valueOf(up));
480       start();
481     }
482
483     /**
484      * Sets a flag to stop the scrolling
485      */
486     public void stopScrolling()
487     {
488       running = false;
489     }
490
491     /**
492      * Scrolls the alignment either up or down, one row at a time, adding newly
493      * visible sequences to the current selection. Speed is limited to a maximum
494      * of ten rows per second. The thread exits when the end of the alignment is
495      * reached or a flag is set to stop it.
496      */
497     @Override
498     public void run()
499     {
500       running = true;
501
502       while (running)
503       {
504         ViewportRanges ranges = IdPanel.this.av.getRanges();
505         if (ranges.scrollUp(up))
506         {
507           int toSeq = up ? ranges.getStartSeq() : ranges.getEndSeq();
508           int fromSeq = toSeq < lastid ? lastid - 1 : lastid + 1;
509           IdPanel.this.selectSeqs(fromSeq, toSeq);
510
511           lastid = toSeq;
512         }
513         else
514         {
515           /*
516            * scroll did nothing - reached limit of visible alignment
517            */
518           running = false;
519         }
520
521         alignPanel.paintAlignment(false, false);
522
523         try
524         {
525           Thread.sleep(100);
526         } catch (Exception ex)
527         {
528         }
529       }
530     }
531   }
532 }