JAL-4047 - proof of concept for JAL-4048 - display columns of info in sequence ID...
[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 import jalview.viewmodel.seqfeatures.IdColumn;
40 import jalview.viewmodel.seqfeatures.IdColumns;
41 import jalview.viewmodel.seqfeatures.IdColumns.ColumnCell;
42
43 /**
44  * DOCUMENT ME!
45  * 
46  * @author $author$
47  * @version $Revision$
48  */
49 public class IdCanvas extends JPanel implements ViewportListenerI
50 {
51   protected AlignViewport av;
52
53   protected boolean showScores = true;
54
55   protected int maxIdLength = -1;
56
57   protected String maxIdStr = null;
58
59   BufferedImage image;
60
61   // Graphics2D gg;
62
63   int imgHeight = 0;
64
65   boolean fastPaint = false;
66
67   List<SequenceI> searchResults;
68
69   AnnotationPanel ap;
70
71   private Font idfont;
72
73   /**
74    * Creates a new IdCanvas object.
75    * 
76    * @param av
77    *          DOCUMENT ME!
78    */
79   public IdCanvas(AlignViewport av)
80   {
81     setLayout(new BorderLayout());
82     this.av = av;
83     PaintRefresher.Register(this, av.getSequenceSetId());
84     av.getRanges().addPropertyChangeListener(this);
85   }
86
87   /**
88    * DOCUMENT ME!
89    * 
90    * @param g
91    *          DOCUMENT ME!
92    * @param hiddenRows
93    *          true - check and display hidden row marker if need be
94    * @param s
95    *          DOCUMENT ME!
96    * @param i
97    *          DOCUMENT ME!
98    * @param starty
99    *          DOCUMENT ME!
100    * @param ypos
101    *          DOCUMENT ME!
102    */
103   public void drawIdString(Graphics2D g, boolean hiddenRows, SequenceI s,
104           int i, int starty, int ypos)
105   {
106     int xPos = 0;
107     int panelWidth = getWidth();
108     int charHeight = av.getCharHeight();
109
110     if ((searchResults != null) && searchResults.contains(s))
111     {
112       g.setColor(Color.black);
113       g.fillRect(0, ((i - starty) * charHeight) + ypos, getWidth(),
114               charHeight);
115       g.setColor(Color.white);
116     }
117     else if ((av.getSelectionGroup() != null)
118             && av.getSelectionGroup().getSequences(null).contains(s))
119     {
120       g.setColor(Color.lightGray);
121       g.fillRect(0, ((i - starty) * charHeight) + ypos, getWidth(),
122               charHeight);
123       g.setColor(Color.white);
124     }
125     else
126     {
127       g.setColor(av.getSequenceColour(s));
128       g.fillRect(0, ((i - starty) * charHeight) + ypos, getWidth(),
129               charHeight);
130       g.setColor(Color.black);
131     }
132
133     if (av.isRightAlignIds())
134     {
135       FontMetrics fm = g.getFontMetrics();
136       xPos = panelWidth
137               - fm.stringWidth(s.getDisplayId(av.getShowJVSuffix())) - 4;
138     }
139
140     g.drawString(s.getDisplayId(av.getShowJVSuffix()), xPos,
141             (((i - starty + 1) * charHeight) + ypos) - (charHeight / 5));
142
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     g.setColor(Color.white);
228     g.fillRect(0, 0, getWidth(), getHeight());
229
230     if (fastPaint)
231     {
232       fastPaint = false;
233       g.drawImage(image, 0, 0, this);
234
235       return;
236     }
237
238     int oldHeight = imgHeight;
239
240     imgHeight = getHeight();
241     imgHeight -= (imgHeight % av.getCharHeight());
242
243     if (imgHeight < 1)
244     {
245       return;
246     }
247
248     if (oldHeight != imgHeight || image.getWidth(this) != getWidth())
249     {
250       image = new BufferedImage(getWidth(), imgHeight,
251               BufferedImage.TYPE_INT_RGB);
252     }
253
254     Graphics2D gg = image.createGraphics();
255
256     // Fill in the background
257     gg.setColor(Color.white);
258     gg.fillRect(0, 0, getWidth(), imgHeight);
259
260     drawIds(gg, av, av.getRanges().getStartSeq(),
261             av.getRanges().getEndSeq(), searchResults);
262
263     gg.dispose();
264
265     g.drawImage(image, 0, 0, this);
266   }
267
268   /**
269    * Draws sequence ids from sequence index startSeq to endSeq (inclusive), with
270    * the font and other display settings configured on the viewport. Ids of
271    * sequences included in the selection are coloured grey, otherwise the
272    * current id colour for the sequence id is used.
273    * 
274    * @param g
275    * @param alignViewport
276    * @param startSeq
277    * @param endSeq
278    * @param selection
279    */
280   void drawIds(Graphics2D g, AlignViewport alignViewport,
281           final int startSeq, final int endSeq, List<SequenceI> selection)
282   {
283     Font font = alignViewport.getFont();
284     if (alignViewport.isSeqNameItalics())
285     {
286       setIdfont(new Font(font.getName(), Font.ITALIC, font.getSize()));
287     }
288     else
289     {
290       setIdfont(font);
291     }
292
293     g.setFont(getIdfont());
294     FontMetrics fm = g.getFontMetrics();
295
296     if (alignViewport.antiAlias)
297     {
298       g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
299               RenderingHints.VALUE_ANTIALIAS_ON);
300     }
301
302     Color currentColor = Color.white;
303     Color currentTextColor = Color.black;
304
305     boolean hasHiddenRows = alignViewport.hasHiddenRows();
306
307     if (alignViewport.getWrapAlignment())
308     {
309       drawIdsWrapped(g, alignViewport, startSeq, getHeight());
310       return;
311     }
312
313     // Now draw the id strings
314     int fullPanelWidth = getWidth();
315
316     IdColumns id_cols = alignViewport.getIdColumns();
317     List<IdColumn> visible = id_cols.getVisible();
318     /**
319      * width of an idColumn
320      */
321     int colWid = 20;
322     int panelWidth = Math.max(fullPanelWidth / 2,
323             fullPanelWidth - (colWid * visible.size()));
324     int xPos = 0;
325
326     // Now draw the id strings
327     for (int i = startSeq; i <= endSeq; i++)
328     {
329       SequenceI sequence = alignViewport.getAlignment().getSequenceAt(i);
330
331       if (sequence == null)
332       {
333         continue;
334       }
335       if (hasHiddenRows || alignViewport.isDisplayReferenceSeq())
336       {
337         g.setFont(getHiddenFont(sequence, alignViewport));
338         fm = g.getFontMetrics();
339       }
340
341       // Selected sequence colours
342       if (selection != null && selection.contains(sequence))
343       {
344         currentColor = Color.black;
345         currentTextColor = Color.white;
346       }
347       else if ((alignViewport.getSelectionGroup() != null) && alignViewport
348               .getSelectionGroup().getSequences(null).contains(sequence))
349       {
350         currentColor = Color.lightGray;
351         currentTextColor = Color.black;
352       }
353       else
354       {
355         currentColor = alignViewport.getSequenceColour(sequence);
356         currentTextColor = Color.black;
357       }
358
359       g.setColor(currentColor);
360
361       int charHeight = alignViewport.getCharHeight();
362       g.fillRect(0, (i - startSeq) * charHeight, getWidth(), charHeight);
363
364       g.setColor(currentTextColor);
365
366       String string = sequence
367               .getDisplayId(alignViewport.getShowJVSuffix());
368
369       if (alignViewport.isRightAlignIds())
370       {
371         xPos = panelWidth - fm.stringWidth(string) - 4;
372       }
373
374       g.drawString(string, xPos,
375               (((i - startSeq) * charHeight) + charHeight)
376                       - (charHeight / 5));
377
378       if (visible != null && visible.size() > 0)
379       {
380         xPos = panelWidth + 2;
381         for (IdColumn col : visible)
382         {
383           ColumnCell col_cell = id_cols.getCellFor(sequence, col);
384           if (col_cell == null)
385           {
386             g.setColor(Color.gray);
387             g.fillRect(xPos, (i - startSeq) * charHeight, xPos + colWid - 4,
388                     charHeight);
389           }
390           else
391           {
392             g.setColor(col_cell.bg);
393             g.fillRect(xPos, (i - startSeq) * charHeight, xPos + colWid - 4,
394                     charHeight);
395             g.setColor(col_cell.fg);
396             g.drawString(col_cell.label, xPos,
397                     (((i - startSeq) * charHeight) + charHeight)
398                             - (charHeight / 5));
399           }
400           xPos += colWid;
401           g.setColor(currentTextColor);
402         }
403       }
404       if (hasHiddenRows && av.getShowHiddenMarkers())
405       {
406         drawMarker(g, alignViewport, i, startSeq, 0);
407       }
408     }
409   }
410
411   /**
412    * Draws sequence ids, and annotation labels if annotations are shown, in
413    * wrapped mode
414    * 
415    * @param g
416    * @param alignViewport
417    * @param startSeq
418    */
419   void drawIdsWrapped(Graphics2D g, AlignViewport alignViewport,
420           int startSeq, int pageHeight)
421   {
422     int alignmentWidth = alignViewport.getAlignment().getWidth();
423     final int alheight = alignViewport.getAlignment().getHeight();
424
425     /*
426      * assumption: SeqCanvas.calculateWrappedGeometry has been called
427      */
428     SeqCanvas seqCanvas = alignViewport.getAlignPanel()
429             .getSeqPanel().seqCanvas;
430
431     final int charHeight = alignViewport.getCharHeight();
432
433     AnnotationLabels labels = null;
434     if (alignViewport.isShowAnnotation())
435     {
436       labels = new AnnotationLabels(alignViewport);
437     }
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,
489           int starty, int yoffset)
490   {
491     SequenceI[] hseqs = alignViewport.getAlignment()
492             .getHiddenSequences().hiddenSequences;
493     // Use this method here instead of calling hiddenSeq adjust
494     // 3 times.
495     int hSize = hseqs.length;
496
497     int hiddenIndex = seqIndex;
498     int lastIndex = seqIndex - 1;
499     int nextIndex = seqIndex + 1;
500
501     for (int j = 0; j < hSize; j++)
502     {
503       if (hseqs[j] != null)
504       {
505         if (j - 1 < hiddenIndex)
506         {
507           hiddenIndex++;
508         }
509         if (j - 1 < lastIndex)
510         {
511           lastIndex++;
512         }
513         if (j - 1 < nextIndex)
514         {
515           nextIndex++;
516         }
517       }
518     }
519
520     /*
521      * are we below or above the hidden sequences?
522      */
523     boolean below = (hiddenIndex > lastIndex + 1);
524     boolean above = (nextIndex > hiddenIndex + 1);
525
526     g.setColor(Color.blue);
527     int charHeight = av.getCharHeight();
528
529     /*
530      * vertices of the triangle, below or above hidden seqs
531      */
532     int[] xPoints = new int[] { 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     if (propertyName.equals(ViewportRanges.STARTSEQ)
610             || (av.getWrapAlignment()
611                     && propertyName.equals(ViewportRanges.STARTRES)))
612     {
613       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
614     }
615     else if (propertyName.equals(ViewportRanges.STARTRESANDSEQ))
616     {
617       fastPaint(((int[]) evt.getNewValue())[1]
618               - ((int[]) evt.getOldValue())[1]);
619     }
620     else if (propertyName.equals(ViewportRanges.MOVE_VIEWPORT))
621     {
622       repaint();
623     }
624   }
625 }