JAL-3148 SequenceRenderer, ResidueColourFinder overloads and
[jalview.git] / src / jalview / gui / SequenceRenderer.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 jalview.api.AlignViewportI;
24 import jalview.datamodel.SequenceGroup;
25 import jalview.datamodel.SequenceI;
26 import jalview.renderer.ResidueColourFinder;
27 import jalview.renderer.seqfeatures.FeatureColourFinder;
28 import jalview.schemes.ColourSchemeI;
29 import jalview.util.Comparison;
30
31 import java.awt.Color;
32 import java.awt.FontMetrics;
33 import java.awt.Graphics;
34
35 public class SequenceRenderer implements jalview.api.SequenceRendererI
36 {
37   final static int CHAR_TO_UPPER = 'A' - 'a';
38
39   private AlignViewportI av;
40
41   private FontMetrics fm;
42
43   private SequenceGroup[] allGroups = null;
44
45   private Graphics graphics;
46
47   private boolean monospacedFont;
48
49   private ResidueColourFinder resColourFinder;
50
51   /**
52    * Creates a new SequenceRenderer object
53    * 
54    * @param viewport
55    */
56   public SequenceRenderer(AlignViewportI viewport)
57   {
58     this.av = viewport;
59     resColourFinder = new ResidueColourFinder();
60   }
61
62   /**
63    * Constructor given a choice of colour scheme. May be used to find colours
64    * for a structure that has a viewport colour scheme other than 'by sequence'
65    * 
66    * @param cs
67    */
68   public SequenceRenderer(AlignViewportI viewport, ColourSchemeI cs) 
69   {
70     this.av = viewport;
71     resColourFinder = new ResidueColourFinder(viewport, cs);
72   }
73
74 /**
75    * Sets the Graphics context to draw on, and also guesses whether we are using a monospaced font
76    * 
77    * @param g
78    */
79   public void setGraphics(Graphics g)
80   {
81     graphics = g;
82     fm = g.getFontMetrics();
83
84     // If EPS graphics, stringWidth will be a double, not an int
85     double dwidth = fm.getStringBounds("M", g).getWidth();
86
87     monospacedFont = (dwidth == fm.getStringBounds("|", g).getWidth()
88             && av.getCharWidth() == dwidth);
89   }
90
91   /**
92    * Get the residue colour at the given sequence position - as determined by
93    * the sequence group colour (if any), else the colour scheme, possibly
94    * overridden by a feature colour.
95    * 
96    * @param seq
97    * @param position
98    * @param finder
99    * @return
100    */
101   @Override
102   public Color getResidueColour(final SequenceI seq, int position,
103           FeatureColourFinder finder)
104   {
105     allGroups = av.getAlignment().findAllGroups(seq);
106     return resColourFinder.getResidueColour(av.getShowBoxes(),
107             av.getResidueShading(),
108             allGroups, seq, position,
109             finder);
110   }
111
112   /**
113    * Draws the sequence (box colour and residues) over the given range, at the
114    * specified y-offset on the Graphics context
115    * 
116    * @param seq
117    * @param sg  groups (if any) that the sequence is a member of (may have
118    *            distinct group colouring)
119    * @param start
120    * @param end
121    * @param y1
122    * @param drawGaps
123    */
124   public void drawSequence(SequenceI seq, SequenceGroup[] sg, int start,
125           int end, int y1, boolean drawGaps)
126   {
127     allGroups = sg;
128
129     drawBoxes(seq, start, end, y1);
130
131     if (av.isValidCharWidth())
132     {
133       drawText(seq, start, end, y1, drawGaps);
134     }
135   }
136
137   /**
138    * Draws box colours on the given sequence residue range, at the specified
139    * y-offset on the Graphics context
140    * 
141    * @param seq
142    * @param start
143    * @param end
144    * @param y1
145    */
146   public synchronized void drawBoxes(SequenceI seq, int start, int end,
147           int y1)
148   {
149     Color resBoxColour = Color.white;
150
151     if (seq == null)
152     {
153       return; // fix for racecondition
154     }
155     int i = start;
156     int length = seq.getLength();
157
158     int curStart = -1;
159     int curWidth = av.getCharWidth(), avWidth = av.getCharWidth(),
160             avHeight = av.getCharHeight();
161
162     Color tempColour = null;
163
164     while (i <= end)
165     {
166       resBoxColour = Color.white;
167
168       if (i < length)
169       {
170         SequenceGroup currentSequenceGroup = resColourFinder
171                 .getCurrentSequenceGroup(
172                 allGroups, i);
173         if (currentSequenceGroup != null)
174         {
175           if (currentSequenceGroup.getDisplayBoxes())
176           {
177             resBoxColour = resColourFinder.getBoxColour(
178                     currentSequenceGroup.getGroupColourScheme(), seq,
179                     i);
180           }
181         }
182         else if (av.getShowBoxes())
183         {
184           resBoxColour = resColourFinder
185                   .getBoxColour(av.getResidueShading(), seq, i);
186         }
187       }
188
189       if (resBoxColour != tempColour)
190       {
191         if (tempColour != null)
192         {
193           graphics.fillRect(avWidth * (curStart - start), y1, curWidth,
194                   avHeight);
195         }
196
197         graphics.setColor(resBoxColour);
198
199         curStart = i;
200         curWidth = avWidth;
201         tempColour = resBoxColour;
202       }
203       else
204       {
205         curWidth += avWidth;
206       }
207
208       i++;
209     }
210
211     graphics.fillRect(avWidth * (curStart - start), y1, curWidth, avHeight);
212
213   }
214
215   /**
216    * Draws residue letters on the given sequence residue range, at the specified
217    * y-offset on the Graphics context
218    * 
219    * @param seq
220    * @param start
221    * @param end
222    * @param y1
223    * @param drawGaps
224    */
225   public void drawText(SequenceI seq, int start, int end, int y1, boolean drawGaps)
226   {
227     y1 += av.getCharHeight() - av.getCharHeight() / 5; // height/5 replaces pady
228     int charOffset = 0;
229     char s;
230
231     if (end + 1 >= seq.getLength())
232     {
233       end = seq.getLength() - 1;
234     }
235     graphics.setColor(av.getTextColour());
236
237     if (monospacedFont && av.getShowText() && allGroups.length == 0
238             && !av.getColourText() && av.getThresholdTextColour() == 0)
239     {
240       if (av.isRenderGaps())
241       {
242         graphics.drawString(seq.getSequenceAsString(start, end + 1), 0, y1);
243       }
244       else
245       {
246         char gap = av.getGapCharacter();
247         graphics.drawString(
248                 seq.getSequenceAsString(start, end + 1).replace(gap, ' '),
249                 0, y1);
250       }
251     }
252     else
253     {
254       boolean srep = av.isDisplayReferenceSeq();
255       boolean getboxColour = false;
256       boolean isarep = av.getAlignment().getSeqrep() == seq;
257       Color resBoxColour = Color.white;
258
259       for (int i = start; i <= end; i++)
260       {
261
262         graphics.setColor(av.getTextColour());
263         getboxColour = false;
264         s = seq.getCharAt(i);
265
266         if (!drawGaps && Comparison.isGap(s))
267         {
268           continue;
269         }
270
271         SequenceGroup currentSequenceGroup = resColourFinder
272                 .getCurrentSequenceGroup(
273                 allGroups, i);
274         if (currentSequenceGroup != null)
275         {
276           if (!currentSequenceGroup.getDisplayText())
277           {
278             continue;
279           }
280
281           if (currentSequenceGroup.thresholdTextColour > 0
282                   || currentSequenceGroup.getColourText())
283           {
284             getboxColour = true;
285             resBoxColour = resColourFinder.getBoxColour(
286                     currentSequenceGroup.getGroupColourScheme(), seq,
287                     i);
288
289             if (currentSequenceGroup.getColourText())
290             {
291               graphics.setColor(resBoxColour.darker());
292             }
293
294             if (currentSequenceGroup.thresholdTextColour > 0)
295             {
296               if (resBoxColour.getRed() + resBoxColour.getBlue()
297                       + resBoxColour
298                               .getGreen() < currentSequenceGroup.thresholdTextColour)
299               {
300                 graphics.setColor(currentSequenceGroup.textColour2);
301               }
302             }
303           }
304           else
305           {
306             graphics.setColor(currentSequenceGroup.textColour);
307           }
308           boolean isgrep = currentSequenceGroup != null
309                   ? currentSequenceGroup.getSeqrep() == seq : false;
310           if (!isarep && !isgrep
311                   && currentSequenceGroup.getShowNonconserved()) // todo
312                                                                  // optimize
313           {
314             // todo - use sequence group consensus
315             s = getDisplayChar(srep, i, s, '.', currentSequenceGroup);
316           }
317         }
318         else
319         {
320           if (!av.getShowText())
321           {
322             continue;
323           }
324
325           if (av.getColourText())
326           {
327             getboxColour = true;
328             resBoxColour = resColourFinder
329                     .getBoxColour(av.getResidueShading(), seq, i);
330
331             if (av.getShowBoxes())
332             {
333               graphics.setColor(resBoxColour.darker());
334             }
335             else
336             {
337               graphics.setColor(resBoxColour);
338             }
339           }
340
341           if (av.getThresholdTextColour() > 0)
342           {
343             if (!getboxColour)
344             {
345               resBoxColour = resColourFinder
346                       .getBoxColour(av.getResidueShading(), seq, i);
347             }
348
349             if (resBoxColour.getRed() + resBoxColour.getBlue()
350                     + resBoxColour.getGreen() < av.getThresholdTextColour())
351             {
352               graphics.setColor(av.getTextColour2());
353             }
354           }
355           if (!isarep && av.getShowUnconserved())
356           {
357             s = getDisplayChar(srep, i, s, '.', null);
358           }
359         }
360
361         charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
362         graphics.drawString(String.valueOf(s),
363                 charOffset + av.getCharWidth() * (i - start), y1);
364       }
365     }
366   }
367
368   /**
369    * Returns 'conservedChar' to represent the given position if the sequence
370    * character at that position is equal to the consensus (ignoring case), else
371    * returns the sequence character
372    * 
373    * @param usesrep
374    * @param position
375    * @param sequenceChar
376    * @param conservedChar
377    * @return
378    */
379   private char getDisplayChar(final boolean usesrep, int position,
380           char sequenceChar, char conservedChar, SequenceGroup currentGroup)
381   {
382     // TODO - use currentSequenceGroup rather than alignment
383     // currentSequenceGroup.getConsensus()
384     char conschar = (usesrep) ? (currentGroup == null
385             || position < currentGroup.getStartRes()
386             || position > currentGroup.getEndRes()
387                     ? av.getAlignment().getSeqrep().getCharAt(position)
388                     : (currentGroup.getSeqrep() != null
389                             ? currentGroup.getSeqrep().getCharAt(position)
390                             : av.getAlignment().getSeqrep()
391                                     .getCharAt(position)))
392             : (currentGroup != null && currentGroup.getConsensus() != null
393                     && position >= currentGroup.getStartRes()
394                     && position <= currentGroup.getEndRes()
395                     && currentGroup
396                             .getConsensus().annotations.length > position)
397                                     ? currentGroup
398                                             .getConsensus().annotations[position].displayCharacter
399                                                     .charAt(0)
400                                     : av.getAlignmentConsensusAnnotation().annotations[position].displayCharacter
401                                             .charAt(0);
402     if (!jalview.util.Comparison.isGap(conschar)
403             && (sequenceChar == conschar
404                     || sequenceChar + CHAR_TO_UPPER == conschar))
405     {
406       sequenceChar = conservedChar;
407     }
408     return sequenceChar;
409   }
410
411   /**
412    * DOCUMENT ME!
413    * 
414    * @param seq
415    *          DOCUMENT ME!
416    * @param start
417    *          DOCUMENT ME!
418    * @param end
419    *          DOCUMENT ME!
420    * @param x1
421    *          DOCUMENT ME!
422    * @param y1
423    *          DOCUMENT ME!
424    * @param width
425    *          DOCUMENT ME!
426    * @param height
427    *          DOCUMENT ME!
428    */
429   public void drawHighlightedText(SequenceI seq, int start, int end, int x1,
430           int y1)
431   {
432     int pady = av.getCharHeight() / 5;
433     int charOffset = 0;
434     graphics.setColor(Color.BLACK);
435     graphics.fillRect(x1, y1, av.getCharWidth() * (end - start + 1),
436             av.getCharHeight());
437     graphics.setColor(Color.white);
438
439     char s = '~';
440
441     // Need to find the sequence position here.
442     if (av.isValidCharWidth())
443     {
444       for (int i = start; i <= end; i++)
445       {
446         if (i < seq.getLength())
447         {
448           s = seq.getCharAt(i);
449         }
450
451         charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
452         graphics.drawString(String.valueOf(s),
453                 charOffset + x1 + (av.getCharWidth() * (i - start)),
454                 (y1 + av.getCharHeight()) - pady);
455       }
456     }
457   }
458
459   /**
460    * Draw a sequence canvas cursor
461    * 
462    * @param g
463    *          graphics context to draw on
464    * @param s
465    *          character to draw at cursor
466    * @param x1
467    *          x position of cursor in graphics context
468    * @param y1
469    *          y position of cursor in graphics context
470    */
471   public void drawCursor(Graphics g, char s, int x1, int y1)
472   {
473     int pady = av.getCharHeight() / 5;
474     int charOffset = 0;
475     g.setColor(Color.black);
476     g.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
477
478     if (av.isValidCharWidth())
479     {
480       g.setColor(Color.white);
481       charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
482       g.drawString(String.valueOf(s), charOffset + x1,
483               (y1 + av.getCharHeight()) - pady);
484     }
485
486   }
487 }