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