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