Merge develop to Release_2_8_3_Branch
[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
31 import java.awt.BorderLayout;
32 import java.awt.event.MouseEvent;
33 import java.awt.event.MouseListener;
34 import java.awt.event.MouseMotionListener;
35 import java.awt.event.MouseWheelEvent;
36 import java.awt.event.MouseWheelListener;
37 import java.util.List;
38 import java.util.Vector;
39
40 import javax.swing.JOptionPane;
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 implements MouseListener,
53         MouseMotionListener, MouseWheelListener
54 {
55   private IdCanvas idCanvas;
56
57   protected AlignViewport 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       StringBuffer tip = new StringBuffer(64);
111       seqAnnotReport
112               .createSequenceAnnotationReport(tip, sequence,
113               av.isShowDBRefs(), av.isShowNPFeats(),
114                       sp.seqCanvas.fr.getMinMax());
115       setToolTipText("<html>" + sequence.getDisplayId(true) + " "
116               + tip.toString() + "</html>");
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       return;
197     }
198
199     Vector links = Preferences.sequenceURLLinks;
200     if (links == null || links.size() < 1)
201     {
202       return;
203     }
204
205     int seq = alignPanel.getSeqPanel().findSeq(e);
206     String url = null;
207     int i = 0;
208     String id = av.getAlignment().getSequenceAt(seq).getName();
209     while (url == null && i < links.size())
210     {
211       // DEFAULT LINK IS FIRST IN THE LINK LIST
212       // BUT IF ITS A REGEX AND DOES NOT MATCH THE NEXT ONE WILL BE TRIED
213       url = links.elementAt(i++).toString();
214       jalview.util.UrlLink urlLink = null;
215       try
216       {
217         urlLink = new UrlLink(url);
218       } catch (Exception foo)
219       {
220         jalview.bin.Cache.log.error("Exception for URLLink '" + url + "'",
221                 foo);
222         url = null;
223         continue;
224       }
225       ;
226       if (!urlLink.isValid())
227       {
228         jalview.bin.Cache.log.error(urlLink.getInvalidMessage());
229         url = null;
230         continue;
231       }
232
233       String urls[] = urlLink.makeUrls(id, true);
234       if (urls == null || urls[0] == null || urls[0].length() < 4)
235       {
236         url = null;
237         continue;
238       }
239       // just take first URL made from regex
240       url = urls[1];
241     }
242     try
243     {
244       jalview.util.BrowserLauncher.openURL(url);
245     } catch (Exception ex)
246     {
247       JOptionPane
248               .showInternalMessageDialog(
249                       Desktop.desktop,
250                       MessageManager.getString("label.web_browser_not_found_unix"),
251                       MessageManager.getString("label.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.getSeqPanel().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.getSequenceFeatures();
327       for (int sl = 0; sf != null && sl < sf.length; sl++)
328       {
329         if (sf[sl].begin == sf[sl].end && sf[sl].begin == 0)
330         {
331           if (sf[sl].links != null && sf[sl].links.size() > 0)
332           {
333             for (int l = 0, lSize = sf[sl].links.size(); l < lSize; l++)
334             {
335               nlinks.addElement(sf[sl].links.elementAt(l));
336             }
337           }
338         }
339       }
340
341       jalview.gui.PopupMenu pop = new jalview.gui.PopupMenu(alignPanel, sq,
342               nlinks, new Vector(Preferences.getGroupURLLinks()));
343       pop.show(this, e.getX(), e.getY());
344
345       return;
346     }
347
348     if ((av.getSelectionGroup() == null)
349             || ((!e.isControlDown() && !e.isShiftDown()) && av
350                     .getSelectionGroup() != null))
351     {
352       av.setSelectionGroup(new SequenceGroup());
353       av.getSelectionGroup().setStartRes(0);
354       av.getSelectionGroup().setEndRes(av.getAlignment().getWidth() - 1);
355     }
356
357     if (e.isShiftDown() && (lastid != -1))
358     {
359       selectSeqs(lastid, seq);
360     }
361     else
362     {
363       selectSeq(seq);
364     }
365     // TODO is this addition ok here?
366     av.isSelectionGroupChanged(true);
367
368     alignPanel.paintAlignment(true);
369   }
370
371   /**
372    * Toggle whether the sequence is part of the current selection group.
373    * 
374    * @param seq
375    */
376   void selectSeq(int seq)
377   {
378     lastid = seq;
379
380     SequenceI pickedSeq = av.getAlignment().getSequenceAt(seq);
381     av.getSelectionGroup().addOrRemove(pickedSeq, true);
382   }
383
384   /**
385    * Add contiguous rows of the alignment to the current selection group. Does
386    * nothing if there is no selection group.
387    * 
388    * @param start
389    * @param end
390    */
391   void selectSeqs(int start, int end)
392   {
393     if (av.getSelectionGroup() == null)
394     {
395       return;
396     }
397
398     if (end >= av.getAlignment().getHeight())
399     {
400       end = av.getAlignment().getHeight() - 1;
401     }
402
403     lastid = start;
404
405     if (end < start)
406     {
407       int tmp = start;
408       start = end;
409       end = tmp;
410       lastid = end;
411     }
412
413     for (int i = start; i <= end; i++)
414     {
415       av.getSelectionGroup().addSequence(
416               av.getAlignment().getSequenceAt(i), i == end);
417     }
418   }
419
420   /**
421    * Respond to mouse released. Refreshes the display and triggers broadcast of
422    * the new selection group to any listeners.
423    * 
424    * @param e
425    */
426   @Override
427   public void mouseReleased(MouseEvent e)
428   {
429     if (scrollThread != null)
430     {
431       scrollThread.running = false;
432     }
433
434     mouseDragging = false;
435     PaintRefresher.Refresh(this, av.getSequenceSetId());
436     // always send selection message when mouse is released
437     av.sendSelection();
438   }
439
440   /**
441    * Highlight sequence ids that match the given list, and if necessary scroll
442    * to the start sequence of the list.
443    * 
444    * @param list
445    */
446   public void highlightSearchResults(List<SequenceI> list)
447   {
448     getIdCanvas().setHighlighted(list);
449
450     if (list == null)
451     {
452       return;
453     }
454
455     int index = av.getAlignment().findIndex(list.get(0));
456
457     // do we need to scroll the panel?
458     if ((av.getStartSeq() > index) || (av.getEndSeq() < index))
459     {
460       alignPanel.setScrollValues(av.getStartRes(), index);
461     }
462   }
463
464   public IdCanvas getIdCanvas()
465   {
466     return idCanvas;
467   }
468
469   public void setIdCanvas(IdCanvas idCanvas)
470   {
471     this.idCanvas = idCanvas;
472   }
473
474   // this class allows scrolling off the bottom of the visible alignment
475   class ScrollThread extends Thread
476   {
477     boolean running = false;
478
479     boolean up = true;
480
481     public ScrollThread(boolean up)
482     {
483       this.up = up;
484       start();
485     }
486
487     public void stopScrolling()
488     {
489       running = false;
490     }
491
492     @Override
493     public void run()
494     {
495       running = true;
496
497       while (running)
498       {
499         if (alignPanel.scrollUp(up))
500         {
501           // scroll was ok, so add new sequence to selection
502           int seq = av.getStartSeq();
503
504           if (!up)
505           {
506             seq = av.getEndSeq();
507           }
508
509           if (seq < lastid)
510           {
511             selectSeqs(lastid - 1, seq);
512           }
513           else if (seq > lastid)
514           {
515             selectSeqs(lastid + 1, seq);
516           }
517
518           lastid = seq;
519         }
520         else
521         {
522           running = false;
523         }
524
525         alignPanel.paintAlignment(false);
526
527         try
528         {
529           Thread.sleep(100);
530         } catch (Exception ex)
531         {
532         }
533       }
534     }
535   }
536 }