update author list in license for (JAL-826)
[jalview.git] / src / jalview / appletgui / AnnotationLabels.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.appletgui;
19
20 import java.util.*;
21
22 import java.awt.*;
23 import java.awt.event.*;
24 import java.awt.image.BufferedImage;
25
26 import jalview.datamodel.*;
27 import jalview.util.ParseHtmlBodyAndLinks;
28
29 public class AnnotationLabels extends Panel implements ActionListener,
30         MouseListener, MouseMotionListener
31 {
32   Image image;
33
34   boolean active = false;
35
36   AlignmentPanel ap;
37
38   AlignViewport av;
39
40   boolean resizing = false;
41
42   int oldY, mouseX;
43
44   static String ADDNEW = "Add New Row";
45
46   static String EDITNAME = "Edit Label/Description";
47
48   static String HIDE = "Hide This Row";
49
50   static String SHOWALL = "Show All Hidden Rows";
51
52   static String OUTPUT_TEXT = "Show Values In Textbox";
53
54   static String COPYCONS_SEQ = "Copy Consensus Sequence";
55
56   int scrollOffset = 0;
57
58   int selectedRow = -1;
59
60   Tooltip tooltip;
61
62   private boolean hasHiddenRows;
63
64   public AnnotationLabels(AlignmentPanel ap)
65   {
66     this.ap = ap;
67     this.av = ap.av;
68     setLayout(null);
69
70     /**
71      * this retrieves the adjustable height glyph from resources. we don't use
72      * it at the moment. java.net.URL url =
73      * getClass().getResource("/images/idwidth.gif"); Image temp = null;
74      * 
75      * if (url != null) { temp =
76      * java.awt.Toolkit.getDefaultToolkit().createImage(url); }
77      * 
78      * try { MediaTracker mt = new MediaTracker(this); mt.addImage(temp, 0);
79      * mt.waitForID(0); } catch (Exception ex) { }
80      * 
81      * BufferedImage bi = new BufferedImage(temp.getHeight(this),
82      * temp.getWidth(this), BufferedImage.TYPE_INT_RGB); Graphics2D g =
83      * (Graphics2D) bi.getGraphics(); g.rotate(Math.toRadians(90));
84      * g.drawImage(temp, 0, -bi.getWidth(this), this); image = (Image) bi;
85      */
86     addMouseListener(this);
87     addMouseMotionListener(this);
88   }
89
90   public AnnotationLabels(AlignViewport av)
91   {
92     this.av = av;
93   }
94
95   public void setScrollOffset(int y)
96   {
97     scrollOffset = y;
98     repaint();
99   }
100
101   /**
102    * 
103    * @param y
104    * @return -2 if no rows are visible at all, -1 if no visible rows were
105    *         selected
106    */
107   int getSelectedRow(int y)
108   {
109     int row = -2;
110     AlignmentAnnotation[] aa = ap.av.alignment.getAlignmentAnnotation();
111
112     if (aa == null)
113     {
114       return row;
115     }
116     int height = 0;
117     for (int i = 0; i < aa.length; i++)
118     {
119       row = -1;
120       if (!aa[i].visible)
121       {
122         continue;
123       }
124       height += aa[i].height;
125       if (y < height)
126       {
127         row = i;
128         break;
129       }
130     }
131
132     return row;
133   }
134
135   public void actionPerformed(ActionEvent evt)
136   {
137     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
138
139     if (evt.getActionCommand().equals(ADDNEW))
140     {
141       AlignmentAnnotation newAnnotation = new AlignmentAnnotation("", null,
142               new Annotation[ap.av.alignment.getWidth()]);
143
144       if (!editLabelDescription(newAnnotation))
145       {
146         return;
147       }
148
149       ap.av.alignment.addAnnotation(newAnnotation);
150       ap.av.alignment.setAnnotationIndex(newAnnotation, 0);
151     }
152     else if (evt.getActionCommand().equals(EDITNAME))
153     {
154       editLabelDescription(aa[selectedRow]);
155     }
156     else if (evt.getActionCommand().equals(HIDE))
157     {
158       aa[selectedRow].visible = false;
159     }
160     else if (evt.getActionCommand().equals(SHOWALL))
161     {
162       for (int i = 0; i < aa.length; i++)
163       {
164         aa[i].visible = (aa[i].annotations == null) ? false : true;
165       }
166     }
167     else if (evt.getActionCommand().equals(OUTPUT_TEXT))
168     {
169       CutAndPasteTransfer cap = new CutAndPasteTransfer(false,
170               ap.alignFrame);
171       Frame frame = new Frame();
172       frame.add(cap);
173       jalview.bin.JalviewLite.addFrame(frame, ap.alignFrame.getTitle()
174               + " - " + aa[selectedRow].label, 500, 100);
175       cap.setText(aa[selectedRow].toString());
176     }
177     else if (evt.getActionCommand().equals(COPYCONS_SEQ))
178     {
179       SequenceI cons = av.getConsensusSeq();
180       if (cons != null)
181       {
182         copy_annotseqtoclipboard(cons);
183       }
184
185     }
186     ap.annotationPanel.adjustPanelHeight();
187     setSize(getSize().width, ap.annotationPanel.getSize().height);
188     ap.validate();
189     ap.paintAlignment(true);
190   }
191
192   boolean editLabelDescription(AlignmentAnnotation annotation)
193   {
194     Checkbox padGaps = new Checkbox("Fill Empty Gaps With \""
195             + ap.av.getGapCharacter() + "\"", annotation.padGaps);
196
197     EditNameDialog dialog = new EditNameDialog(annotation.label,
198             annotation.description, "      Annotation Label",
199             "Annotation Description", ap.alignFrame,
200             "Edit Annotation Name / Description", 500, 180, false);
201
202     Panel empty = new Panel(new FlowLayout());
203     empty.add(padGaps);
204     dialog.add(empty);
205     dialog.pack();
206
207     dialog.setVisible(true);
208
209     if (dialog.accept)
210     {
211       annotation.label = dialog.getName();
212       annotation.description = dialog.getDescription();
213       annotation.setPadGaps(padGaps.getState(), av.getGapCharacter());
214       repaint();
215       return true;
216     }
217     else
218       return false;
219
220   }
221
222   boolean resizePanel = false;
223
224   public void mouseMoved(MouseEvent evt)
225   {
226     resizePanel = evt.getY() < 10 && evt.getX() < 14;
227     int row = getSelectedRow(evt.getY() + scrollOffset);
228
229     if (row > -1)
230     {
231       ParseHtmlBodyAndLinks phb = new ParseHtmlBodyAndLinks(av.alignment.getAlignmentAnnotation()[row].getDescription(true), true, "\n");
232       if (tooltip == null)
233       {
234         tooltip = new Tooltip(phb.getNonHtmlContent(), this);
235       }
236       else
237       {
238         tooltip.setTip(phb.getNonHtmlContent());
239       }
240     }
241     else if (tooltip != null)
242     {
243       tooltip.setTip("");
244     }
245   }
246
247   /**
248    * curent drag position
249    */
250   MouseEvent dragEvent = null;
251
252   /**
253    * flag to indicate drag events should be ignored
254    */
255   private boolean dragCancelled = false;
256
257   /**
258    * clear any drag events in progress
259    */
260   public void cancelDrag()
261   {
262     dragEvent = null;
263     dragCancelled = true;
264   }
265
266   public void mouseDragged(MouseEvent evt)
267   {
268     if (dragCancelled)
269     {
270       return;
271     }
272     ;
273     dragEvent = evt;
274
275     if (resizePanel)
276     {
277       Dimension d = ap.annotationPanelHolder.getSize(), e = ap.annotationSpaceFillerHolder
278               .getSize(), f = ap.seqPanelHolder.getSize();
279       int dif = evt.getY() - oldY;
280
281       dif /= ap.av.charHeight;
282       dif *= ap.av.charHeight;
283
284       if ((d.height - dif) > 20 && (f.height + dif) > 20)
285       {
286         ap.annotationPanel.setSize(d.width, d.height - dif);
287         setSize(new Dimension(e.width, d.height - dif));
288         ap.annotationSpaceFillerHolder.setSize(new Dimension(e.width,
289                 d.height - dif));
290         ap.annotationPanelHolder.setSize(new Dimension(d.width, d.height
291                 - dif));
292         ap.apvscroll.setValues(ap.apvscroll.getValue(), d.height - dif, 0,
293                 ap.annotationPanel.calcPanelHeight());
294         f.height += dif;
295         ap.seqPanelHolder.setPreferredSize(f);
296         ap.setScrollValues(av.getStartRes(), av.getStartSeq());
297         ap.validate();
298         // ap.paintAlignment(true);
299         ap.addNotify();
300       }
301
302     }
303     else
304     {
305       int diff;
306       if ((diff = 6 - evt.getY()) > 0)
307       {
308         // nudge scroll up
309         ap.apvscroll.setValue(ap.apvscroll.getValue() - diff);
310         ap.adjustmentValueChanged(null);
311
312       }
313       else if ((0 < (diff = 6
314               - ap.annotationSpaceFillerHolder.getSize().height
315               + evt.getY())))
316       {
317         // nudge scroll down
318         ap.apvscroll.setValue(ap.apvscroll.getValue() + diff);
319         ap.adjustmentValueChanged(null);
320       }
321       repaint();
322     }
323   }
324
325   public void mouseClicked(MouseEvent evt)
326   {
327   }
328
329   public void mouseReleased(MouseEvent evt)
330   {
331     if (!resizePanel && !dragCancelled)
332     {
333       int start = selectedRow;
334
335       int end = getSelectedRow(evt.getY() + scrollOffset);
336
337       if (start>-1 && start != end)
338       {
339         // Swap these annotations
340         AlignmentAnnotation startAA = ap.av.alignment
341                 .getAlignmentAnnotation()[start];
342         if (end == -1)
343         {
344           end = ap.av.alignment.getAlignmentAnnotation().length - 1;
345         }
346         AlignmentAnnotation endAA = ap.av.alignment
347                 .getAlignmentAnnotation()[end];
348
349         ap.av.alignment.getAlignmentAnnotation()[end] = startAA;
350         ap.av.alignment.getAlignmentAnnotation()[start] = endAA;
351       }
352     }
353     resizePanel = false;
354     dragEvent = null;
355     dragCancelled = false;
356     repaint();
357     ap.annotationPanel.repaint();
358   }
359
360   public void mouseEntered(MouseEvent evt)
361   {
362     if (evt.getY() < 10 && evt.getX() < 14)
363     {
364       resizePanel = true;
365       repaint();
366     }
367   }
368
369   public void mouseExited(MouseEvent evt)
370   {
371     dragCancelled = false;
372
373     if (dragEvent == null)
374     {
375       resizePanel = false;
376     }
377     else
378     {
379       if (!resizePanel)
380       {
381         dragEvent = null;
382       }
383     }
384     repaint();
385   }
386
387   public void mousePressed(MouseEvent evt)
388   {
389     oldY = evt.getY();
390     if (resizePanel)
391     {
392       return;
393     }
394     dragCancelled=false;
395     // todo: move below to mouseClicked ?
396     selectedRow = getSelectedRow(evt.getY() + scrollOffset);
397
398     AlignmentAnnotation[] aa = ap.av.alignment.getAlignmentAnnotation();
399
400     // DETECT RIGHT MOUSE BUTTON IN AWT
401     if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK)
402     {
403
404       PopupMenu popup = new PopupMenu("Annotations");
405
406       MenuItem item = new MenuItem(ADDNEW);
407       item.addActionListener(this);
408       popup.add(item);
409       if (selectedRow < 0)
410       {
411         // this never happens at moment: - see comment on JAL-563
412         if (hasHiddenRows)
413         {
414           item = new MenuItem(SHOWALL);
415           item.addActionListener(this);
416           popup.add(item);
417         }
418         this.add(popup);
419         popup.show(this, evt.getX(), evt.getY());
420         return;
421       }
422       // add the rest if there are actually rows to show
423       item = new MenuItem(EDITNAME);
424       item.addActionListener(this);
425       popup.add(item);
426       item = new MenuItem(HIDE);
427       item.addActionListener(this);
428       popup.add(item);
429       if (hasHiddenRows)
430       {
431         item = new MenuItem(SHOWALL);
432         item.addActionListener(this);
433         popup.add(item);
434       }
435       this.add(popup);
436       item = new MenuItem(OUTPUT_TEXT);
437       item.addActionListener(this);
438       popup.add(item);
439       if (selectedRow < aa.length)
440       {
441         if (aa[selectedRow].autoCalculated)
442         {
443           if (aa[selectedRow].label.indexOf("Consensus") > -1)
444           {
445             popup.addSeparator();
446             final CheckboxMenuItem cbmi = new CheckboxMenuItem(
447                     "Ignore Gaps In Consensus",
448                     (aa[selectedRow].groupRef != null) ? aa[selectedRow].groupRef
449                             .getIgnoreGapsConsensus() : ap.av
450                             .getIgnoreGapsConsensus());
451             final AlignmentAnnotation aaa = aa[selectedRow];
452             cbmi.addItemListener(new ItemListener()
453             {
454               public void itemStateChanged(ItemEvent e)
455               {
456                 if (aaa.groupRef != null)
457                 {
458                   // TODO: pass on reference to ap so the view can be updated.
459                   aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
460                 }
461                 else
462                 {
463                   ap.av.setIgnoreGapsConsensus(cbmi.getState());
464                 }
465                 ap.paintAlignment(true);
466               }
467             });
468             popup.add(cbmi);
469             if (aaa.groupRef != null)
470             {
471               final CheckboxMenuItem chist = new CheckboxMenuItem(
472                       "Show Group Histogram",
473                       aa[selectedRow].groupRef.isShowConsensusHistogram());
474               chist.addItemListener(new ItemListener()
475               {
476                 public void itemStateChanged(ItemEvent e)
477                 {
478                   // TODO: pass on reference
479                   // to ap
480                   // so the
481                   // view
482                   // can be
483                   // updated.
484                   aaa.groupRef.setShowConsensusHistogram(chist.getState());
485                   ap.repaint();
486                   // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
487                 }
488               });
489               popup.add(chist);
490               final CheckboxMenuItem cprofl = new CheckboxMenuItem(
491                       "Show Group Logo",
492                       aa[selectedRow].groupRef.isShowSequenceLogo());
493               cprofl.addItemListener(new ItemListener()
494               {
495                 public void itemStateChanged(ItemEvent e)
496                 {
497                   // TODO: pass on reference
498                   // to ap
499                   // so the
500                   // view
501                   // can be
502                   // updated.
503                   aaa.groupRef.setshowSequenceLogo(cprofl.getState());
504                   ap.repaint();
505                   // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
506                 }
507               });
508               popup.add(cprofl);
509             }
510             else
511             {
512               final CheckboxMenuItem chist = new CheckboxMenuItem(
513                       "Show Histogram", av.isShowConsensusHistogram());
514               chist.addItemListener(new ItemListener()
515               {
516                 public void itemStateChanged(ItemEvent e)
517                 {
518                   // TODO: pass on reference
519                   // to ap
520                   // so the
521                   // view
522                   // can be
523                   // updated.
524                   av.setShowConsensusHistogram(chist.getState());
525                   ap.repaint();
526                   // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
527                 }
528               });
529               popup.add(chist);
530               final CheckboxMenuItem cprof = new CheckboxMenuItem(
531                       "Show Logo", av.isShowSequenceLogo());
532               cprof.addItemListener(new ItemListener()
533               {
534                 public void itemStateChanged(ItemEvent e)
535                 {
536                   // TODO: pass on reference
537                   // to ap
538                   // so the
539                   // view
540                   // can be
541                   // updated.
542                   av.setShowSequenceLogo(cprof.getState());
543                   ap.repaint();
544                   // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
545                 }
546               });
547               popup.add(cprof);
548             }
549
550             item = new MenuItem(COPYCONS_SEQ);
551             item.addActionListener(this);
552             popup.add(item);
553           }
554         }
555       }
556       popup.show(this, evt.getX(), evt.getY());
557     }
558     else
559     {
560       // selection action.
561       if (selectedRow > -1 && selectedRow < aa.length)
562       {
563         if (aa[selectedRow].groupRef != null)
564         {
565           if (evt.getClickCount() >= 2)
566           {
567             // todo: make the ap scroll to the selection - not necessary, first
568             // click highlights/scrolls, second selects
569             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
570             ap.av.setSelectionGroup(// new SequenceGroup(
571             aa[selectedRow].groupRef); // );
572             ap.av.sendSelection();
573             ap.paintAlignment(false);
574             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
575           }
576           else
577           {
578             ap.seqPanel.ap.idPanel
579                     .highlightSearchResults(aa[selectedRow].groupRef
580                             .getSequences(null));
581           }
582           return;
583         }
584         else if (aa[selectedRow].sequenceRef != null)
585         {
586           Vector sr = new Vector();
587           sr.addElement(aa[selectedRow].sequenceRef);
588           if (evt.getClickCount() == 1)
589           {
590             ap.seqPanel.ap.idPanel.highlightSearchResults(sr);
591           }
592           else if (evt.getClickCount() >= 2)
593           {
594             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
595             SequenceGroup sg = new SequenceGroup();
596             sg.addSequence(aa[selectedRow].sequenceRef, false);
597             ap.av.setSelectionGroup(sg);
598             ap.paintAlignment(false);
599             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
600             ap.av.sendSelection();
601           }
602
603         }
604       }
605
606     }
607   }
608
609   /**
610    * DOCUMENT ME!
611    * 
612    * @param e
613    *          DOCUMENT ME!
614    */
615   protected void copy_annotseqtoclipboard(SequenceI sq)
616   {
617     if (sq == null || sq.getLength() < 1)
618     {
619       return;
620     }
621     jalview.appletgui.AlignFrame.copiedSequences = new StringBuffer();
622     jalview.appletgui.AlignFrame.copiedSequences.append(sq.getName() + "\t"
623             + sq.getStart() + "\t" + sq.getEnd() + "\t"
624             + sq.getSequenceAsString() + "\n");
625     if (av.hasHiddenColumns)
626     {
627       jalview.appletgui.AlignFrame.copiedHiddenColumns = new Vector();
628       for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
629       {
630         int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
631                 .elementAt(i);
632
633         jalview.appletgui.AlignFrame.copiedHiddenColumns
634                 .addElement(new int[]
635                 { region[0], region[1] });
636       }
637     }
638   }
639
640   public void update(Graphics g)
641   {
642     paint(g);
643   }
644
645   public void paint(Graphics g)
646   {
647     int w = getSize().width;
648     int h = getSize().height;
649     if (image == null || w != image.getWidth(this) || h!=image.getHeight(this) )
650     {
651       image = createImage(w, ap.annotationPanel.getSize().height);
652     }
653
654     drawComponent(image.getGraphics(), w);
655     g.drawImage(image, 0, 0, this);
656   }
657
658   public void drawComponent(Graphics g, int width)
659   {
660     g.setFont(av.getFont());
661     FontMetrics fm = g.getFontMetrics(av.getFont());
662     g.setColor(Color.white);
663     g.fillRect(0, 0, getSize().width, getSize().height);
664
665     g.translate(0, -scrollOffset);
666     g.setColor(Color.black);
667
668     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
669     int y = 0, fy = g.getFont().getSize();
670     int x = 0, offset;
671
672     if (aa != null)
673     {
674       hasHiddenRows = false;
675       for (int i = 0; i < aa.length; i++)
676       {
677         if (!aa[i].visible)
678         {
679           hasHiddenRows = true;
680           continue;
681         }
682
683         x = width - fm.stringWidth(aa[i].label) - 3;
684
685         y += aa[i].height;
686         offset = -(aa[i].height - fy) / 2;
687
688         g.drawString(aa[i].label, x, y + offset);
689       }
690     }
691     g.translate(0, +scrollOffset);
692     if (resizePanel)
693     {
694       g.setColor(Color.red);
695       g.setPaintMode();
696       g.drawLine(2, 8, 5, 2);
697       g.drawLine(5, 2, 8, 8);
698     }
699     else if (!dragCancelled && dragEvent != null && aa != null)
700     {
701       g.setColor(Color.lightGray);
702       g.drawString(aa[selectedRow].label, dragEvent.getX(),
703               dragEvent.getY());
704     }
705
706     if ((aa == null) || (aa.length < 1))
707     {
708       g.setColor(Color.black);
709       g.drawString("Right click", 2, 8);
710       g.drawString("to add annotation", 2, 18);
711     }
712   }
713 }