ensure all annotation dependent rendering gets refreshed
[jalview.git] / src / jalview / gui / AnnotationPanel.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.gui;
19
20 import java.awt.*;
21 import java.awt.event.*;
22 import java.awt.image.*;
23 import javax.swing.*;
24
25 import jalview.datamodel.*;
26 import jalview.renderer.AnnotationRenderer;
27 import jalview.renderer.AwtRenderPanelI;
28
29 /**
30  * DOCUMENT ME!
31  *
32  * @author $author$
33  * @version $Revision$
34  */
35 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
36         MouseListener, MouseMotionListener, ActionListener,
37         AdjustmentListener
38 {
39   final String HELIX = "Helix";
40
41   final String SHEET = "Sheet";
42
43   /**
44    * For RNA secondary structure "stems" aka helices
45    */
46   final String STEM = "RNA Helix";
47
48   final String LABEL = "Label";
49
50   final String REMOVE = "Remove Annotation";
51
52   final String COLOUR = "Colour";
53
54   public final Color HELIX_COLOUR = Color.red.darker();
55
56   public final Color SHEET_COLOUR = Color.green.darker().darker();
57
58   public final Color STEM_COLOUR = Color.blue.darker();
59
60   /** DOCUMENT ME!! */
61   public AlignViewport av;
62
63   AlignmentPanel ap;
64
65   public int activeRow = -1;
66
67   public BufferedImage image;
68
69   public volatile BufferedImage fadedImage;
70
71   Graphics2D gg;
72
73   public FontMetrics fm;
74
75   public int imgWidth = 0;
76
77   boolean fastPaint = false;
78
79   // Used For mouse Dragging and resizing graphs
80   int graphStretch = -1;
81
82   int graphStretchY = -1;
83
84   int min; // used by mouseDragged to see if user
85
86   int max; // used by mouseDragged to see if user
87
88   boolean mouseDragging = false;
89
90   boolean MAC = false;
91
92   // for editing cursor
93   int cursorX = 0;
94
95   int cursorY = 0;
96
97   public final AnnotationRenderer renderer;
98
99   /**
100    * Creates a new AnnotationPanel object.
101    *
102    * @param ap
103    *          DOCUMENT ME!
104    */
105   public AnnotationPanel(AlignmentPanel ap)
106   {
107
108     MAC = new jalview.util.Platform().isAMac();
109
110     ToolTipManager.sharedInstance().registerComponent(this);
111     ToolTipManager.sharedInstance().setInitialDelay(0);
112     ToolTipManager.sharedInstance().setDismissDelay(10000);
113     this.ap = ap;
114     av = ap.av;
115     this.setLayout(null);
116     addMouseListener(this);
117     addMouseMotionListener(this);
118     ap.annotationScroller.getVerticalScrollBar()
119             .addAdjustmentListener(this);
120     renderer = new AnnotationRenderer();
121   }
122
123   public AnnotationPanel(AlignViewport av)
124   {
125     this.av = av;
126     renderer = new AnnotationRenderer();
127   }
128
129   /**
130    * DOCUMENT ME!
131    *
132    * @param evt
133    *          DOCUMENT ME!
134    */
135   @Override
136   public void adjustmentValueChanged(AdjustmentEvent evt)
137   {
138     ap.alabels.setScrollOffset(-evt.getValue());
139   }
140
141   /**
142    * Calculates the height of the annotation displayed in the annotation panel.
143    * Callers should normally call the ap.adjustAnnotationHeight method to ensure
144    * all annotation associated components are updated correctly.
145    *
146    */
147   public int adjustPanelHeight()
148   {
149     int height = calcPanelHeight();
150     this.setPreferredSize(new Dimension(1, height));
151     if (ap != null)
152     {
153       // revalidate only when the alignment panel is fully constructed
154       ap.validate();
155     }
156
157     return height;
158   }
159
160   /**
161    * calculate the height for visible annotation, revalidating bounds where
162    * necessary ABSTRACT GUI METHOD
163    *
164    * @return total height of annotation
165    */
166   public int calcPanelHeight()
167   {
168     // setHeight of panels
169     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
170     int height = 0;
171
172     if (aa != null)
173     {
174       for (int i = 0; i < aa.length; i++)
175       {
176         if (aa[i] == null)
177         {
178           System.err.println("Null annotation row: ignoring.");
179           continue;
180         }
181         if (!aa[i].visible)
182         {
183           continue;
184         }
185
186         aa[i].height = 0;
187
188         if (aa[i].hasText)
189         {
190           aa[i].height += av.charHeight;
191         }
192
193         if (aa[i].hasIcons)
194         {
195           aa[i].height += 16;
196         }
197
198         if (aa[i].graph > 0)
199         {
200           aa[i].height += aa[i].graphHeight;
201         }
202
203         if (aa[i].height == 0)
204         {
205           aa[i].height = 20;
206         }
207
208         height += aa[i].height;
209       }
210     }
211     if (height == 0)
212     {
213       // set minimum
214       height = 20;
215     }
216     return height;
217   }
218
219   /**
220    * DOCUMENT ME!
221    *
222    * @param evt
223    *          DOCUMENT ME!
224    */
225   @Override
226   public void actionPerformed(ActionEvent evt)
227   {
228     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
229     if (aa == null)
230     {
231       return;
232     }
233     Annotation[] anot = aa[activeRow].annotations;
234
235     if (anot.length < av.getColumnSelection().getMax())
236     {
237       Annotation[] temp = new Annotation[av.getColumnSelection().getMax() + 2];
238       System.arraycopy(anot, 0, temp, 0, anot.length);
239       anot = temp;
240       aa[activeRow].annotations = anot;
241     }
242
243     if (evt.getActionCommand().equals(REMOVE))
244     {
245       for (int i = 0; i < av.getColumnSelection().size(); i++)
246       {
247         anot[av.getColumnSelection().columnAt(i)] = null;
248       }
249     }
250     else if (evt.getActionCommand().equals(LABEL))
251     {
252       String exMesg = collectAnnotVals(anot, av.getColumnSelection(), LABEL);
253       String label = JOptionPane.showInputDialog(this, "Enter label",
254               exMesg);
255
256       if (label == null)
257       {
258         return;
259       }
260
261       if ((label.length() > 0) && !aa[activeRow].hasText)
262       {
263         aa[activeRow].hasText = true;
264       }
265
266       for (int i = 0; i < av.getColumnSelection().size(); i++)
267       {
268         int index = av.getColumnSelection().columnAt(i);
269
270         if (!av.getColumnSelection().isVisible(index))
271           continue;
272
273         if (anot[index] == null)
274         {
275           anot[index] = new Annotation(label, "", ' ', 0); // TODO: verify that
276           // null exceptions
277           // aren't raised
278           // elsewhere.
279         }
280         else
281         {
282           anot[index].displayCharacter = label;
283         }
284       }
285     }
286     else if (evt.getActionCommand().equals(COLOUR))
287     {
288       Color col = JColorChooser.showDialog(this,
289               "Choose foreground colour", Color.black);
290
291       for (int i = 0; i < av.getColumnSelection().size(); i++)
292       {
293         int index = av.getColumnSelection().columnAt(i);
294
295         if (!av.getColumnSelection().isVisible(index))
296           continue;
297
298         if (anot[index] == null)
299         {
300           anot[index] = new Annotation("", "", ' ', 0);
301         }
302
303         anot[index].colour = col;
304       }
305     }
306     else
307     // HELIX OR SHEET
308     {
309       char type = 0;
310       String symbol = "\u03B1";
311
312       if (evt.getActionCommand().equals(HELIX))
313       {
314         type = 'H';
315       }
316       else if (evt.getActionCommand().equals(SHEET))
317       {
318         type = 'E';
319         symbol = "\u03B2";
320       }
321
322       // Added by LML to color stems
323       else if (evt.getActionCommand().equals(STEM))
324       {
325         type = 'S';
326         symbol = "\u03C3";
327       }
328
329       if (!aa[activeRow].hasIcons)
330       {
331         aa[activeRow].hasIcons = true;
332       }
333
334       String label = JOptionPane.showInputDialog(
335               "Enter a label for the structure?", symbol);
336
337       if (label == null)
338       {
339         return;
340       }
341
342       if ((label.length() > 0) && !aa[activeRow].hasText)
343       {
344         aa[activeRow].hasText = true;
345       }
346
347       for (int i = 0; i < av.getColumnSelection().size(); i++)
348       {
349         int index = av.getColumnSelection().columnAt(i);
350
351         if (!av.getColumnSelection().isVisible(index))
352           continue;
353
354         if (anot[index] == null)
355         {
356           anot[index] = new Annotation(label, "", type, 0);
357         }
358
359         anot[index].secondaryStructure = type;
360         anot[index].displayCharacter = label;
361       }
362     }
363     aa[activeRow].validateRangeAndDisplay();
364
365     adjustPanelHeight();
366     ap.alignmentChanged();
367     repaint();
368
369     return;
370   }
371
372   private String collectAnnotVals(Annotation[] anot,
373           ColumnSelection columnSelection, String label2)
374   {
375     String collatedInput = "";
376     String last = "";
377     ColumnSelection viscols=av.getColumnSelection();
378     // TODO: refactor and save av.getColumnSelection for efficiency
379     for (int i = 0; i < columnSelection.size(); i++)
380     {
381       int index = columnSelection.columnAt(i);
382       // always check for current display state - just in case
383       if (!viscols.isVisible(index))
384         continue;
385       String tlabel = null;
386       if (anot[index] != null)
387       { // LML added stem code
388         if (label2.equals(HELIX) || label2.equals(SHEET)
389                 || label2.equals(STEM) || label2.equals(LABEL))
390         {
391           tlabel = anot[index].description;
392           if (tlabel == null || tlabel.length() < 1)
393           {
394             if (label2.equals(HELIX) || label2.equals(SHEET)
395                     || label2.equals(STEM))
396             {
397               tlabel = "" + anot[index].secondaryStructure;
398             }
399             else
400             {
401               tlabel = "" + anot[index].displayCharacter;
402             }
403           }
404         }
405         if (tlabel != null && !tlabel.equals(last))
406         {
407           if (last.length() > 0)
408           {
409             collatedInput += " ";
410           }
411           collatedInput += tlabel;
412         }
413       }
414     }
415     return collatedInput;
416   }
417
418   /**
419    * DOCUMENT ME!
420    *
421    * @param evt
422    *          DOCUMENT ME!
423    */
424   @Override
425   public void mousePressed(MouseEvent evt)
426   {
427
428     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
429     if (aa == null)
430     {
431       return;
432     }
433
434     int height = 0;
435     activeRow = -1;
436
437     for (int i = 0; i < aa.length; i++)
438     {
439       if (aa[i].visible)
440       {
441         height += aa[i].height;
442       }
443
444       if (evt.getY() < height)
445       {
446         if (aa[i].editable)
447         {
448           activeRow = i;
449         }
450         else if (aa[i].graph > 0)
451         {
452           // Stretch Graph
453           graphStretch = i;
454           graphStretchY = evt.getY();
455         }
456
457         break;
458       }
459     }
460
461     if (SwingUtilities.isRightMouseButton(evt) && activeRow != -1)
462     {
463       if (av.getColumnSelection() == null)
464       {
465         return;
466       }
467
468       JPopupMenu pop = new JPopupMenu("Structure type");
469       JMenuItem item;
470       /*
471        * Just display the needed structure options
472        */
473       if (av.getAlignment().isNucleotide() == true)
474       {
475         item = new JMenuItem(STEM);
476         item.addActionListener(this);
477         pop.add(item);
478       }
479       else
480       {
481         item = new JMenuItem(HELIX);
482         item.addActionListener(this);
483         pop.add(item);
484         item = new JMenuItem(SHEET);
485         item.addActionListener(this);
486         pop.add(item);
487       }
488       item = new JMenuItem(LABEL);
489       item.addActionListener(this);
490       pop.add(item);
491       item = new JMenuItem(COLOUR);
492       item.addActionListener(this);
493       pop.add(item);
494       item = new JMenuItem(REMOVE);
495       item.addActionListener(this);
496       pop.add(item);
497       pop.show(this, evt.getX(), evt.getY());
498
499       return;
500     }
501
502     if (aa == null)
503     {
504       return;
505     }
506
507     ap.scalePanel.mousePressed(evt);
508
509   }
510
511   /**
512    * DOCUMENT ME!
513    *
514    * @param evt
515    *          DOCUMENT ME!
516    */
517   @Override
518   public void mouseReleased(MouseEvent evt)
519   {
520     graphStretch = -1;
521     graphStretchY = -1;
522     mouseDragging = false;
523     ap.scalePanel.mouseReleased(evt);
524   }
525
526   /**
527    * DOCUMENT ME!
528    *
529    * @param evt
530    *          DOCUMENT ME!
531    */
532   @Override
533   public void mouseEntered(MouseEvent evt)
534   {
535     ap.scalePanel.mouseEntered(evt);
536   }
537
538   /**
539    * DOCUMENT ME!
540    *
541    * @param evt
542    *          DOCUMENT ME!
543    */
544   @Override
545   public void mouseExited(MouseEvent evt)
546   {
547     ap.scalePanel.mouseExited(evt);
548   }
549
550   /**
551    * DOCUMENT ME!
552    *
553    * @param evt
554    *          DOCUMENT ME!
555    */
556   @Override
557   public void mouseDragged(MouseEvent evt)
558   {
559     if (graphStretch > -1)
560     {
561       av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
562               - evt.getY();
563       if (av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight < 0)
564       {
565         av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight = 0;
566       }
567       graphStretchY = evt.getY();
568       adjustPanelHeight();
569       ap.paintAlignment(true);
570     }
571     else
572     {
573       ap.scalePanel.mouseDragged(evt);
574     }
575   }
576
577   /**
578    * DOCUMENT ME!
579    *
580    * @param evt
581    *          DOCUMENT ME!
582    */
583   @Override
584   public void mouseMoved(MouseEvent evt)
585   {
586     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
587
588     if (aa == null)
589     {
590       this.setToolTipText(null);
591       return;
592     }
593
594     int row = -1;
595     int height = 0;
596
597     for (int i = 0; i < aa.length; i++)
598     {
599       if (aa[i].visible)
600       {
601         height += aa[i].height;
602       }
603
604       if (evt.getY() < height)
605       {
606         row = i;
607
608         break;
609       }
610     }
611
612     if (row == -1)
613     {
614       this.setToolTipText(null);
615       return;
616     }
617
618     int res = (evt.getX() / av.getCharWidth()) + av.getStartRes();
619
620     if (av.hasHiddenColumns())
621     {
622       res = av.getColumnSelection().adjustForHiddenColumns(res);
623     }
624
625     if (row > -1 && aa[row].annotations != null
626             && res < aa[row].annotations.length)
627     {
628       if (aa[row].graphGroup > -1)
629       {
630         StringBuffer tip = new StringBuffer("<html>");
631         for (int gg = 0; gg < aa.length; gg++)
632         {
633           if (aa[gg].graphGroup == aa[row].graphGroup
634                   && aa[gg].annotations[res] != null)
635           {
636             tip.append(aa[gg].label + " "
637                     + aa[gg].annotations[res].description + "<br>");
638           }
639         }
640         if (tip.length() != 6)
641         {
642           tip.setLength(tip.length() - 4);
643           this.setToolTipText(tip.toString() + "</html>");
644         }
645       }
646       else if (aa[row].annotations[res] != null
647               && aa[row].annotations[res].description != null
648               && aa[row].annotations[res].description.length() > 0)
649       {
650         this.setToolTipText(aa[row].annotations[res].description);
651       }
652       else
653       {
654         // clear the tooltip.
655         this.setToolTipText(null);
656       }
657
658       if (aa[row].annotations[res] != null)
659       {
660         StringBuffer text = new StringBuffer("Sequence position "
661                 + (res + 1));
662
663         if (aa[row].annotations[res].description != null)
664         {
665           text.append("  " + aa[row].annotations[res].description);
666         }
667
668         ap.alignFrame.statusBar.setText(text.toString());
669       }
670     }
671     else
672     {
673       this.setToolTipText(null);
674     }
675   }
676
677   /**
678    * DOCUMENT ME!
679    *
680    * @param evt
681    *          DOCUMENT ME!
682    */
683   @Override
684   public void mouseClicked(MouseEvent evt)
685   {
686     if (activeRow != -1)
687     {
688       AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
689       AlignmentAnnotation anot = aa[activeRow];
690
691       if (anot.description.equals("secondary structure"))
692       {
693         // System.out.println(anot.description+" "+anot.getRNAStruc());
694       }
695     }
696   }
697
698   // TODO mouseClicked-content and drawCursor are quite experimental!
699   public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
700           int y1)
701   {
702     int pady = av.charHeight / 5;
703     int charOffset = 0;
704     graphics.setColor(Color.black);
705     graphics.fillRect(x1, y1, av.charWidth, av.charHeight);
706
707     if (av.validCharWidth)
708     {
709       graphics.setColor(Color.white);
710
711       char s = seq.getCharAt(res);
712
713       charOffset = (av.charWidth - fm.charWidth(s)) / 2;
714       graphics.drawString(String.valueOf(s), charOffset + x1,
715               (y1 + av.charHeight) - pady);
716     }
717
718   }
719   private volatile boolean imageFresh=false;
720   /**
721    * DOCUMENT ME!
722    *
723    * @param g
724    *          DOCUMENT ME!
725    */
726   @Override
727   public void paintComponent(Graphics g)
728   {
729     g.setColor(Color.white);
730     g.fillRect(0, 0, getWidth(), getHeight());
731
732     if (image != null)
733     {
734       if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
735               || (getVisibleRect().height != g.getClipBounds().height))
736       {
737         g.drawImage(image, 0, 0, this);
738         fastPaint = false;
739         return;
740       }
741     }
742     imgWidth = (av.endRes - av.startRes + 1) * av.charWidth;
743     if (imgWidth < 1)
744       return;
745     if (image == null || imgWidth != image.getWidth()
746             || image.getHeight(this) != getHeight())
747     {
748       image = new BufferedImage(imgWidth, ap.annotationPanel.getHeight(),
749               BufferedImage.TYPE_INT_RGB);
750       gg = (Graphics2D) image.getGraphics();
751
752       if (av.antiAlias)
753       {
754         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
755                 RenderingHints.VALUE_ANTIALIAS_ON);
756       }
757
758       gg.setFont(av.getFont());
759       fm = gg.getFontMetrics();
760       gg.setColor(Color.white);
761       gg.fillRect(0, 0, imgWidth, image.getHeight());
762       imageFresh=true;
763     }
764
765     drawComponent(gg, av.startRes, av.endRes + 1);
766     imageFresh=false;
767     g.drawImage(image, 0, 0, this);
768   }
769
770   /**
771    * non-Thread safe repaint
772    *
773    * @param horizontal
774    *          repaint with horizontal shift in alignment
775    */
776   public void fastPaint(int horizontal)
777   {
778
779     if ((horizontal == 0) || gg == null
780             || av.getAlignment().getAlignmentAnnotation() == null
781             || av.getAlignment().getAlignmentAnnotation().length < 1
782             || av.isCalcInProgress())
783     {
784       repaint();
785       return;
786     }
787     gg.copyArea(0, 0, imgWidth, getHeight(), -horizontal * av.charWidth, 0);
788
789     int sr = av.startRes;
790     int er = av.endRes + 1;
791     int transX = 0;
792
793     if (horizontal > 0) // scrollbar pulled right, image to the left
794     {
795       transX = (er - sr - horizontal) * av.charWidth;
796       sr = er - horizontal;
797     }
798     else if (horizontal < 0)
799     {
800       er = sr - horizontal;
801     }
802
803     gg.translate(transX, 0);
804
805     drawComponent(gg, sr, er);
806
807     gg.translate(-transX, 0);
808
809     fastPaint = true;
810     repaint();
811
812   }
813   private volatile boolean lastImageGood=false;
814   /**
815    * DOCUMENT ME!
816    *
817    * @param g
818    *          DOCUMENT ME!
819    * @param startRes
820    *          DOCUMENT ME!
821    * @param endRes
822    *          DOCUMENT ME!
823    */
824   public void drawComponent(Graphics g, int startRes, int endRes)
825   {
826     BufferedImage oldFaded=fadedImage;
827     if (av.isCalcInProgress())
828     {
829       if (image == null)
830       {
831         lastImageGood=false;
832         return;
833       }
834       // We'll keep a record of the old image,
835       // and draw a faded image until the calculation
836       // has completed
837       if (lastImageGood && (fadedImage == null || fadedImage.getWidth() != imgWidth
838               || fadedImage.getHeight() != image.getHeight()))
839       {
840 //        System.err.println("redraw faded image ("+(fadedImage==null ? "null image" : "") + " lastGood="+lastImageGood+")");
841         fadedImage = new BufferedImage(imgWidth, image.getHeight(),
842                 BufferedImage.TYPE_INT_RGB);
843
844         Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
845
846         fadedG.setColor(Color.white);
847         fadedG.fillRect(0, 0, imgWidth, image.getHeight());
848
849         fadedG.setComposite(AlphaComposite.getInstance(
850                 AlphaComposite.SRC_OVER, .3f));
851         fadedG.drawImage(image, 0, 0, this);
852
853       }
854       // make sure we don't overwrite the last good faded image until all calculations have finished
855       lastImageGood=false;
856
857     }
858     else
859     {
860       if (fadedImage!=null)
861       {
862         oldFaded=fadedImage;
863       }
864       fadedImage = null;
865     }
866
867     g.setColor(Color.white);
868     g.fillRect(0, 0, (endRes - startRes) * av.charWidth, getHeight());
869
870     g.setFont(av.getFont());
871     if (fm == null)
872     {
873       fm = g.getFontMetrics();
874     }
875
876     if ((av.getAlignment().getAlignmentAnnotation() == null)
877             || (av.getAlignment().getAlignmentAnnotation().length < 1))
878     {
879       g.setColor(Color.white);
880       g.fillRect(0, 0, getWidth(), getHeight());
881       g.setColor(Color.black);
882       if (av.validCharWidth)
883       {
884         g.drawString("Alignment has no annotations", 20, 15);
885       }
886
887       return;
888     }
889     lastImageGood = renderer.drawComponent(this, av, g, activeRow, startRes, endRes);
890     if (!lastImageGood && fadedImage==null)
891     {
892       fadedImage=oldFaded;
893     }
894   }
895
896   @Override
897   public FontMetrics getFontMetrics()
898   {
899     return fm;
900   }
901
902   @Override
903   public Image getFadedImage()
904   {
905     return fadedImage;
906   }
907
908   @Override
909   public int getFadedImageWidth()
910   {
911     return imgWidth;
912   }
913 }