Merge commit 'alpha/update_2_12_for_2_11_2_series_merge^2' into HEAD
[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         fm = g.getFontMetrics();
336       }
337
338       // Selected sequence colours
339       if (selection != null && selection.contains(sequence))
340       {
341         currentColor = Color.black;
342         currentTextColor = Color.white;
343       }
344       else if ((alignViewport.getSelectionGroup() != null) && alignViewport
345               .getSelectionGroup().getSequences(null).contains(sequence))
346       {
347         currentColor = Color.lightGray;
348         currentTextColor = Color.black;
349       }
350       else
351       {
352         currentColor = alignViewport.getSequenceColour(sequence);
353         currentTextColor = Color.black;
354       }
355
356       g.setColor(currentColor);
357
358       int charHeight = alignViewport.getCharHeight();
359       g.fillRect(0, (i - startSeq) * charHeight,
360               getWidth(), charHeight);
361
362       g.setColor(currentTextColor);
363
364       String string = sequence
365               .getDisplayId(alignViewport.getShowJVSuffix());
366
367       if (alignViewport.isRightAlignIds())
368       {
369         xPos = panelWidth - fm.stringWidth(string) - 4;
370       }
371
372       g.drawString(string, xPos, (((i - startSeq) * charHeight) + charHeight)
373               - (charHeight / 5));
374
375       if (hasHiddenRows && av.getShowHiddenMarkers())
376       {
377         drawMarker(g, alignViewport, i, startSeq, 0);
378       }
379     }
380   }
381
382   /**
383    * Draws sequence ids, and annotation labels if annotations are shown, in
384    * wrapped mode
385    * 
386    * @param g
387    * @param alignViewport
388    * @param startSeq
389    */
390   void drawIdsWrapped(Graphics2D g, AlignViewport alignViewport,
391           int startSeq, int pageHeight)
392   {
393     int alignmentWidth = alignViewport.getAlignment().getWidth();
394     final int alheight = alignViewport.getAlignment().getHeight();
395
396     
397 //    int annotationHeight = 0;
398
399     /* (former)
400      * assumption: SeqCanvas.calculateWrappedGeometry has been called
401      * 
402      * was based on the fact that SeqCanvas was added as a child prior to IdCanvas, 
403      * and children are processed in order of addition.
404      * 
405      * It's probably fine. But...
406      * 
407      */
408     SeqCanvas seqCanvas = alignViewport.getAlignPanel()
409             .getSeqPanel().seqCanvas;
410     // ...better: let's call it now
411     seqCanvas.calculateWrappedGeometry();
412
413     final int charHeight = alignViewport.getCharHeight();
414
415     AnnotationLabels labels = null;
416     if (alignViewport.isShowAnnotation())
417     {
418         // BH when was ap == null?
419       if (ap == null)
420       {
421         ap = new AnnotationPanel(alignViewport);
422       }
423 //      annotationHeight = ap.adjustPanelHeight();
424       labels = new AnnotationLabels(alignViewport);
425     }
426
427 //    int hgap = charHeight;
428 //    if (alignViewport.getScaleAboveWrapped())
429 //    {
430 //      hgap += charHeight;
431 //    }
432 //
433 //    /*
434 //     * height of alignment + gap + annotations (if shown)
435 //     */
436 //    int cHeight = alheight * charHeight + hgap
437 //            + annotationHeight;
438 //
439     ViewportRanges ranges = alignViewport.getRanges();
440
441     int rowSize = ranges.getViewportWidth();
442
443     /*
444      * draw repeating sequence ids until out of sequence data or
445      * out of visible space, whichever comes first
446      */
447     boolean hasHiddenRows = alignViewport.hasHiddenRows();
448     int ypos = seqCanvas.wrappedSpaceAboveAlignment;
449     int rowStartRes = ranges.getStartRes();
450     while ((ypos <= pageHeight) && (rowStartRes < alignmentWidth))
451     {
452       for (int i = startSeq; i < alheight; i++)
453       {
454         SequenceI s = alignViewport.getAlignment().getSequenceAt(i);
455         if (hasHiddenRows || alignViewport.isDisplayReferenceSeq())
456         {
457           g.setFont(getHiddenFont(s, alignViewport));
458         }
459         else
460         {
461           g.setFont(getIdfont());
462         }
463         drawIdString(g, hasHiddenRows, s, i, 0, ypos);
464       }
465
466       if (labels != null && alignViewport.isShowAnnotation())
467       {
468         g.translate(0, ypos + (alheight * charHeight));
469         labels.drawComponent(g, getWidth());
470         g.translate(0, -ypos - (alheight * charHeight));
471       }
472
473       ypos += seqCanvas.wrappedRepeatHeightPx;
474       rowStartRes += rowSize;
475     }
476   }
477
478   /**
479    * Draws a marker (a blue right-pointing triangle) between sequences to
480    * indicate hidden sequences.
481    * 
482    * @param g
483    * @param alignViewport
484    * @param seqIndex
485    * @param starty
486    * @param yoffset
487    */
488   void drawMarker(Graphics2D g, AlignViewport alignViewport, int seqIndex, int starty, int yoffset)
489   {
490     SequenceI[] hseqs = alignViewport.getAlignment()
491             .getHiddenSequences().hiddenSequences;
492     // Use this method here instead of calling hiddenSeq adjust
493     // 3 times.
494     int hSize = hseqs.length;
495
496     int hiddenIndex = seqIndex;
497     int lastIndex = seqIndex - 1;
498     int nextIndex = seqIndex + 1;
499
500     for (int j = 0; j < hSize; j++)
501     {
502       if (hseqs[j] != null)
503       {
504         if (j - 1 < hiddenIndex)
505         {
506           hiddenIndex++;
507         }
508         if (j - 1 < lastIndex)
509         {
510           lastIndex++;
511         }
512         if (j - 1 < nextIndex)
513         {
514           nextIndex++;
515         }
516       }
517     }
518
519     /*
520      * are we below or above the hidden sequences?
521      */
522     boolean below = (hiddenIndex > lastIndex + 1);
523     boolean above = (nextIndex > hiddenIndex + 1);
524
525     g.setColor(Color.blue);
526     int charHeight = av.getCharHeight();
527
528     /*
529      * vertices of the triangle, below or above hidden seqs
530      */
531     int[] xPoints = new int[]
532     { getWidth() - charHeight,
533         getWidth() - charHeight, getWidth() };
534     int yShift = seqIndex - starty;
535
536     if (below)
537     {
538       int[] yPoints = new int[] { yShift * charHeight + yoffset,
539           yShift * charHeight + yoffset + charHeight / 4,
540           yShift * charHeight + yoffset };
541       g.fillPolygon(xPoints, yPoints, 3);
542     }
543     if (above)
544     {
545       yShift++;
546       int[] yPoints = new int[] { yShift * charHeight + yoffset,
547           yShift * charHeight + yoffset - charHeight / 4,
548           yShift * charHeight + yoffset };
549       g.fillPolygon(xPoints, yPoints, 3);
550     }
551   }
552
553   /**
554    * Answers the standard sequence id font, or a bold font if the sequence is
555    * set as reference or a hidden group representative
556    * 
557    * @param seq
558    * @param alignViewport
559    * @return
560    */
561   private Font getHiddenFont(SequenceI seq, AlignViewport alignViewport)
562   {
563     if (av.isReferenceSeq(seq) || av.isHiddenRepSequence(seq))
564     {
565       return new Font(av.getFont().getName(), Font.BOLD,
566               av.getFont().getSize());
567     }
568     return getIdfont();
569   }
570
571   /**
572    * DOCUMENT ME!
573    * 
574    * @param list
575    *          DOCUMENT ME!
576    */
577   public void setHighlighted(List<SequenceI> list)
578   {
579     searchResults = list;
580     repaint();
581   }
582
583   public Font getIdfont()
584   {
585     return idfont;
586   }
587
588   public void setIdfont(Font idfont)
589   {
590     this.idfont = idfont;
591   }
592
593   /**
594    * Respond to viewport range changes (e.g. alignment panel was scrolled). Both
595    * scrolling and resizing change viewport ranges. Scrolling changes both start
596    * and end points, but resize only changes end values. Here we only want to
597    * fastpaint on a scroll, with resize using a normal paint, so scroll events
598    * are identified as changes to the horizontal or vertical start value.
599    * <p>
600    * In unwrapped mode, only responds to a vertical scroll, as horizontal scroll
601    * leaves sequence ids unchanged. In wrapped mode, only vertical scroll is
602    * provided, but it generates a change of "startres" which does require an
603    * update here.
604    */
605   @Override
606   public void propertyChange(PropertyChangeEvent evt)
607   {
608     String propertyName = evt.getPropertyName();
609     switch (propertyName)
610     {
611     case ViewportRanges.STARTSEQ:
612       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
613       break;
614     case ViewportRanges.STARTRES:
615       if (av.getWrapAlignment())
616       {
617         fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
618       }
619       break;
620     case ViewportRanges.STARTRESANDSEQ:
621       fastPaint(((int[]) evt.getNewValue())[1]
622               - ((int[]) evt.getOldValue())[1]);
623       break;
624     case ViewportRanges.MOVE_VIEWPORT:
625       repaint();
626       break;
627     default:
628     }
629   }
630
631   /**
632    * Clears the flag that allows a 'fast paint' on the next repaint, so
633    * requiring a full repaint
634    */
635   public void setNoFastPaint()
636   {
637     allowFastPaint = false;
638   }
639 }