JAL-3446 defer size calculations until panel added to window
[jalview.git] / src / jalview / gui / IdCanvas.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.SequenceI;
24 import jalview.viewmodel.ViewportListenerI;
25 import jalview.viewmodel.ViewportRanges;
26
27 import java.awt.BorderLayout;
28 import java.awt.Color;
29 import java.awt.Font;
30 import java.awt.FontMetrics;
31 import java.awt.Graphics;
32 import java.awt.Graphics2D;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.beans.PropertyChangeEvent;
36 import java.util.List;
37
38 import javax.swing.JPanel;
39
40 /**
41  * DOCUMENT ME!
42  * 
43  * @author $author$
44  * @version $Revision$
45  */
46 public class IdCanvas extends JPanel implements ViewportListenerI
47 {
48   protected AlignViewport av;
49
50   protected boolean showScores = true;
51
52   protected int maxIdLength = -1;
53
54   protected String maxIdStr = null;
55
56   BufferedImage image;
57
58 //  Graphics2D gg;
59
60   int imgHeight = 0;
61
62   private boolean fastPaint = false;
63
64   List<SequenceI> searchResults;
65
66   AnnotationPanel ap;
67
68   private Font idfont;
69
70   private boolean allowFastPaint;
71
72   /**
73    * Creates a new IdCanvas object.
74    * 
75    * @param av
76    *          DOCUMENT ME!
77    */
78   public IdCanvas(AlignViewport av)
79   {
80     setLayout(new BorderLayout());
81     this.av = av;
82     PaintRefresher.Register(this, av.getSequenceSetId());
83     av.getRanges().addPropertyChangeListener(this);
84     }
85
86   /**
87    * DOCUMENT ME!
88    * 
89    * @param g
90    *          DOCUMENT ME!
91    * @param hiddenRows
92    *          true - check and display hidden row marker if need be
93    * @param s
94    *          DOCUMENT ME!
95    * @param i
96    *          DOCUMENT ME!
97    * @param starty
98    *          DOCUMENT ME!
99    * @param ypos
100    *          DOCUMENT ME!
101    */
102   public void drawIdString(Graphics2D g, boolean hiddenRows, SequenceI s,
103           int i, int starty, int ypos)
104   {
105     int xPos = 0;
106     int panelWidth = getWidth();
107     int charHeight = av.getCharHeight();
108
109     if ((searchResults != null) && searchResults.contains(s))
110     {
111       g.setColor(Color.black);
112       g.fillRect(0, ((i - starty) * charHeight) + ypos, getWidth(),
113               charHeight);
114       g.setColor(Color.white);
115     }
116     else if ((av.getSelectionGroup() != null)
117             && av.getSelectionGroup().getSequences(null).contains(s))
118     {
119       g.setColor(Color.lightGray);
120       g.fillRect(0, ((i - starty) * charHeight) + ypos, getWidth(),
121               charHeight);
122       g.setColor(Color.white);
123     }
124     else
125     {
126       g.setColor(av.getSequenceColour(s));
127       g.fillRect(0, ((i - starty) * charHeight) + ypos, getWidth(),
128               charHeight);
129       g.setColor(Color.black);
130     }
131
132     if (av.isRightAlignIds())
133     {
134       FontMetrics fm = g.getFontMetrics();
135       xPos = panelWidth
136               - fm.stringWidth(s.getDisplayId(av.getShowJVSuffix())) - 4;
137     }
138
139     g.drawString(s.getDisplayId(av.getShowJVSuffix()), xPos,
140             (((i - starty + 1) * charHeight) + ypos) - (charHeight / 5));
141
142     // JAL-3253-applet was just hiddenRows here. ccfc48e (gmungoc) added getShowHiddenMarkers test
143     if (hiddenRows && av.getShowHiddenMarkers())
144     {
145       drawMarker(g, av, i, starty, ypos);
146     }
147
148   }
149
150   /**
151    * DOCUMENT ME!
152    * 
153    * @param vertical
154    *          DOCUMENT ME!
155    */
156   public void fastPaint(int vertical)
157   {
158
159     /*
160      * for now, not attempting fast paint of wrapped ids...
161      */
162     if (image == null || av.getWrapAlignment())
163     {
164       repaint();
165
166       return;
167     }
168
169     ViewportRanges ranges = av.getRanges();
170
171     Graphics2D gg = image.createGraphics();
172     gg.copyArea(0, 0, getWidth(), imgHeight, 0,
173             -vertical * av.getCharHeight());
174
175     int ss = ranges.getStartSeq();
176     int es = ranges.getEndSeq();
177     int transY = 0;
178
179     if (vertical > 0) // scroll down
180     {
181       ss = es - vertical;
182
183       if (ss < ranges.getStartSeq())
184       { // ie scrolling too fast, more than a page at a time
185         ss = ranges.getStartSeq();
186       }
187       else
188       {
189         transY = imgHeight - ((vertical + 1) * av.getCharHeight());
190       }
191     }
192     else if (vertical < 0) // scroll up
193     {
194       es = ss - vertical;
195
196       if (es > ranges.getEndSeq())
197       {
198         es = ranges.getEndSeq();
199       }
200     }
201
202     gg.translate(0, transY);
203
204     drawIds(gg, av, ss, es, searchResults);
205
206     gg.translate(0, -transY);
207
208     gg.dispose();
209     
210     fastPaint = true;
211
212     // Call repaint on alignment panel so that repaints from other alignment
213     // panel components can be aggregated. Otherwise performance of the overview
214     // window and others may be adversely affected.
215     av.getAlignPanel().repaint();
216   }
217
218   /**
219    * DOCUMENT ME!
220    * 
221    * @param g
222    *          DOCUMENT ME!
223    */
224   @Override
225   public void paintComponent(Graphics g)
226   {
227     if (av.getAlignPanel().getHoldRepaint())
228     {
229       return;
230     }
231
232     g.setColor(Color.white);
233     g.fillRect(0, 0, getWidth(), getHeight());
234     
235     if (allowFastPaint && fastPaint)
236     {
237       fastPaint = false;
238       g.drawImage(image, 0, 0, this);
239     
240       return;
241     }
242     
243     int oldHeight = imgHeight;
244     
245     imgHeight = getHeight();
246     imgHeight -= (imgHeight % av.getCharHeight());
247     
248     if (imgHeight < 1)
249     {
250       return;
251     }
252     
253     if (oldHeight != imgHeight || image.getWidth(this) != getWidth())
254     {
255       image = new BufferedImage(getWidth(), imgHeight,
256                 BufferedImage.TYPE_INT_RGB);
257     }
258     
259     Graphics2D gg = image.createGraphics();
260     
261     // Fill in the background
262     gg.setColor(Color.white);
263     gg.fillRect(0, 0, getWidth(), imgHeight);
264     
265     drawIds(gg, av, av.getRanges().getStartSeq(), av.getRanges().getEndSeq(), searchResults);
266
267     gg.dispose();
268     
269     g.drawImage(image, 0, 0, this);
270   }
271
272   /**
273    * Draws sequence ids from sequence index startSeq to endSeq (inclusive), with
274    * the font and other display settings configured on the viewport. Ids of
275    * sequences included in the selection are coloured grey, otherwise the
276    * current id colour for the sequence id is used.
277    * 
278    * @param g
279    * @param alignViewport
280    * @param startSeq
281    * @param endSeq
282    * @param selection
283    */
284   void drawIds(Graphics2D g, AlignViewport alignViewport, final int startSeq,
285           final int endSeq, List<SequenceI> selection)
286   {
287     Font font = alignViewport.getFont();
288     if (alignViewport.isSeqNameItalics())
289     {
290       setIdfont(new Font(font.getName(), Font.ITALIC,
291               font.getSize()));
292     }
293     else
294     {
295       setIdfont(font);
296     }
297
298     g.setFont(getIdfont());
299     FontMetrics fm = g.getFontMetrics();
300
301     if (alignViewport.antiAlias)
302     {
303       g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
304               RenderingHints.VALUE_ANTIALIAS_ON);
305     }
306
307     Color currentColor = Color.white;
308     Color currentTextColor = Color.black;
309
310     boolean hasHiddenRows = alignViewport.hasHiddenRows();
311
312     if (alignViewport.getWrapAlignment())
313     {
314       drawIdsWrapped(g, alignViewport, startSeq, getHeight());
315       return;
316     }
317
318     // Now draw the id strings
319     int panelWidth = getWidth();
320     int xPos = 0;
321
322     // Now draw the id strings
323     for (int i = startSeq; i <= endSeq; i++)
324     {
325       SequenceI sequence = alignViewport.getAlignment().getSequenceAt(i);
326
327       if (sequence == null)
328       {
329         continue;
330       }
331
332       if (hasHiddenRows || alignViewport.isDisplayReferenceSeq())
333       {
334         g.setFont(getHiddenFont(sequence, alignViewport));
335       }
336
337       // Selected sequence colours
338       if (selection != null && selection.contains(sequence))
339       {
340         currentColor = Color.black;
341         currentTextColor = Color.white;
342       }
343       else if ((alignViewport.getSelectionGroup() != null) && alignViewport
344               .getSelectionGroup().getSequences(null).contains(sequence))
345       {
346         currentColor = Color.lightGray;
347         currentTextColor = Color.black;
348       }
349       else
350       {
351         currentColor = alignViewport.getSequenceColour(sequence);
352         currentTextColor = Color.black;
353       }
354
355       g.setColor(currentColor);
356
357       int charHeight = alignViewport.getCharHeight();
358       g.fillRect(0, (i - startSeq) * charHeight,
359               getWidth(), charHeight);
360
361       g.setColor(currentTextColor);
362
363       String string = sequence
364               .getDisplayId(alignViewport.getShowJVSuffix());
365
366       if (alignViewport.isRightAlignIds())
367       {
368         xPos = panelWidth - fm.stringWidth(string) - 4;
369       }
370
371       g.drawString(string, xPos, (((i - startSeq) * charHeight) + charHeight)
372               - (charHeight / 5));
373
374       if (hasHiddenRows && av.getShowHiddenMarkers())
375       {
376         drawMarker(g, alignViewport, i, startSeq, 0);
377       }
378     }
379   }
380
381   /**
382    * Draws sequence ids, and annotation labels if annotations are shown, in
383    * wrapped mode
384    * 
385    * @param g
386    * @param alignViewport
387    * @param startSeq
388    */
389   void drawIdsWrapped(Graphics2D g, AlignViewport alignViewport,
390           int startSeq, int pageHeight)
391   {
392     int alignmentWidth = alignViewport.getAlignment().getWidth();
393     final int alheight = alignViewport.getAlignment().getHeight();
394
395     
396 //    int annotationHeight = 0;
397
398     /* (former)
399      * assumption: SeqCanvas.calculateWrappedGeometry has been called
400      * 
401      * was based on the fact that SeqCanvas was added as a child prior to IdCanvas, 
402      * and children are processed in order of addition.
403      * 
404      * It's probably fine. But...
405      * 
406      */
407     SeqCanvas seqCanvas = alignViewport.getAlignPanel()
408             .getSeqPanel().seqCanvas;
409     // ...better: let's call it now
410     seqCanvas.calculateWrappedGeometry();
411
412     final int charHeight = alignViewport.getCharHeight();
413
414     AnnotationLabels labels = null;
415     if (alignViewport.isShowAnnotation())
416     {
417         // BH when was ap == null?
418       if (ap == null)
419       {
420         ap = new AnnotationPanel(alignViewport);
421       }
422 //      annotationHeight = ap.adjustPanelHeight();
423       labels = new AnnotationLabels(alignViewport);
424     }
425
426 //    int hgap = charHeight;
427 //    if (alignViewport.getScaleAboveWrapped())
428 //    {
429 //      hgap += charHeight;
430 //    }
431 //
432 //    /*
433 //     * height of alignment + gap + annotations (if shown)
434 //     */
435 //    int cHeight = alheight * charHeight + hgap
436 //            + annotationHeight;
437 //
438     ViewportRanges ranges = alignViewport.getRanges();
439
440     int rowSize = ranges.getViewportWidth();
441
442     /*
443      * draw repeating sequence ids until out of sequence data or
444      * out of visible space, whichever comes first
445      */
446     boolean hasHiddenRows = alignViewport.hasHiddenRows();
447     int ypos = seqCanvas.wrappedSpaceAboveAlignment;
448     int rowStartRes = ranges.getStartRes();
449     while ((ypos <= pageHeight) && (rowStartRes < alignmentWidth))
450     {
451       for (int i = startSeq; i < alheight; i++)
452       {
453         SequenceI s = alignViewport.getAlignment().getSequenceAt(i);
454         if (hasHiddenRows || alignViewport.isDisplayReferenceSeq())
455         {
456           g.setFont(getHiddenFont(s, alignViewport));
457         }
458         else
459         {
460           g.setFont(getIdfont());
461         }
462         drawIdString(g, hasHiddenRows, s, i, 0, ypos);
463       }
464
465       if (labels != null && alignViewport.isShowAnnotation())
466       {
467         g.translate(0, ypos + (alheight * charHeight));
468         labels.drawComponent(g, getWidth());
469         g.translate(0, -ypos - (alheight * charHeight));
470       }
471
472       ypos += seqCanvas.wrappedRepeatHeightPx;
473       rowStartRes += rowSize;
474     }
475   }
476
477   /**
478    * Draws a marker (a blue right-pointing triangle) between sequences to
479    * indicate hidden sequences.
480    * 
481    * @param g
482    * @param alignViewport
483    * @param seqIndex
484    * @param starty
485    * @param yoffset
486    */
487   void drawMarker(Graphics2D g, AlignViewport alignViewport, int seqIndex, int starty, int yoffset)
488   {
489     SequenceI[] hseqs = alignViewport.getAlignment()
490             .getHiddenSequences().hiddenSequences;
491     // Use this method here instead of calling hiddenSeq adjust
492     // 3 times.
493     int hSize = hseqs.length;
494
495     int hiddenIndex = seqIndex;
496     int lastIndex = seqIndex - 1;
497     int nextIndex = seqIndex + 1;
498
499     for (int j = 0; j < hSize; j++)
500     {
501       if (hseqs[j] != null)
502       {
503         if (j - 1 < hiddenIndex)
504         {
505           hiddenIndex++;
506         }
507         if (j - 1 < lastIndex)
508         {
509           lastIndex++;
510         }
511         if (j - 1 < nextIndex)
512         {
513           nextIndex++;
514         }
515       }
516     }
517
518     /*
519      * are we below or above the hidden sequences?
520      */
521     boolean below = (hiddenIndex > lastIndex + 1);
522     boolean above = (nextIndex > hiddenIndex + 1);
523
524     g.setColor(Color.blue);
525     int charHeight = av.getCharHeight();
526
527     /*
528      * vertices of the triangle, below or above hidden seqs
529      */
530     int[] xPoints = new int[]
531     { getWidth() - charHeight,
532         getWidth() - charHeight, getWidth() };
533     int yShift = seqIndex - starty;
534
535     if (below)
536     {
537       int[] yPoints = new int[] { yShift * charHeight + yoffset,
538           yShift * charHeight + yoffset + charHeight / 4,
539           yShift * charHeight + yoffset };
540       g.fillPolygon(xPoints, yPoints, 3);
541     }
542     if (above)
543     {
544       yShift++;
545       int[] yPoints = new int[] { yShift * charHeight + yoffset,
546           yShift * charHeight + yoffset - charHeight / 4,
547           yShift * charHeight + yoffset };
548       g.fillPolygon(xPoints, yPoints, 3);
549     }
550   }
551
552   /**
553    * Answers the standard sequence id font, or a bold font if the sequence is
554    * set as reference or a hidden group representative
555    * 
556    * @param seq
557    * @param alignViewport
558    * @return
559    */
560   private Font getHiddenFont(SequenceI seq, AlignViewport alignViewport)
561   {
562     if (av.isReferenceSeq(seq) || av.isHiddenRepSequence(seq))
563     {
564       return new Font(av.getFont().getName(), Font.BOLD,
565               av.getFont().getSize());
566     }
567     return getIdfont();
568   }
569
570   /**
571    * DOCUMENT ME!
572    * 
573    * @param list
574    *          DOCUMENT ME!
575    */
576   public void setHighlighted(List<SequenceI> list)
577   {
578     searchResults = list;
579     repaint();
580   }
581
582   public Font getIdfont()
583   {
584     return idfont;
585   }
586
587   public void setIdfont(Font idfont)
588   {
589     this.idfont = idfont;
590   }
591
592   /**
593    * Respond to viewport range changes (e.g. alignment panel was scrolled). Both
594    * scrolling and resizing change viewport ranges. Scrolling changes both start
595    * and end points, but resize only changes end values. Here we only want to
596    * fastpaint on a scroll, with resize using a normal paint, so scroll events
597    * are identified as changes to the horizontal or vertical start value.
598    * <p>
599    * In unwrapped mode, only responds to a vertical scroll, as horizontal scroll
600    * leaves sequence ids unchanged. In wrapped mode, only vertical scroll is
601    * provided, but it generates a change of "startres" which does require an
602    * update here.
603    */
604   @Override
605   public void propertyChange(PropertyChangeEvent evt)
606   {
607     String propertyName = evt.getPropertyName();
608     switch (propertyName)
609     {
610     case ViewportRanges.STARTSEQ:
611       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
612       break;
613     case ViewportRanges.STARTRES:
614       if (av.getWrapAlignment())
615       {
616         fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
617       }
618       break;
619     case ViewportRanges.STARTRESANDSEQ:
620       fastPaint(((int[]) evt.getNewValue())[1]
621               - ((int[]) evt.getOldValue())[1]);
622       break;
623     case ViewportRanges.MOVE_VIEWPORT:
624       repaint();
625       break;
626     default:
627     }
628   }
629
630   /**
631    * Clears the flag that allows a 'fast paint' on the next repaint, so
632    * requiring a full repaint
633    */
634   public void setNoFastPaint()
635   {
636     allowFastPaint = false;
637   }
638 }