JAL-4048 fix disappearing sequence IDs, and non-positional feature descriptions
[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
325     // Now draw the id strings
326     for (int i = startSeq; i <= endSeq; i++)
327     {
328       int xPos = 0;
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         try
381         {
382           xPos = panelWidth + 2;
383           for (IdColumn col : visible)
384           {
385             ColumnCell col_cell = id_cols.getCellFor(sequence, col);
386             if (col_cell == null)
387             {
388               g.setColor(Color.gray);
389               g.fillRect(xPos + 1, (i - startSeq) * charHeight,
390                       xPos + colWid - 3, charHeight);
391             }
392             else
393             {
394               g.setColor(col_cell.bg);
395               g.fillRect(xPos + 1, (i - startSeq) * charHeight,
396                       xPos + colWid - 3, charHeight);
397               g.setColor(col_cell.fg);
398               g.drawString(col_cell.label, xPos,
399                       (((i - startSeq) * charHeight) + charHeight)
400                               - (charHeight / 5));
401             }
402             xPos += colWid;
403             g.setColor(currentTextColor);
404           }
405         } catch (Exception q)
406         {
407         }
408       }
409       if (hasHiddenRows && av.getShowHiddenMarkers())
410       {
411         drawMarker(g, alignViewport, i, startSeq, 0);
412       }
413     }
414   }
415
416   /**
417    * Draws sequence ids, and annotation labels if annotations are shown, in
418    * wrapped mode
419    * 
420    * @param g
421    * @param alignViewport
422    * @param startSeq
423    */
424   void drawIdsWrapped(Graphics2D g, AlignViewport alignViewport,
425           int startSeq, int pageHeight)
426   {
427     int alignmentWidth = alignViewport.getAlignment().getWidth();
428     final int alheight = alignViewport.getAlignment().getHeight();
429
430     /*
431      * assumption: SeqCanvas.calculateWrappedGeometry has been called
432      */
433     SeqCanvas seqCanvas = alignViewport.getAlignPanel()
434             .getSeqPanel().seqCanvas;
435
436     final int charHeight = alignViewport.getCharHeight();
437
438     AnnotationLabels labels = null;
439     if (alignViewport.isShowAnnotation())
440     {
441       labels = new AnnotationLabels(alignViewport);
442     }
443
444     ViewportRanges ranges = alignViewport.getRanges();
445
446     int rowSize = ranges.getViewportWidth();
447
448     /*
449      * draw repeating sequence ids until out of sequence data or
450      * out of visible space, whichever comes first
451      */
452     boolean hasHiddenRows = alignViewport.hasHiddenRows();
453     int ypos = seqCanvas.wrappedSpaceAboveAlignment;
454     int rowStartRes = ranges.getStartRes();
455     while ((ypos <= pageHeight) && (rowStartRes < alignmentWidth))
456     {
457       for (int i = startSeq; i < alheight; i++)
458       {
459         SequenceI s = alignViewport.getAlignment().getSequenceAt(i);
460         if (hasHiddenRows || alignViewport.isDisplayReferenceSeq())
461         {
462           g.setFont(getHiddenFont(s, alignViewport));
463         }
464         else
465         {
466           g.setFont(getIdfont());
467         }
468         drawIdString(g, hasHiddenRows, s, i, 0, ypos);
469       }
470
471       if (labels != null && alignViewport.isShowAnnotation())
472       {
473         g.translate(0, ypos + (alheight * charHeight));
474         labels.drawComponent(g, getWidth());
475         g.translate(0, -ypos - (alheight * charHeight));
476       }
477
478       ypos += seqCanvas.wrappedRepeatHeightPx;
479       rowStartRes += rowSize;
480     }
481   }
482
483   /**
484    * Draws a marker (a blue right-pointing triangle) between sequences to
485    * indicate hidden sequences.
486    * 
487    * @param g
488    * @param alignViewport
489    * @param seqIndex
490    * @param starty
491    * @param yoffset
492    */
493   void drawMarker(Graphics2D g, AlignViewport alignViewport, int seqIndex,
494           int starty, int yoffset)
495   {
496     SequenceI[] hseqs = alignViewport.getAlignment()
497             .getHiddenSequences().hiddenSequences;
498     // Use this method here instead of calling hiddenSeq adjust
499     // 3 times.
500     int hSize = hseqs.length;
501
502     int hiddenIndex = seqIndex;
503     int lastIndex = seqIndex - 1;
504     int nextIndex = seqIndex + 1;
505
506     for (int j = 0; j < hSize; j++)
507     {
508       if (hseqs[j] != null)
509       {
510         if (j - 1 < hiddenIndex)
511         {
512           hiddenIndex++;
513         }
514         if (j - 1 < lastIndex)
515         {
516           lastIndex++;
517         }
518         if (j - 1 < nextIndex)
519         {
520           nextIndex++;
521         }
522       }
523     }
524
525     /*
526      * are we below or above the hidden sequences?
527      */
528     boolean below = (hiddenIndex > lastIndex + 1);
529     boolean above = (nextIndex > hiddenIndex + 1);
530
531     g.setColor(Color.blue);
532     int charHeight = av.getCharHeight();
533
534     /*
535      * vertices of the triangle, below or above hidden seqs
536      */
537     int[] xPoints = new int[] { getWidth() - charHeight,
538         getWidth() - charHeight, getWidth() };
539     int yShift = seqIndex - starty;
540
541     if (below)
542     {
543       int[] yPoints = new int[] { yShift * charHeight + yoffset,
544           yShift * charHeight + yoffset + charHeight / 4,
545           yShift * charHeight + yoffset };
546       g.fillPolygon(xPoints, yPoints, 3);
547     }
548     if (above)
549     {
550       yShift++;
551       int[] yPoints = new int[] { yShift * charHeight + yoffset,
552           yShift * charHeight + yoffset - charHeight / 4,
553           yShift * charHeight + yoffset };
554       g.fillPolygon(xPoints, yPoints, 3);
555     }
556   }
557
558   /**
559    * Answers the standard sequence id font, or a bold font if the sequence is
560    * set as reference or a hidden group representative
561    * 
562    * @param seq
563    * @param alignViewport
564    * @return
565    */
566   private Font getHiddenFont(SequenceI seq, AlignViewport alignViewport)
567   {
568     if (av.isReferenceSeq(seq) || av.isHiddenRepSequence(seq))
569     {
570       return new Font(av.getFont().getName(), Font.BOLD,
571               av.getFont().getSize());
572     }
573     return getIdfont();
574   }
575
576   /**
577    * DOCUMENT ME!
578    * 
579    * @param list
580    *          DOCUMENT ME!
581    */
582   public void setHighlighted(List<SequenceI> list)
583   {
584     searchResults = list;
585     repaint();
586   }
587
588   public Font getIdfont()
589   {
590     return idfont;
591   }
592
593   public void setIdfont(Font idfont)
594   {
595     this.idfont = idfont;
596   }
597
598   /**
599    * Respond to viewport range changes (e.g. alignment panel was scrolled). Both
600    * scrolling and resizing change viewport ranges. Scrolling changes both start
601    * and end points, but resize only changes end values. Here we only want to
602    * fastpaint on a scroll, with resize using a normal paint, so scroll events
603    * are identified as changes to the horizontal or vertical start value.
604    * <p>
605    * In unwrapped mode, only responds to a vertical scroll, as horizontal scroll
606    * leaves sequence ids unchanged. In wrapped mode, only vertical scroll is
607    * provided, but it generates a change of "startres" which does require an
608    * update here.
609    */
610   @Override
611   public void propertyChange(PropertyChangeEvent evt)
612   {
613     String propertyName = evt.getPropertyName();
614     if (propertyName.equals(ViewportRanges.STARTSEQ)
615             || (av.getWrapAlignment()
616                     && propertyName.equals(ViewportRanges.STARTRES)))
617     {
618       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
619     }
620     else if (propertyName.equals(ViewportRanges.STARTRESANDSEQ))
621     {
622       fastPaint(((int[]) evt.getNewValue())[1]
623               - ((int[]) evt.getOldValue())[1]);
624     }
625     else if (propertyName.equals(ViewportRanges.MOVE_VIEWPORT))
626     {
627       repaint();
628     }
629   }
630 }