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