JAL-1554 handle left-then-right click on sequence id
[jalview.git] / src / jalview / gui / IdPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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.UrlLink;
29
30 import java.awt.BorderLayout;
31 import java.awt.event.MouseEvent;
32 import java.awt.event.MouseListener;
33 import java.awt.event.MouseMotionListener;
34 import java.awt.event.MouseWheelEvent;
35 import java.awt.event.MouseWheelListener;
36 import java.util.List;
37 import java.util.Vector;
38
39 import javax.swing.JOptionPane;
40 import javax.swing.JPanel;
41 import javax.swing.SwingUtilities;
42 import javax.swing.ToolTipManager;
43
44 /**
45  * This panel hosts alignment sequence ids and responds to mouse clicks on them,
46  * as well as highlighting ids matched by a search from the Find menu.
47  * 
48  * @author $author$
49  * @version $Revision$
50  */
51 public class IdPanel extends JPanel implements MouseListener,
52         MouseMotionListener, MouseWheelListener
53 {
54   protected IdCanvas idCanvas;
55
56   protected AlignViewport av;
57
58   protected AlignmentPanel alignPanel;
59
60   ScrollThread scrollThread = null;
61
62   String linkImageURL;
63
64   int offy;
65
66   // int width;
67   int lastid = -1;
68
69   boolean mouseDragging = false;
70
71   private final SequenceAnnotationReport seqAnnotReport;
72
73   /**
74    * Creates a new IdPanel object.
75    * 
76    * @param av
77    * @param parent
78    */
79   public IdPanel(AlignViewport av, AlignmentPanel parent)
80   {
81     this.av = av;
82     alignPanel = parent;
83     idCanvas = new IdCanvas(av);
84     linkImageURL = getClass().getResource("/images/link.gif").toString();
85     seqAnnotReport = new SequenceAnnotationReport(linkImageURL);
86     setLayout(new BorderLayout());
87     add(idCanvas, BorderLayout.CENTER);
88     addMouseListener(this);
89     addMouseMotionListener(this);
90     addMouseWheelListener(this);
91     ToolTipManager.sharedInstance().registerComponent(this);
92   }
93
94   /**
95    * Respond to mouse movement by constructing tooltip text for the sequence id
96    * under the mouse.
97    * 
98    * @param e
99    *          DOCUMENT ME!
100    */
101   @Override
102   public void mouseMoved(MouseEvent e)
103   {
104     SeqPanel sp = alignPanel.seqPanel;
105     int seq = Math.max(0, sp.findSeq(e));
106     if (seq > -1 && seq < av.getAlignment().getHeight())
107     {
108       SequenceI sequence = av.getAlignment().getSequenceAt(seq);
109       StringBuffer tip = new StringBuffer(64);
110       seqAnnotReport
111               .createSequenceAnnotationReport(tip, sequence,
112                       av.isShowDbRefs(), av.isShowNpFeats(),
113                       sp.seqCanvas.fr.minmax);
114       setToolTipText("<html>" + sequence.getDisplayId(true) + " "
115               + tip.toString() + "</html>");
116     }
117   }
118
119   /**
120    * Responds to a mouse drag by selecting the sequences under the dragged
121    * region.
122    * 
123    * @param e
124    */
125   @Override
126   public void mouseDragged(MouseEvent e)
127   {
128     mouseDragging = true;
129
130     int seq = Math.max(0, alignPanel.seqPanel.findSeq(e));
131
132     if (seq < lastid)
133     {
134       selectSeqs(lastid - 1, seq);
135     }
136     else if (seq > lastid)
137     {
138       selectSeqs(lastid + 1, seq);
139     }
140
141     lastid = seq;
142     alignPanel.paintAlignment(true);
143   }
144
145   /**
146    * Response to the mouse wheel by scrolling the alignment panel.
147    */
148   @Override
149   public void mouseWheelMoved(MouseWheelEvent e)
150   {
151     e.consume();
152     if (e.getWheelRotation() > 0)
153     {
154       if (e.isShiftDown())
155       {
156         alignPanel.scrollRight(true);
157       }
158       else
159       {
160         alignPanel.scrollUp(false);
161       }
162     }
163     else
164     {
165       if (e.isShiftDown())
166       {
167         alignPanel.scrollRight(false);
168       }
169       else
170       {
171         alignPanel.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       return;
196     }
197
198     Vector links = Preferences.sequenceURLLinks;
199     if (links == null || links.size() < 1)
200     {
201       return;
202     }
203
204     int seq = alignPanel.seqPanel.findSeq(e);
205     String url = null;
206     int i = 0;
207     String id = av.getAlignment().getSequenceAt(seq).getName();
208     while (url == null && i < links.size())
209     {
210       // DEFAULT LINK IS FIRST IN THE LINK LIST
211       // BUT IF ITS A REGEX AND DOES NOT MATCH THE NEXT ONE WILL BE TRIED
212       url = links.elementAt(i++).toString();
213       jalview.util.UrlLink urlLink = null;
214       try
215       {
216         urlLink = new UrlLink(url);
217       } catch (Exception foo)
218       {
219         jalview.bin.Cache.log.error("Exception for URLLink '" + url + "'",
220                 foo);
221         url = null;
222         continue;
223       }
224       ;
225       if (!urlLink.isValid())
226       {
227         jalview.bin.Cache.log.error(urlLink.getInvalidMessage());
228         url = null;
229         continue;
230       }
231
232       String urls[] = urlLink.makeUrls(id, true);
233       if (urls == null || urls[0] == null || urls[0].length() < 4)
234       {
235         url = null;
236         continue;
237       }
238       // just take first URL made from regex
239       url = urls[1];
240     }
241     try
242     {
243       jalview.util.BrowserLauncher.openURL(url);
244     } catch (Exception ex)
245     {
246       JOptionPane
247               .showInternalMessageDialog(
248                       Desktop.desktop,
249                       "Unixers: Couldn't find default web browser."
250                               + "\nAdd the full path to your browser in Preferences.",
251                       "Web browser not found", JOptionPane.WARNING_MESSAGE);
252       ex.printStackTrace();
253     }
254   }
255
256   /**
257    * DOCUMENT ME!
258    * 
259    * @param e
260    *          DOCUMENT ME!
261    */
262   @Override
263   public void mouseEntered(MouseEvent e)
264   {
265     if (scrollThread != null)
266     {
267       scrollThread.running = false;
268     }
269   }
270
271   /**
272    * DOCUMENT ME!
273    * 
274    * @param e
275    *          DOCUMENT ME!
276    */
277   @Override
278   public void mouseExited(MouseEvent e)
279   {
280     if (av.getWrapAlignment())
281     {
282       return;
283     }
284
285     if (mouseDragging && (e.getY() < 0) && (av.getStartSeq() > 0))
286     {
287       scrollThread = new ScrollThread(true);
288     }
289
290     if (mouseDragging && (e.getY() >= getHeight())
291             && (av.getAlignment().getHeight() > av.getEndSeq()))
292     {
293       scrollThread = new ScrollThread(false);
294     }
295   }
296
297   /**
298    * Respond to a mouse press. Does nothing for (left) double-click as this is
299    * handled by mouseClicked().
300    * 
301    * Right mouse down - construct and show context menu.
302    * 
303    * Ctrl-down or Shift-down - add to or expand current selection group if there
304    * is one.
305    * 
306    * Mouse down - select this sequence.
307    * 
308    * @param e
309    */
310   @Override
311   public void mousePressed(MouseEvent e)
312   {
313     if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e))
314     {
315       return;
316     }
317
318     int seq = alignPanel.seqPanel.findSeq(e);
319
320     if (SwingUtilities.isRightMouseButton(e))
321     {
322       Sequence sq = (Sequence) av.getAlignment().getSequenceAt(seq);
323       // build a new links menu based on the current links + any non-positional
324       // features
325       Vector nlinks = new Vector(Preferences.sequenceURLLinks);
326       SequenceFeature sf[] = sq == null ? null : sq.getDatasetSequence()
327               .getSequenceFeatures();
328       for (int sl = 0; sf != null && sl < sf.length; sl++)
329       {
330         if (sf[sl].begin == sf[sl].end && sf[sl].begin == 0)
331         {
332           if (sf[sl].links != null && sf[sl].links.size() > 0)
333           {
334             for (int l = 0, lSize = sf[sl].links.size(); l < lSize; l++)
335             {
336               nlinks.addElement(sf[sl].links.elementAt(l));
337             }
338           }
339         }
340       }
341
342       jalview.gui.PopupMenu pop = new jalview.gui.PopupMenu(alignPanel, sq,
343               nlinks, new Vector(Preferences.getGroupURLLinks()));
344       pop.show(this, e.getX(), e.getY());
345
346       return;
347     }
348
349     if ((av.getSelectionGroup() == null)
350             || ((!e.isControlDown() && !e.isShiftDown()) && av
351                     .getSelectionGroup() != null))
352     {
353       av.setSelectionGroup(new SequenceGroup());
354       av.getSelectionGroup().setStartRes(0);
355       av.getSelectionGroup().setEndRes(av.getAlignment().getWidth() - 1);
356     }
357
358     if (e.isShiftDown() && (lastid != -1))
359     {
360       selectSeqs(lastid, seq);
361     }
362     else
363     {
364       selectSeq(seq);
365     }
366     alignPanel.paintAlignment(true);
367   }
368
369   /**
370    * Toggle whether the sequence is part of the current selection group.
371    * 
372    * @param seq
373    */
374   void selectSeq(int seq)
375   {
376     lastid = seq;
377
378     SequenceI pickedSeq = av.getAlignment().getSequenceAt(seq);
379     av.getSelectionGroup().addOrRemove(pickedSeq, true);
380   }
381
382   /**
383    * Add contiguous rows of the alignment to the current selection group. Does
384    * nothing if there is no selection group.
385    * 
386    * @param start
387    * @param end
388    */
389   void selectSeqs(int start, int end)
390   {
391     if (av.getSelectionGroup() == null)
392     {
393       return;
394     }
395
396     if (end >= av.getAlignment().getHeight())
397     {
398       end = av.getAlignment().getHeight() - 1;
399     }
400
401     lastid = start;
402
403     if (end < start)
404     {
405       int tmp = start;
406       start = end;
407       end = tmp;
408       lastid = end;
409     }
410
411     for (int i = start; i <= end; i++)
412     {
413       av.getSelectionGroup().addSequence(
414               av.getAlignment().getSequenceAt(i), i == end);
415     }
416   }
417
418   /**
419    * Respond to mouse released. Refreshes the display and triggers broadcast of
420    * the new selection group to any listeners.
421    * 
422    * @param e
423    */
424   @Override
425   public void mouseReleased(MouseEvent e)
426   {
427     if (scrollThread != null)
428     {
429       scrollThread.running = false;
430     }
431
432     mouseDragging = false;
433     PaintRefresher.Refresh(this, av.getSequenceSetId());
434     // always send selection message when mouse is released
435     av.sendSelection();
436   }
437
438   /**
439    * Highlight sequence ids that match the given list, and if necessary scroll
440    * to the start sequence of the list.
441    * 
442    * @param list
443    */
444   public void highlightSearchResults(List<SequenceI> list)
445   {
446     idCanvas.setHighlighted(list);
447
448     if (list == null)
449     {
450       return;
451     }
452
453     int index = av.getAlignment().findIndex(list.get(0));
454
455     // do we need to scroll the panel?
456     if ((av.getStartSeq() > index) || (av.getEndSeq() < index))
457     {
458       alignPanel.setScrollValues(av.getStartRes(), index);
459     }
460   }
461
462   // this class allows scrolling off the bottom of the visible alignment
463   class ScrollThread extends Thread
464   {
465     boolean running = false;
466
467     boolean up = true;
468
469     public ScrollThread(boolean up)
470     {
471       this.up = up;
472       start();
473     }
474
475     public void stopScrolling()
476     {
477       running = false;
478     }
479
480     @Override
481     public void run()
482     {
483       running = true;
484
485       while (running)
486       {
487         if (alignPanel.scrollUp(up))
488         {
489           // scroll was ok, so add new sequence to selection
490           int seq = av.getStartSeq();
491
492           if (!up)
493           {
494             seq = av.getEndSeq();
495           }
496
497           if (seq < lastid)
498           {
499             selectSeqs(lastid - 1, seq);
500           }
501           else if (seq > lastid)
502           {
503             selectSeqs(lastid + 1, seq);
504           }
505
506           lastid = seq;
507         }
508         else
509         {
510           running = false;
511         }
512
513         alignPanel.paintAlignment(false);
514
515         try
516         {
517           Thread.sleep(100);
518         } catch (Exception ex)
519         {
520         }
521       }
522     }
523   }
524 }