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