JAL-1691 applet SplitFrame scrolling; pull up of 5 fields to
[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
113               .createSequenceAnnotationReport(tip, sequence,
114               av.isShowDBRefs(), av.isShowNPFeats(),
115                       sp.seqCanvas.fr.getMinMax());
116       setToolTipText("<html>" + sequence.getDisplayId(true) + " "
117               + tip.toString() + "</html>");
118     }
119   }
120
121   /**
122    * Responds to a mouse drag by selecting the sequences under the dragged
123    * region.
124    * 
125    * @param e
126    */
127   @Override
128   public void mouseDragged(MouseEvent e)
129   {
130     mouseDragging = true;
131
132     int seq = Math.max(0, alignPanel.getSeqPanel().findSeq(e));
133
134     if (seq < lastid)
135     {
136       selectSeqs(lastid - 1, seq);
137     }
138     else if (seq > lastid)
139     {
140       selectSeqs(lastid + 1, seq);
141     }
142
143     lastid = seq;
144     alignPanel.paintAlignment(true);
145   }
146
147   /**
148    * Response to the mouse wheel by scrolling the alignment panel.
149    */
150   @Override
151   public void mouseWheelMoved(MouseWheelEvent e)
152   {
153     e.consume();
154     if (e.getWheelRotation() > 0)
155     {
156       if (e.isShiftDown())
157       {
158         alignPanel.scrollRight(true);
159       }
160       else
161       {
162         alignPanel.scrollUp(false);
163       }
164     }
165     else
166     {
167       if (e.isShiftDown())
168       {
169         alignPanel.scrollRight(false);
170       }
171       else
172       {
173         alignPanel.scrollUp(true);
174       }
175     }
176   }
177
178   /**
179    * Handle a mouse click event. Currently only responds to a double-click. The
180    * action is to try to open a browser window at a URL that searches for the
181    * selected sequence id. The search URL is configured in Preferences |
182    * Connections | URL link from Sequence ID. For example:
183    * 
184    * http://www.ebi.ac.uk/ebisearch/search.ebi?db=allebi&query=$SEQUENCE_ID$
185    * 
186    * @param e
187    */
188   @Override
189   public void mouseClicked(MouseEvent e)
190   {
191     /*
192      * Ignore single click. Ignore 'left' click followed by 'right' click (user
193      * selects a row then its pop-up menu).
194      */
195     if (e.getClickCount() < 2 || SwingUtilities.isRightMouseButton(e))
196     {
197       return;
198     }
199
200     Vector links = Preferences.sequenceURLLinks;
201     if (links == null || links.size() < 1)
202     {
203       return;
204     }
205
206     int seq = alignPanel.getSeqPanel().findSeq(e);
207     String url = null;
208     int i = 0;
209     String id = av.getAlignment().getSequenceAt(seq).getName();
210     while (url == null && i < links.size())
211     {
212       // DEFAULT LINK IS FIRST IN THE LINK LIST
213       // BUT IF ITS A REGEX AND DOES NOT MATCH THE NEXT ONE WILL BE TRIED
214       url = links.elementAt(i++).toString();
215       jalview.util.UrlLink urlLink = null;
216       try
217       {
218         urlLink = new UrlLink(url);
219       } catch (Exception foo)
220       {
221         jalview.bin.Cache.log.error("Exception for URLLink '" + url + "'",
222                 foo);
223         url = null;
224         continue;
225       }
226       ;
227       if (!urlLink.isValid())
228       {
229         jalview.bin.Cache.log.error(urlLink.getInvalidMessage());
230         url = null;
231         continue;
232       }
233
234       String urls[] = urlLink.makeUrls(id, true);
235       if (urls == null || urls[0] == null || urls[0].length() < 4)
236       {
237         url = null;
238         continue;
239       }
240       // just take first URL made from regex
241       url = urls[1];
242     }
243     try
244     {
245       jalview.util.BrowserLauncher.openURL(url);
246     } catch (Exception ex)
247     {
248       JOptionPane
249               .showInternalMessageDialog(
250                       Desktop.desktop,
251                       MessageManager.getString("label.web_browser_not_found_unix"),
252                       MessageManager.getString("label.web_browser_not_found"), 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     int seq = alignPanel.getSeqPanel().findSeq(e);
320
321     if (SwingUtilities.isRightMouseButton(e))
322     {
323       Sequence sq = (Sequence) av.getAlignment().getSequenceAt(seq);
324       // build a new links menu based on the current links + any non-positional
325       // features
326       Vector nlinks = new Vector(Preferences.sequenceURLLinks);
327       SequenceFeature sf[] = sq == null ? null : sq.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     // TODO is this addition ok here?
367     av.isSelectionGroupChanged(true);
368
369     alignPanel.paintAlignment(true);
370   }
371
372   /**
373    * Toggle whether the sequence is part of the current selection group.
374    * 
375    * @param seq
376    */
377   void selectSeq(int seq)
378   {
379     lastid = seq;
380
381     SequenceI pickedSeq = av.getAlignment().getSequenceAt(seq);
382     av.getSelectionGroup().addOrRemove(pickedSeq, true);
383   }
384
385   /**
386    * Add contiguous rows of the alignment to the current selection group. Does
387    * nothing if there is no selection group.
388    * 
389    * @param start
390    * @param end
391    */
392   void selectSeqs(int start, int end)
393   {
394     if (av.getSelectionGroup() == null)
395     {
396       return;
397     }
398
399     if (end >= av.getAlignment().getHeight())
400     {
401       end = av.getAlignment().getHeight() - 1;
402     }
403
404     lastid = start;
405
406     if (end < start)
407     {
408       int tmp = start;
409       start = end;
410       end = tmp;
411       lastid = end;
412     }
413
414     for (int i = start; i <= end; i++)
415     {
416       av.getSelectionGroup().addSequence(
417               av.getAlignment().getSequenceAt(i), i == end);
418     }
419   }
420
421   /**
422    * Respond to mouse released. Refreshes the display and triggers broadcast of
423    * the new selection group to any listeners.
424    * 
425    * @param e
426    */
427   @Override
428   public void mouseReleased(MouseEvent e)
429   {
430     if (scrollThread != null)
431     {
432       scrollThread.running = false;
433     }
434
435     mouseDragging = false;
436     PaintRefresher.Refresh(this, av.getSequenceSetId());
437     // always send selection message when mouse is released
438     av.sendSelection();
439   }
440
441   /**
442    * Highlight sequence ids that match the given list, and if necessary scroll
443    * to the start sequence of the list.
444    * 
445    * @param list
446    */
447   public void highlightSearchResults(List<SequenceI> list)
448   {
449     getIdCanvas().setHighlighted(list);
450
451     if (list == null)
452     {
453       return;
454     }
455
456     int index = av.getAlignment().findIndex(list.get(0));
457
458     // do we need to scroll the panel?
459     if ((av.getStartSeq() > index) || (av.getEndSeq() < index))
460     {
461       alignPanel.setScrollValues(av.getStartRes(), index);
462     }
463   }
464
465   public IdCanvas getIdCanvas()
466   {
467     return idCanvas;
468   }
469
470   public void setIdCanvas(IdCanvas idCanvas)
471   {
472     this.idCanvas = idCanvas;
473   }
474
475   // this class allows scrolling off the bottom of the visible alignment
476   class ScrollThread extends Thread
477   {
478     boolean running = false;
479
480     boolean up = true;
481
482     public ScrollThread(boolean up)
483     {
484       this.up = up;
485       start();
486     }
487
488     public void stopScrolling()
489     {
490       running = false;
491     }
492
493     @Override
494     public void run()
495     {
496       running = true;
497
498       while (running)
499       {
500         if (alignPanel.scrollUp(up))
501         {
502           // scroll was ok, so add new sequence to selection
503           int seq = av.getStartSeq();
504
505           if (!up)
506           {
507             seq = av.getEndSeq();
508           }
509
510           if (seq < lastid)
511           {
512             selectSeqs(lastid - 1, seq);
513           }
514           else if (seq > lastid)
515           {
516             selectSeqs(lastid + 1, seq);
517           }
518
519           lastid = seq;
520         }
521         else
522         {
523           running = false;
524         }
525
526         alignPanel.paintAlignment(false);
527
528         try
529         {
530           Thread.sleep(100);
531         } catch (Exception ex)
532         {
533         }
534       }
535     }
536   }
537 }