JAL-2665 OOM checks just in case
[jalview.git] / src / jalview / gui / SeqCanvas.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.datamodel.AlignmentI;
24 import jalview.datamodel.HiddenColumns;
25 import jalview.datamodel.SearchResultsI;
26 import jalview.datamodel.SequenceGroup;
27 import jalview.datamodel.SequenceI;
28 import jalview.renderer.ScaleRenderer;
29 import jalview.renderer.ScaleRenderer.ScaleMark;
30 import jalview.viewmodel.ViewportListenerI;
31 import jalview.viewmodel.ViewportRanges;
32
33 import java.awt.AlphaComposite;
34 import java.awt.BasicStroke;
35 import java.awt.BorderLayout;
36 import java.awt.Color;
37 import java.awt.FontMetrics;
38 import java.awt.Graphics;
39 import java.awt.Graphics2D;
40 import java.awt.RenderingHints;
41 import java.awt.Shape;
42 import java.awt.image.BufferedImage;
43 import java.beans.PropertyChangeEvent;
44 import java.util.List;
45
46 import javax.swing.JComponent;
47
48 /**
49  * DOCUMENT ME!
50  * 
51  * @author $author$
52  * @version $Revision$
53  */
54 public class SeqCanvas extends JComponent implements ViewportListenerI
55 {
56   private static String ZEROS = "0000000000";
57
58   final FeatureRenderer fr;
59
60   final SequenceRenderer seqRdr;
61
62   BufferedImage img;
63
64   Graphics2D gg;
65
66   AlignViewport av;
67
68   boolean fastPaint = false;
69
70   int labelWidthWest;
71
72   int labelWidthEast;
73
74   int cursorX = 0;
75
76   int cursorY = 0;
77
78   int charHeight = 0;
79
80   int charWidth = 0;
81
82   boolean fastpainting = false;
83
84   AnnotationPanel annotations;
85
86   /**
87    * Creates a new SeqCanvas object.
88    * 
89    * @param av
90    *          DOCUMENT ME!
91    */
92   public SeqCanvas(AlignmentPanel ap)
93   {
94     this.av = ap.av;
95     updateViewport();
96     fr = new FeatureRenderer(ap);
97     seqRdr = new SequenceRenderer(av);
98     setLayout(new BorderLayout());
99     PaintRefresher.Register(this, av.getSequenceSetId());
100     setBackground(Color.white);
101
102     av.getRanges().addPropertyChangeListener(this);
103   }
104
105   public SequenceRenderer getSequenceRenderer()
106   {
107     return seqRdr;
108   }
109
110   public FeatureRenderer getFeatureRenderer()
111   {
112     return fr;
113   }
114
115   private void updateViewport()
116   {
117     charHeight = av.getCharHeight();
118     charWidth = av.getCharWidth();
119   }
120
121   /**
122    * DOCUMENT ME!
123    * 
124    * @param g
125    *          DOCUMENT ME!
126    * @param startx
127    *          DOCUMENT ME!
128    * @param endx
129    *          DOCUMENT ME!
130    * @param ypos
131    *          DOCUMENT ME!
132    */
133   private void drawNorthScale(Graphics g, int startx, int endx, int ypos)
134   {
135     updateViewport();
136     for (ScaleMark mark : new ScaleRenderer().calculateMarks(av, startx,
137             endx))
138     {
139       int mpos = mark.column; // (i - startx - 1)
140       if (mpos < 0)
141       {
142         continue;
143       }
144       String mstring = mark.text;
145
146       if (mark.major)
147       {
148         if (mstring != null)
149         {
150           g.drawString(mstring, mpos * charWidth, ypos - (charHeight / 2));
151         }
152         g.drawLine((mpos * charWidth) + (charWidth / 2),
153                 (ypos + 2) - (charHeight / 2),
154                 (mpos * charWidth) + (charWidth / 2), ypos - 2);
155       }
156     }
157   }
158
159   /**
160    * DOCUMENT ME!
161    * 
162    * @param g
163    *          DOCUMENT ME!
164    * @param startx
165    *          DOCUMENT ME!
166    * @param endx
167    *          DOCUMENT ME!
168    * @param ypos
169    *          DOCUMENT ME!
170    */
171   void drawWestScale(Graphics g, int startx, int endx, int ypos)
172   {
173     FontMetrics fm = getFontMetrics(av.getFont());
174     ypos += charHeight;
175
176     if (av.hasHiddenColumns())
177     {
178       startx = av.getAlignment().getHiddenColumns()
179               .adjustForHiddenColumns(startx);
180       endx = av.getAlignment().getHiddenColumns()
181               .adjustForHiddenColumns(endx);
182     }
183
184     int maxwidth = av.getAlignment().getWidth();
185     if (av.hasHiddenColumns())
186     {
187       maxwidth = av.getAlignment().getHiddenColumns()
188               .findColumnPosition(maxwidth) - 1;
189     }
190
191     // WEST SCALE
192     for (int i = 0; i < av.getAlignment().getHeight(); i++)
193     {
194       SequenceI seq = av.getAlignment().getSequenceAt(i);
195       int index = startx;
196       int value = -1;
197
198       while (index < endx)
199       {
200         if (jalview.util.Comparison.isGap(seq.getCharAt(index)))
201         {
202           index++;
203
204           continue;
205         }
206
207         value = av.getAlignment().getSequenceAt(i).findPosition(index);
208
209         break;
210       }
211
212       if (value != -1)
213       {
214         int x = labelWidthWest - fm.stringWidth(String.valueOf(value))
215                 - charWidth / 2;
216         g.drawString(value + "", x,
217                 (ypos + (i * charHeight)) - (charHeight / 5));
218       }
219     }
220   }
221
222   /**
223    * DOCUMENT ME!
224    * 
225    * @param g
226    *          DOCUMENT ME!
227    * @param startx
228    *          DOCUMENT ME!
229    * @param endx
230    *          DOCUMENT ME!
231    * @param ypos
232    *          DOCUMENT ME!
233    */
234   void drawEastScale(Graphics g, int startx, int endx, int ypos)
235   {
236     ypos += charHeight;
237
238     if (av.hasHiddenColumns())
239     {
240       endx = av.getAlignment().getHiddenColumns()
241               .adjustForHiddenColumns(endx);
242     }
243
244     SequenceI seq;
245     // EAST SCALE
246     for (int i = 0; i < av.getAlignment().getHeight(); i++)
247     {
248       seq = av.getAlignment().getSequenceAt(i);
249       int index = endx;
250       int value = -1;
251
252       while (index > startx)
253       {
254         if (jalview.util.Comparison.isGap(seq.getCharAt(index)))
255         {
256           index--;
257
258           continue;
259         }
260
261         value = seq.findPosition(index);
262
263         break;
264       }
265
266       if (value != -1)
267       {
268         g.drawString(String.valueOf(value), 0,
269                 (ypos + (i * charHeight)) - (charHeight / 5));
270       }
271     }
272   }
273
274
275   /**
276    * need to make this thread safe move alignment rendering in response to
277    * slider adjustment
278    * 
279    * @param horizontal
280    *          shift along
281    * @param vertical
282    *          shift up or down in repaint
283    */
284   public void fastPaint(int horizontal, int vertical)
285   {
286     if (fastpainting || gg == null)
287     {
288       return;
289     }
290     fastpainting = true;
291     fastPaint = true;
292     updateViewport();
293
294     ViewportRanges ranges = av.getRanges();
295     int startRes = ranges.getStartRes();
296     int endRes = ranges.getEndRes();
297     int startSeq = ranges.getStartSeq();
298     int endSeq = ranges.getEndSeq();
299     int transX = 0;
300     int transY = 0;
301
302     gg.copyArea(horizontal * charWidth, vertical * charHeight,
303             img.getWidth(), img.getHeight(), -horizontal * charWidth,
304             -vertical * charHeight);
305
306     if (horizontal > 0) // scrollbar pulled right, image to the left
307     {
308       transX = (endRes - startRes - horizontal) * charWidth;
309       startRes = endRes - horizontal;
310     }
311     else if (horizontal < 0)
312     {
313       endRes = startRes - horizontal;
314     }
315     else if (vertical > 0) // scroll down
316     {
317       startSeq = endSeq - vertical;
318
319       if (startSeq < ranges.getStartSeq())
320       { // ie scrolling too fast, more than a page at a time
321         startSeq = ranges.getStartSeq();
322       }
323       else
324       {
325         transY = img.getHeight() - ((vertical + 1) * charHeight);
326       }
327     }
328     else if (vertical < 0)
329     {
330       endSeq = startSeq - vertical;
331
332       if (endSeq > ranges.getEndSeq())
333       {
334         endSeq = ranges.getEndSeq();
335       }
336     }
337
338     gg.translate(transX, transY);
339     drawPanel(gg, startRes, endRes, startSeq, endSeq, 0);
340     gg.translate(-transX, -transY);
341
342     repaint();
343     fastpainting = false;
344   }
345
346   @Override
347   public void paintComponent(Graphics g)
348   {
349     super.paintComponent(g);
350
351     updateViewport();
352
353     ViewportRanges ranges = av.getRanges();
354
355     int width = getWidth();
356     int height = getHeight();
357
358     width -= (width % charWidth);
359     height -= (height % charHeight);
360
361     // selectImage is the selection group outline image
362     BufferedImage selectImage = drawSelectionGroup(
363             ranges.getStartRes(), ranges.getEndRes(),
364             ranges.getStartSeq(), ranges.getEndSeq());
365
366     if ((img != null) && (fastPaint
367             || (getVisibleRect().width != g.getClipBounds().width)
368             || (getVisibleRect().height != g.getClipBounds().height)))
369     {
370       BufferedImage lcimg = buildLocalImage(selectImage);
371       g.drawImage(lcimg, 0, 0, this);
372       fastPaint = false;
373     }
374     else if ((width > 0) && (height > 0))
375     {
376       // img is a cached version of the last view we drew, if any
377       // if we have no img or the size has changed, make a new one
378       if (img == null || width != img.getWidth()
379               || height != img.getHeight())
380       {
381         img = setupImage();
382         if (img == null)
383         {
384           return;
385         }
386         gg = (Graphics2D) img.getGraphics();
387         gg.setFont(av.getFont());
388       }
389
390       if (av.antiAlias)
391       {
392         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
393                 RenderingHints.VALUE_ANTIALIAS_ON);
394       }
395
396       gg.setColor(Color.white);
397       gg.fillRect(0, 0, img.getWidth(), img.getHeight());
398
399       if (av.getWrapAlignment())
400       {
401         drawWrappedPanel(gg, getWidth(), getHeight(), ranges.getStartRes());
402       }
403       else
404       {
405         drawPanel(gg, ranges.getStartRes(), ranges.getEndRes(),
406                 ranges.getStartSeq(), ranges.getEndSeq(), 0);
407       }
408
409       // lcimg is a local *copy* of img which we'll draw selectImage on top of
410       BufferedImage lcimg = buildLocalImage(selectImage);
411       g.drawImage(lcimg, 0, 0, this);
412     }
413   }
414
415   /**
416    * Draw an alignment panel for printing
417    * 
418    * @param g1
419    *          Graphics object to draw with
420    * @param startRes
421    *          start residue of print area
422    * @param endRes
423    *          end residue of print area
424    * @param startSeq
425    *          start sequence of print area
426    * @param endSeq
427    *          end sequence of print area
428    */
429   public void drawPanelForPrinting(Graphics g1, int startRes, int endRes,
430           int startSeq, int endSeq)
431   {
432     BufferedImage selectImage = drawSelectionGroup(startRes, endRes,
433             startSeq, endSeq);
434     drawPanel(g1, startRes, endRes, startSeq, endSeq, 0);
435     ((Graphics2D) g1).setComposite(
436             AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
437     g1.drawImage(selectImage, 0, 0, this);
438   }
439
440   /**
441    * Draw a wrapped alignment panel for printing
442    * 
443    * @param g
444    *          Graphics object to draw with
445    * @param canvasWidth
446    *          width of drawing area
447    * @param canvasHeight
448    *          height of drawing area
449    * @param startRes
450    *          start residue of print area
451    */
452   public void drawWrappedPanelForPrinting(Graphics g, int canvasWidth,
453           int canvasHeight, int startRes)
454   {
455     SequenceGroup group = av.getSelectionGroup();
456
457     drawWrappedPanel(g, canvasWidth, canvasHeight, startRes);
458
459     if (group != null)
460     {
461       BufferedImage selectImage = null;
462       try
463       {
464         selectImage = new BufferedImage(canvasWidth, canvasHeight,
465                 BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
466       } catch (OutOfMemoryError er)
467       {
468         System.gc();
469         System.err.println("Print image OutOfMemory Error.\n" + er);
470         new OOMWarning("Creating wrapped alignment image for printing", er);
471       }
472       if (selectImage != null)
473       {
474         Graphics2D g2 = selectImage.createGraphics();
475         setupSelectionGroup(g2, selectImage);
476         drawWrappedSelection(g2, group, canvasWidth, canvasHeight,
477                 startRes);
478
479         g2.setComposite(
480                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
481         g.drawImage(selectImage, 0, 0, this);
482         g2.dispose();
483       }
484     }
485   }
486
487   /*
488    * Make a local image by combining the cached image img
489    * with any selection
490    */
491   private BufferedImage buildLocalImage(BufferedImage selectImage)
492   {
493     // clone the cached image
494     BufferedImage lcimg = new BufferedImage(img.getWidth(), img.getHeight(),
495             img.getType());
496     Graphics2D g2d = lcimg.createGraphics();
497     g2d.drawImage(img, 0, 0, null);
498
499     // overlay selection group on lcimg
500     if (selectImage != null)
501     {
502       g2d.setComposite(
503               AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
504       g2d.drawImage(selectImage, 0, 0, this);
505     }
506     g2d.dispose();
507
508     return lcimg;
509   }
510
511   /*
512    * Set up a buffered image of the correct height and size for the sequence canvas
513    */
514   private BufferedImage setupImage()
515   {
516     BufferedImage lcimg = null;
517
518     int width = getWidth();
519     int height = getHeight();
520
521     width -= (width % charWidth);
522     height -= (height % charHeight);
523
524     if ((width < 1) || (height < 1))
525     {
526       return null;
527     }
528
529     try
530     {
531       lcimg = new BufferedImage(width, height,
532               BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
533     } catch (OutOfMemoryError er)
534     {
535       System.gc();
536       System.err.println(
537               "Group image OutOfMemory Redraw Error.\n" + er);
538       new OOMWarning("Creating alignment image for display", er);
539
540       return null;
541     }
542
543     return lcimg;
544   }
545
546   /**
547    * Returns the visible width of the canvas in residues, after allowing for
548    * East or West scales (if shown)
549    * 
550    * @param canvasWidth
551    *          the width in pixels (possibly including scales)
552    * 
553    * @return
554    */
555   public int getWrappedCanvasWidth(int canvasWidth)
556   {
557     FontMetrics fm = getFontMetrics(av.getFont());
558
559     labelWidthEast = 0;
560     labelWidthWest = 0;
561
562     if (av.getScaleRightWrapped())
563     {
564       labelWidthEast = getLabelWidth(fm);
565     }
566
567     if (av.getScaleLeftWrapped())
568     {
569       labelWidthWest = labelWidthEast > 0 ? labelWidthEast
570               : getLabelWidth(fm);
571     }
572
573     return (canvasWidth - labelWidthEast - labelWidthWest) / charWidth;
574   }
575
576   /**
577    * Returns a pixel width suitable for showing the largest sequence coordinate
578    * (end position) in the alignment. Returns 2 plus the number of decimal
579    * digits to be shown (3 for 1-10, 4 for 11-99 etc).
580    * 
581    * @param fm
582    * @return
583    */
584   protected int getLabelWidth(FontMetrics fm)
585   {
586     /*
587      * find the biggest sequence end position we need to show
588      * (note this is not necessarily the sequence length)
589      */
590     int maxWidth = 0;
591     AlignmentI alignment = av.getAlignment();
592     for (int i = 0; i < alignment.getHeight(); i++)
593     {
594       maxWidth = Math.max(maxWidth, alignment.getSequenceAt(i).getEnd());
595     }
596
597     int length = 2;
598     for (int i = maxWidth; i > 0; i /= 10)
599     {
600       length++;
601     }
602
603     return fm.stringWidth(ZEROS.substring(0, length));
604   }
605
606   /**
607    * DOCUMENT ME!
608    * 
609    * @param g
610    *          DOCUMENT ME!
611    * @param canvasWidth
612    *          DOCUMENT ME!
613    * @param canvasHeight
614    *          DOCUMENT ME!
615    * @param startRes
616    *          DOCUMENT ME!
617    */
618   private void drawWrappedPanel(Graphics g, int canvasWidth,
619           int canvasHeight, int startRes)
620   {
621     updateViewport();
622     AlignmentI al = av.getAlignment();
623
624     int labelWidth = 0;
625     if (av.getScaleRightWrapped() || av.getScaleLeftWrapped())
626     {
627       FontMetrics fm = getFontMetrics(av.getFont());
628       labelWidth = getLabelWidth(fm);
629     }
630
631     labelWidthEast = av.getScaleRightWrapped() ? labelWidth : 0;
632     labelWidthWest = av.getScaleLeftWrapped() ? labelWidth : 0;
633
634     int hgap = charHeight;
635     if (av.getScaleAboveWrapped())
636     {
637       hgap += charHeight;
638     }
639
640     int cWidth = (canvasWidth - labelWidthEast - labelWidthWest) / charWidth;
641     int cHeight = av.getAlignment().getHeight() * charHeight;
642
643     av.setWrappedWidth(cWidth);
644
645     av.getRanges().setViewportStartAndWidth(startRes, cWidth);
646
647     int endx;
648     int ypos = hgap;
649     int maxwidth = av.getAlignment().getWidth();
650
651     if (av.hasHiddenColumns())
652     {
653       maxwidth = av.getAlignment().getHiddenColumns()
654               .findColumnPosition(maxwidth);
655     }
656
657     int annotationHeight = getAnnotationHeight();
658
659     while ((ypos <= canvasHeight) && (startRes < maxwidth))
660     {
661       endx = startRes + cWidth - 1;
662
663       if (endx > maxwidth)
664       {
665         endx = maxwidth;
666       }
667
668       g.setFont(av.getFont());
669       g.setColor(Color.black);
670
671       if (av.getScaleLeftWrapped())
672       {
673         drawWestScale(g, startRes, endx, ypos);
674       }
675
676       if (av.getScaleRightWrapped())
677       {
678         g.translate(canvasWidth - labelWidthEast, 0);
679         drawEastScale(g, startRes, endx, ypos);
680         g.translate(-(canvasWidth - labelWidthEast), 0);
681       }
682
683       g.translate(labelWidthWest, 0);
684
685       if (av.getScaleAboveWrapped())
686       {
687         drawNorthScale(g, startRes, endx, ypos);
688       }
689
690       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
691       {
692         g.setColor(Color.blue);
693         int res;
694         HiddenColumns hidden = av.getAlignment().getHiddenColumns();
695         List<Integer> positions = hidden.findHiddenRegionPositions();
696         for (int pos : positions)
697         {
698           res = pos - startRes;
699
700           if (res < 0 || res > endx - startRes)
701           {
702             continue;
703           }
704
705           gg.fillPolygon(
706                   new int[]
707                   { res * charWidth - charHeight / 4,
708                       res * charWidth + charHeight / 4, res * charWidth },
709                   new int[]
710                   { ypos - (charHeight / 2), ypos - (charHeight / 2),
711                       ypos - (charHeight / 2) + 8 },
712                   3);
713
714         }
715       }
716
717       // When printing we have an extra clipped region,
718       // the Printable page which we need to account for here
719       Shape clip = g.getClip();
720
721       if (clip == null)
722       {
723         g.setClip(0, 0, cWidth * charWidth, canvasHeight);
724       }
725       else
726       {
727         g.setClip(0, (int) clip.getBounds().getY(), cWidth * charWidth,
728                 (int) clip.getBounds().getHeight());
729       }
730
731       drawPanel(g, startRes, endx, 0, al.getHeight() - 1, ypos);
732
733       if (av.isShowAnnotation())
734       {
735         g.translate(0, cHeight + ypos + 3);
736         if (annotations == null)
737         {
738           annotations = new AnnotationPanel(av);
739         }
740
741         annotations.renderer.drawComponent(annotations, av, g, -1, startRes,
742                 endx + 1);
743         g.translate(0, -cHeight - ypos - 3);
744       }
745       g.setClip(clip);
746       g.translate(-labelWidthWest, 0);
747
748       ypos += cHeight + annotationHeight + hgap;
749
750       startRes += cWidth;
751     }
752   }
753
754   /*
755    * Draw a selection group over a wrapped alignment
756    */
757   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
758           int canvasWidth,
759           int canvasHeight, int startRes)
760   {
761     // height gap above each panel
762     int hgap = charHeight;
763     if (av.getScaleAboveWrapped())
764     {
765       hgap += charHeight;
766     }
767
768     int cWidth = (canvasWidth - labelWidthEast - labelWidthWest)
769             / charWidth;
770     int cHeight = av.getAlignment().getHeight() * charHeight;
771
772     int startx = startRes;
773     int endx;
774     int ypos = hgap; // vertical offset
775     int maxwidth = av.getAlignment().getWidth();
776
777     if (av.hasHiddenColumns())
778     {
779       maxwidth = av.getAlignment().getHiddenColumns()
780               .findColumnPosition(maxwidth);
781     }
782
783     // chop the wrapped alignment extent up into panel-sized blocks and treat
784     // each block as if it were a block from an unwrapped alignment
785     while ((ypos <= canvasHeight) && (startx < maxwidth))
786     {
787       // set end value to be start + width, or maxwidth, whichever is smaller
788       endx = startx + cWidth - 1;
789
790       if (endx > maxwidth)
791       {
792         endx = maxwidth;
793       }
794
795       g.translate(labelWidthWest, 0);
796
797       drawUnwrappedSelection(g, group, startx, endx, 0,
798               av.getAlignment().getHeight() - 1,
799               ypos);
800
801       g.translate(-labelWidthWest, 0);
802
803       // update vertical offset
804       ypos += cHeight + getAnnotationHeight() + hgap;
805
806       // update horizontal offset
807       startx += cWidth;
808     }
809   }
810
811   int getAnnotationHeight()
812   {
813     if (!av.isShowAnnotation())
814     {
815       return 0;
816     }
817
818     if (annotations == null)
819     {
820       annotations = new AnnotationPanel(av);
821     }
822
823     return annotations.adjustPanelHeight();
824   }
825
826
827   /**
828    * Draws the visible region of the alignment on the graphics context. If there
829    * are hidden column markers in the visible region, then each sub-region
830    * between the markers is drawn separately, followed by the hidden column
831    * marker.
832    * 
833    * @param g1
834    *          Graphics object to draw with
835    * @param startRes
836    *          offset of the first column in the visible region (0..)
837    * @param endRes
838    *          offset of the last column in the visible region (0..)
839    * @param startSeq
840    *          offset of the first sequence in the visible region (0..)
841    * @param endSeq
842    *          offset of the last sequence in the visible region (0..)
843    * @param yOffset
844    *          vertical offset at which to draw (for wrapped alignments)
845    */
846   private void drawPanel(Graphics g1, int startRes, int endRes,
847           int startSeq, int endSeq, int yOffset)
848
849   {
850     updateViewport();
851     if (!av.hasHiddenColumns())
852     {
853       draw(g1, startRes, endRes, startSeq, endSeq, yOffset);
854     }
855     else
856     {
857       int screenY = 0;
858       final int screenYMax = endRes - startRes;
859       int blockStart = startRes;
860       int blockEnd = endRes;
861
862       for (int[] region : av.getAlignment().getHiddenColumns()
863               .getHiddenColumnsCopy())
864       {
865         int hideStart = region[0];
866         int hideEnd = region[1];
867
868         if (hideStart <= blockStart)
869         {
870           blockStart += (hideEnd - hideStart) + 1;
871           continue;
872         }
873
874         /*
875          * draw up to just before the next hidden region, or the end of
876          * the visible region, whichever comes first
877          */
878         blockEnd = Math.min(hideStart - 1, blockStart + screenYMax
879                 - screenY);
880
881         g1.translate(screenY * charWidth, 0);
882
883         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
884
885         /*
886          * draw the downline of the hidden column marker (ScalePanel draws the
887          * triangle on top) if we reached it
888          */
889         if (av.getShowHiddenMarkers() && blockEnd == hideStart - 1)
890         {
891           g1.setColor(Color.blue);
892
893           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
894                   0 + yOffset, (blockEnd - blockStart + 1) * charWidth - 1,
895                   (endSeq - startSeq + 1) * charHeight + yOffset);
896         }
897
898         g1.translate(-screenY * charWidth, 0);
899         screenY += blockEnd - blockStart + 1;
900         blockStart = hideEnd + 1;
901
902         if (screenY > screenYMax)
903         {
904           // already rendered last block
905           return;
906         }
907       }
908
909       if (screenY <= screenYMax)
910       {
911         // remaining visible region to render
912         blockEnd = blockStart + screenYMax - screenY;
913         g1.translate(screenY * charWidth, 0);
914         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
915
916         g1.translate(-screenY * charWidth, 0);
917       }
918     }
919
920   }
921
922
923   /**
924    * Draws a region of the visible alignment
925    * 
926    * @param g1
927    * @param startRes
928    *          offset of the first column in the visible region (0..)
929    * @param endRes
930    *          offset of the last column in the visible region (0..)
931    * @param startSeq
932    *          offset of the first sequence in the visible region (0..)
933    * @param endSeq
934    *          offset of the last sequence in the visible region (0..)
935    * @param yOffset
936    *          vertical offset at which to draw (for wrapped alignments)
937    */
938   private void draw(Graphics g, int startRes, int endRes, int startSeq,
939           int endSeq, int offset)
940   {
941     g.setFont(av.getFont());
942     seqRdr.prepare(g, av.isRenderGaps());
943
944     SequenceI nextSeq;
945
946     // / First draw the sequences
947     // ///////////////////////////
948     for (int i = startSeq; i <= endSeq; i++)
949     {
950       nextSeq = av.getAlignment().getSequenceAt(i);
951       if (nextSeq == null)
952       {
953         // occasionally, a race condition occurs such that the alignment row is
954         // empty
955         continue;
956       }
957       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
958               startRes, endRes, offset + ((i - startSeq) * charHeight));
959
960       if (av.isShowSequenceFeatures())
961       {
962         fr.drawSequence(g, nextSeq, startRes, endRes,
963                 offset + ((i - startSeq) * charHeight), false);
964       }
965
966       /*
967        * highlight search Results once sequence has been drawn
968        */
969       if (av.hasSearchResults())
970       {
971         SearchResultsI searchResults = av.getSearchResults();
972         int[] visibleResults = searchResults.getResults(nextSeq,
973                 startRes, endRes);
974         if (visibleResults != null)
975         {
976           for (int r = 0; r < visibleResults.length; r += 2)
977           {
978             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
979                     visibleResults[r + 1], (visibleResults[r] - startRes)
980                             * charWidth, offset
981                             + ((i - startSeq) * charHeight));
982           }
983         }
984       }
985
986       if (av.cursorMode && cursorY == i && cursorX >= startRes
987               && cursorX <= endRes)
988       {
989         seqRdr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
990                 offset + ((i - startSeq) * charHeight));
991       }
992     }
993
994     if (av.getSelectionGroup() != null
995             || av.getAlignment().getGroups().size() > 0)
996     {
997       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
998     }
999
1000   }
1001
1002   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
1003           int startSeq, int endSeq, int offset)
1004   {
1005     Graphics2D g = (Graphics2D) g1;
1006     //
1007     // ///////////////////////////////////
1008     // Now outline any areas if necessary
1009     // ///////////////////////////////////
1010
1011     SequenceGroup group = null;
1012     int groupIndex = -1;
1013
1014     if (av.getAlignment().getGroups().size() > 0)
1015     {
1016       group = av.getAlignment().getGroups().get(0);
1017       groupIndex = 0;
1018     }
1019
1020     if (group != null)
1021     {
1022       g.setStroke(new BasicStroke());
1023       g.setColor(group.getOutlineColour());
1024       
1025       do
1026       {
1027         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
1028                 endSeq, offset);
1029         
1030         groupIndex++;
1031
1032         g.setStroke(new BasicStroke());
1033
1034         if (groupIndex >= av.getAlignment().getGroups().size())
1035         {
1036           break;
1037         }
1038
1039         group = av.getAlignment().getGroups().get(groupIndex);
1040
1041       } while (groupIndex < av.getAlignment().getGroups().size());
1042
1043     }
1044
1045   }
1046
1047
1048   /*
1049    * Draw the selection group as a separate image and overlay
1050    */
1051   private BufferedImage drawSelectionGroup(int startRes, int endRes,
1052           int startSeq, int endSeq)
1053   {
1054     // get a new image of the correct size
1055     BufferedImage selectionImage = setupImage();
1056
1057     if (selectionImage == null)
1058     {
1059       return null;
1060     }
1061
1062     SequenceGroup group = av.getSelectionGroup();
1063     if (group == null)
1064     {
1065       // nothing to draw
1066       return null;
1067     }
1068
1069     // set up drawing colour
1070     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1071
1072     setupSelectionGroup(g, selectionImage);
1073
1074     if (!av.getWrapAlignment())
1075     {
1076       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1077               0);
1078     }
1079     else
1080     {
1081       drawWrappedSelection(g, group, getWidth(), getHeight(),
1082               av.getRanges().getStartRes());
1083     }
1084
1085     g.dispose();
1086     return selectionImage;
1087   }
1088
1089   /*
1090    * Set up graphics for selection group
1091    */
1092   private void setupSelectionGroup(Graphics2D g,
1093           BufferedImage selectionImage)
1094   {
1095     // set background to transparent
1096     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1097     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1098
1099     // set up foreground to draw red dashed line
1100     g.setComposite(AlphaComposite.Src);
1101     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1102             BasicStroke.JOIN_ROUND, 3f, new float[]
1103     { 5f, 3f }, 0f));
1104     g.setColor(Color.RED);
1105   }
1106
1107   /*
1108    * Draw a selection group over an unwrapped alignment
1109    * @param g graphics object to draw with
1110    * @param group selection group
1111    * @param startRes start residue of area to draw
1112    * @param endRes end residue of area to draw
1113    * @param startSeq start sequence of area to draw
1114    * @param endSeq end sequence of area to draw
1115    * @param offset vertical offset (used when called from wrapped alignment code)
1116    */
1117   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1118           int startRes, int endRes, int startSeq, int endSeq, int offset)
1119   {
1120     if (!av.hasHiddenColumns())
1121     {
1122       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1123               offset);
1124     }
1125     else
1126     {
1127       // package into blocks of visible columns
1128       int screenY = 0;
1129       int blockStart = startRes;
1130       int blockEnd = endRes;
1131
1132       for (int[] region : av.getAlignment().getHiddenColumns()
1133               .getHiddenColumnsCopy())
1134       {
1135         int hideStart = region[0];
1136         int hideEnd = region[1];
1137
1138         if (hideStart <= blockStart)
1139         {
1140           blockStart += (hideEnd - hideStart) + 1;
1141           continue;
1142         }
1143
1144         blockEnd = hideStart - 1;
1145
1146         g.translate(screenY * charWidth, 0);
1147         drawPartialGroupOutline(g, group,
1148                 blockStart, blockEnd, startSeq, endSeq, offset);
1149
1150         g.translate(-screenY * charWidth, 0);
1151         screenY += blockEnd - blockStart + 1;
1152         blockStart = hideEnd + 1;
1153
1154         if (screenY > (endRes - startRes))
1155         {
1156           // already rendered last block
1157           break;
1158         }
1159       }
1160
1161       if (screenY <= (endRes - startRes))
1162       {
1163         // remaining visible region to render
1164         blockEnd = blockStart + (endRes - startRes) - screenY;
1165         g.translate(screenY * charWidth, 0);
1166         drawPartialGroupOutline(g, group,
1167                 blockStart, blockEnd, startSeq, endSeq, offset);
1168         
1169         g.translate(-screenY * charWidth, 0);
1170       }
1171     }
1172   }
1173
1174   /*
1175    * Draw the selection group as a separate image and overlay
1176    */
1177   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1178           int startRes, int endRes, int startSeq, int endSeq,
1179           int verticalOffset)
1180   {
1181     int visWidth = (endRes - startRes + 1) * charWidth;
1182
1183     int oldY = -1;
1184     int i = 0;
1185     boolean inGroup = false;
1186     int top = -1;
1187     int bottom = -1;
1188
1189     int sx = -1;
1190     int sy = -1;
1191     int xwidth = -1;
1192
1193     for (i = startSeq; i <= endSeq; i++)
1194     {
1195       // position of start residue of group relative to startRes, in pixels
1196       sx = (group.getStartRes() - startRes) * charWidth;
1197
1198       // width of group in pixels
1199       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1200               - 1;
1201
1202       sy = verticalOffset + (i - startSeq) * charHeight;
1203
1204       if (sx + xwidth < 0 || sx > visWidth)
1205       {
1206         continue;
1207       }
1208
1209       if ((sx <= (endRes - startRes) * charWidth)
1210               && group.getSequences(null)
1211                       .contains(av.getAlignment().getSequenceAt(i)))
1212       {
1213         if ((bottom == -1) && !group.getSequences(null)
1214                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1215         {
1216           bottom = sy + charHeight;
1217         }
1218
1219         if (!inGroup)
1220         {
1221           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1222                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1223           {
1224             top = sy;
1225           }
1226
1227           oldY = sy;
1228           inGroup = true;
1229         }
1230       }
1231       else
1232       {
1233         if (inGroup)
1234         {
1235           // if start position is visible, draw vertical line to left of
1236           // group
1237           if (sx >= 0 && sx < visWidth)
1238           {
1239             g.drawLine(sx, oldY, sx, sy);
1240           }
1241
1242           // if end position is visible, draw vertical line to right of
1243           // group
1244           if (sx + xwidth < visWidth)
1245           {
1246             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1247           }
1248
1249           if (sx < 0)
1250           {
1251             xwidth += sx;
1252             sx = 0;
1253           }
1254
1255           // don't let width extend beyond current block, or group extent
1256           // fixes JAL-2672
1257           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1258           {
1259             xwidth = (endRes - startRes + 1) * charWidth - sx;
1260           }
1261           
1262           // draw horizontal line at top of group
1263           if (top != -1)
1264           {
1265             g.drawLine(sx, top, sx + xwidth, top);
1266             top = -1;
1267           }
1268
1269           // draw horizontal line at bottom of group
1270           if (bottom != -1)
1271           {
1272             g.drawLine(sx, bottom, sx + xwidth, bottom);
1273             bottom = -1;
1274           }
1275
1276           inGroup = false;
1277         }
1278       }
1279     }
1280
1281     if (inGroup)
1282     {
1283       sy = verticalOffset + ((i - startSeq) * charHeight);
1284       if (sx >= 0 && sx < visWidth)
1285       {
1286         g.drawLine(sx, oldY, sx, sy);
1287       }
1288
1289       if (sx + xwidth < visWidth)
1290       {
1291         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1292       }
1293
1294       if (sx < 0)
1295       {
1296         xwidth += sx;
1297         sx = 0;
1298       }
1299
1300       if (sx + xwidth > visWidth)
1301       {
1302         xwidth = visWidth;
1303       }
1304       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1305       {
1306         xwidth = (endRes - startRes + 1) * charWidth;
1307       }
1308
1309       if (top != -1)
1310       {
1311         g.drawLine(sx, top, sx + xwidth, top);
1312         top = -1;
1313       }
1314
1315       if (bottom != -1)
1316       {
1317         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1318         bottom = -1;
1319       }
1320
1321       inGroup = false;
1322     }
1323   }
1324   
1325   /**
1326    * Highlights search results in the visible region by rendering as white text
1327    * on a black background. Any previous highlighting is removed. Answers true
1328    * if any highlight was left on the visible alignment (so status bar should be
1329    * set to match), else false.
1330    * <p>
1331    * Currently fastPaint is not implemented for wrapped alignments. If a wrapped
1332    * alignment had to be scrolled to show the highlighted region, then it should
1333    * be fully redrawn, otherwise a fast paint can be performed. This argument
1334    * could be removed if fast paint of scrolled wrapped alignment is coded in
1335    * future (JAL-2609).
1336    * 
1337    * @param results
1338    * @param noFastPaint
1339    * @return
1340    */
1341   public boolean highlightSearchResults(SearchResultsI results,
1342           boolean noFastPaint)
1343   {
1344     if (fastpainting)
1345     {
1346       return false;
1347     }
1348     boolean wrapped = av.getWrapAlignment();
1349
1350     try
1351     {
1352       fastPaint = !noFastPaint;
1353       fastpainting = fastPaint;
1354
1355       updateViewport();
1356
1357       /*
1358        * to avoid redrawing the whole visible region, we instead
1359        * redraw just the minimal regions to remove previous highlights
1360        * and add new ones
1361        */
1362       SearchResultsI previous = av.getSearchResults();
1363       av.setSearchResults(results);
1364       boolean redrawn = false;
1365       boolean drawn = false;
1366       if (wrapped)
1367       {
1368         redrawn = drawMappedPositionsWrapped(previous);
1369         drawn = drawMappedPositionsWrapped(results);
1370         redrawn |= drawn;
1371       }
1372       else
1373       {
1374         redrawn = drawMappedPositions(previous);
1375         drawn = drawMappedPositions(results);
1376         redrawn |= drawn;
1377       }
1378
1379       /*
1380        * if highlights were either removed or added, repaint
1381        */
1382       if (redrawn)
1383       {
1384         repaint();
1385       }
1386
1387       /*
1388        * return true only if highlights were added
1389        */
1390       return drawn;
1391
1392     } finally
1393     {
1394       fastpainting = false;
1395     }
1396   }
1397
1398   /**
1399    * Redraws the minimal rectangle in the visible region (if any) that includes
1400    * mapped positions of the given search results. Whether or not positions are
1401    * highlighted depends on the SearchResults set on the Viewport. This allows
1402    * this method to be called to either clear or set highlighting. Answers true
1403    * if any positions were drawn (in which case a repaint is still required),
1404    * else false.
1405    * 
1406    * @param results
1407    * @return
1408    */
1409   protected boolean drawMappedPositions(SearchResultsI results)
1410   {
1411     if (results == null)
1412     {
1413       return false;
1414     }
1415
1416     /*
1417      * calculate the minimal rectangle to redraw that 
1418      * includes both new and existing search results
1419      */
1420     int firstSeq = Integer.MAX_VALUE;
1421     int lastSeq = -1;
1422     int firstCol = Integer.MAX_VALUE;
1423     int lastCol = -1;
1424     boolean matchFound = false;
1425
1426     ViewportRanges ranges = av.getRanges();
1427     int firstVisibleColumn = ranges.getStartRes();
1428     int lastVisibleColumn = ranges.getEndRes();
1429     AlignmentI alignment = av.getAlignment();
1430     if (av.hasHiddenColumns())
1431     {
1432       firstVisibleColumn = alignment.getHiddenColumns()
1433               .adjustForHiddenColumns(firstVisibleColumn);
1434       lastVisibleColumn = alignment.getHiddenColumns()
1435               .adjustForHiddenColumns(lastVisibleColumn);
1436     }
1437
1438     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1439             .getEndSeq(); seqNo++)
1440     {
1441       SequenceI seq = alignment.getSequenceAt(seqNo);
1442
1443       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1444               lastVisibleColumn);
1445       if (visibleResults != null)
1446       {
1447         for (int i = 0; i < visibleResults.length - 1; i += 2)
1448         {
1449           int firstMatchedColumn = visibleResults[i];
1450           int lastMatchedColumn = visibleResults[i + 1];
1451           if (firstMatchedColumn <= lastVisibleColumn
1452                   && lastMatchedColumn >= firstVisibleColumn)
1453           {
1454             /*
1455              * found a search results match in the visible region - 
1456              * remember the first and last sequence matched, and the first
1457              * and last visible columns in the matched positions
1458              */
1459             matchFound = true;
1460             firstSeq = Math.min(firstSeq, seqNo);
1461             lastSeq = Math.max(lastSeq, seqNo);
1462             firstMatchedColumn = Math.max(firstMatchedColumn,
1463                     firstVisibleColumn);
1464             lastMatchedColumn = Math.min(lastMatchedColumn,
1465                     lastVisibleColumn);
1466             firstCol = Math.min(firstCol, firstMatchedColumn);
1467             lastCol = Math.max(lastCol, lastMatchedColumn);
1468           }
1469         }
1470       }
1471     }
1472
1473     if (matchFound)
1474     {
1475       if (av.hasHiddenColumns())
1476       {
1477         firstCol = alignment.getHiddenColumns()
1478                 .findColumnPosition(firstCol);
1479         lastCol = alignment.getHiddenColumns().findColumnPosition(lastCol);
1480       }
1481       int transX = (firstCol - ranges.getStartRes()) * av.getCharWidth();
1482       int transY = (firstSeq - ranges.getStartSeq()) * av.getCharHeight();
1483       gg.translate(transX, transY);
1484       drawPanel(gg, firstCol, lastCol, firstSeq, lastSeq, 0);
1485       gg.translate(-transX, -transY);
1486     }
1487
1488     return matchFound;
1489   }
1490
1491   @Override
1492   public void propertyChange(PropertyChangeEvent evt)
1493   {
1494     String eventName = evt.getPropertyName();
1495
1496     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1497     {
1498       fastPaint = true;
1499       repaint();
1500     }
1501     else if (av.getWrapAlignment())
1502     {
1503       if (eventName.equals(ViewportRanges.STARTRES))
1504       {
1505         repaint();
1506       }
1507     }
1508     else
1509     {
1510       int scrollX = 0;
1511       if (eventName.equals(ViewportRanges.STARTRES))
1512       {
1513         // Make sure we're not trying to draw a panel
1514         // larger than the visible window
1515         ViewportRanges vpRanges = av.getRanges();
1516         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1517         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1518         if (scrollX > range)
1519         {
1520           scrollX = range;
1521         }
1522         else if (scrollX < -range)
1523         {
1524           scrollX = -range;
1525         }
1526       }
1527
1528       // Both scrolling and resizing change viewport ranges: scrolling changes
1529       // both start and end points, but resize only changes end values.
1530       // Here we only want to fastpaint on a scroll, with resize using a normal
1531       // paint, so scroll events are identified as changes to the horizontal or
1532       // vertical start value.
1533       if (eventName.equals(ViewportRanges.STARTRES))
1534       {
1535         // scroll - startres and endres both change
1536         fastPaint(scrollX, 0);
1537       }
1538       else if (eventName.equals(ViewportRanges.STARTSEQ))
1539       {
1540         // scroll
1541         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1542       }
1543     }
1544   }
1545
1546   /**
1547    * Redraws any positions in the search results in the visible region of a
1548    * wrapped alignment. Any highlights are drawn depending on the search results
1549    * set on the Viewport, not the <code>results</code> argument. This allows
1550    * this method to be called either to clear highlights (passing the previous
1551    * search results), or to draw new highlights.
1552    * 
1553    * @param results
1554    * @return
1555    */
1556   protected boolean drawMappedPositionsWrapped(SearchResultsI results)
1557   {
1558     if (results == null)
1559     {
1560       return false;
1561     }
1562   
1563     boolean matchFound = false;
1564
1565     int wrappedWidth = av.getWrappedWidth();
1566     int wrappedHeight = getRepeatHeightWrapped();
1567
1568     ViewportRanges ranges = av.getRanges();
1569     int canvasHeight = getHeight();
1570     int repeats = canvasHeight / wrappedHeight;
1571     if (canvasHeight / wrappedHeight > 0)
1572     {
1573       repeats++;
1574     }
1575
1576     int firstVisibleColumn = ranges.getStartRes();
1577     int lastVisibleColumn = ranges.getStartRes() + repeats
1578             * ranges.getViewportWidth() - 1;
1579
1580     AlignmentI alignment = av.getAlignment();
1581     if (av.hasHiddenColumns())
1582     {
1583       firstVisibleColumn = alignment.getHiddenColumns()
1584               .adjustForHiddenColumns(firstVisibleColumn);
1585       lastVisibleColumn = alignment.getHiddenColumns()
1586               .adjustForHiddenColumns(lastVisibleColumn);
1587     }
1588
1589     int gapHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
1590
1591     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1592             .getEndSeq(); seqNo++)
1593     {
1594       SequenceI seq = alignment.getSequenceAt(seqNo);
1595
1596       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1597               lastVisibleColumn);
1598       if (visibleResults != null)
1599       {
1600         for (int i = 0; i < visibleResults.length - 1; i += 2)
1601         {
1602           int firstMatchedColumn = visibleResults[i];
1603           int lastMatchedColumn = visibleResults[i + 1];
1604           if (firstMatchedColumn <= lastVisibleColumn
1605                   && lastMatchedColumn >= firstVisibleColumn)
1606           {
1607             /*
1608              * found a search results match in the visible region
1609              */
1610             firstMatchedColumn = Math.max(firstMatchedColumn,
1611                     firstVisibleColumn);
1612             lastMatchedColumn = Math.min(lastMatchedColumn,
1613                     lastVisibleColumn);
1614
1615             /*
1616              * draw each mapped position separately (as contiguous positions may
1617              * wrap across lines)
1618              */
1619             for (int mappedPos = firstMatchedColumn; mappedPos <= lastMatchedColumn; mappedPos++)
1620             {
1621               int displayColumn = mappedPos;
1622               if (av.hasHiddenColumns())
1623               {
1624                 displayColumn = alignment.getHiddenColumns()
1625                         .findColumnPosition(displayColumn);
1626               }
1627
1628               /*
1629                * transX: offset from left edge of canvas to residue position
1630                */
1631               int transX = labelWidthWest
1632                       + ((displayColumn - ranges.getStartRes()) % wrappedWidth)
1633                       * av.getCharWidth();
1634
1635               /*
1636                * transY: offset from top edge of canvas to residue position
1637                */
1638               int transY = gapHeight;
1639               transY += (displayColumn - ranges.getStartRes())
1640                       / wrappedWidth * wrappedHeight;
1641               transY += (seqNo - ranges.getStartSeq()) * av.getCharHeight();
1642
1643               /*
1644                * yOffset is from graphics origin to start of visible region
1645                */
1646               int yOffset = 0;// (displayColumn / wrappedWidth) * wrappedHeight;
1647               if (transY < getHeight())
1648               {
1649                 matchFound = true;
1650                 gg.translate(transX, transY);
1651                 drawPanel(gg, displayColumn, displayColumn, seqNo, seqNo,
1652                         yOffset);
1653                 gg.translate(-transX, -transY);
1654               }
1655             }
1656           }
1657         }
1658       }
1659     }
1660   
1661     return matchFound;
1662   }
1663
1664   /**
1665    * Answers the height in pixels of a repeating section of the wrapped
1666    * alignment, including space above, scale above if shown, sequences, and
1667    * annotation panel if shown
1668    * 
1669    * @return
1670    */
1671   protected int getRepeatHeightWrapped()
1672   {
1673     // gap (and maybe scale) above
1674     int repeatHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
1675
1676     // add sequences
1677     repeatHeight += av.getRanges().getViewportHeight() * charHeight;
1678
1679     // add annotations panel height if shown
1680     repeatHeight += getAnnotationHeight();
1681
1682     return repeatHeight;
1683   }
1684 }