JAL-2647 Added iterators and associated tests and benchmarks
[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.Iterator;
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 || img == 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     drawPanel(g1, startRes, endRes, startSeq, endSeq, 0);
433
434     BufferedImage selectImage = drawSelectionGroup(startRes, endRes,
435             startSeq, endSeq);
436     if (selectImage != null)
437     {
438       ((Graphics2D) g1).setComposite(AlphaComposite
439               .getInstance(AlphaComposite.SRC_OVER));
440       g1.drawImage(selectImage, 0, 0, this);
441     }
442   }
443
444   /**
445    * Draw a wrapped alignment panel for printing
446    * 
447    * @param g
448    *          Graphics object to draw with
449    * @param canvasWidth
450    *          width of drawing area
451    * @param canvasHeight
452    *          height of drawing area
453    * @param startRes
454    *          start residue of print area
455    */
456   public void drawWrappedPanelForPrinting(Graphics g, int canvasWidth,
457           int canvasHeight, int startRes)
458   {
459     SequenceGroup group = av.getSelectionGroup();
460
461     drawWrappedPanel(g, canvasWidth, canvasHeight, startRes);
462
463     if (group != null)
464     {
465       BufferedImage selectImage = null;
466       try
467       {
468         selectImage = new BufferedImage(canvasWidth, canvasHeight,
469                 BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
470       } catch (OutOfMemoryError er)
471       {
472         System.gc();
473         System.err.println("Print image OutOfMemory Error.\n" + er);
474         new OOMWarning("Creating wrapped alignment image for printing", er);
475       }
476       if (selectImage != null)
477       {
478         Graphics2D g2 = selectImage.createGraphics();
479         setupSelectionGroup(g2, selectImage);
480         drawWrappedSelection(g2, group, canvasWidth, canvasHeight,
481                 startRes);
482
483         g2.setComposite(
484                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
485         g.drawImage(selectImage, 0, 0, this);
486         g2.dispose();
487       }
488     }
489   }
490
491   /*
492    * Make a local image by combining the cached image img
493    * with any selection
494    */
495   private BufferedImage buildLocalImage(BufferedImage selectImage)
496   {
497     // clone the cached image
498     BufferedImage lcimg = new BufferedImage(img.getWidth(), img.getHeight(),
499             img.getType());
500     Graphics2D g2d = lcimg.createGraphics();
501     g2d.drawImage(img, 0, 0, null);
502
503     // overlay selection group on lcimg
504     if (selectImage != null)
505     {
506       g2d.setComposite(
507               AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
508       g2d.drawImage(selectImage, 0, 0, this);
509     }
510     g2d.dispose();
511
512     return lcimg;
513   }
514
515   /*
516    * Set up a buffered image of the correct height and size for the sequence canvas
517    */
518   private BufferedImage setupImage()
519   {
520     BufferedImage lcimg = null;
521
522     int width = getWidth();
523     int height = getHeight();
524
525     width -= (width % charWidth);
526     height -= (height % charHeight);
527
528     if ((width < 1) || (height < 1))
529     {
530       return null;
531     }
532
533     try
534     {
535       lcimg = new BufferedImage(width, height,
536               BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
537     } catch (OutOfMemoryError er)
538     {
539       System.gc();
540       System.err.println(
541               "Group image OutOfMemory Redraw Error.\n" + er);
542       new OOMWarning("Creating alignment image for display", er);
543
544       return null;
545     }
546
547     return lcimg;
548   }
549
550   /**
551    * Returns the visible width of the canvas in residues, after allowing for
552    * East or West scales (if shown)
553    * 
554    * @param canvasWidth
555    *          the width in pixels (possibly including scales)
556    * 
557    * @return
558    */
559   public int getWrappedCanvasWidth(int canvasWidth)
560   {
561     FontMetrics fm = getFontMetrics(av.getFont());
562
563     labelWidthEast = 0;
564     labelWidthWest = 0;
565
566     if (av.getScaleRightWrapped())
567     {
568       labelWidthEast = getLabelWidth(fm);
569     }
570
571     if (av.getScaleLeftWrapped())
572     {
573       labelWidthWest = labelWidthEast > 0 ? labelWidthEast
574               : getLabelWidth(fm);
575     }
576
577     return (canvasWidth - labelWidthEast - labelWidthWest) / charWidth;
578   }
579
580   /**
581    * Returns a pixel width suitable for showing the largest sequence coordinate
582    * (end position) in the alignment. Returns 2 plus the number of decimal
583    * digits to be shown (3 for 1-10, 4 for 11-99 etc).
584    * 
585    * @param fm
586    * @return
587    */
588   protected int getLabelWidth(FontMetrics fm)
589   {
590     /*
591      * find the biggest sequence end position we need to show
592      * (note this is not necessarily the sequence length)
593      */
594     int maxWidth = 0;
595     AlignmentI alignment = av.getAlignment();
596     for (int i = 0; i < alignment.getHeight(); i++)
597     {
598       maxWidth = Math.max(maxWidth, alignment.getSequenceAt(i).getEnd());
599     }
600
601     int length = 2;
602     for (int i = maxWidth; i > 0; i /= 10)
603     {
604       length++;
605     }
606
607     return fm.stringWidth(ZEROS.substring(0, length));
608   }
609
610   /**
611    * DOCUMENT ME!
612    * 
613    * @param g
614    *          DOCUMENT ME!
615    * @param canvasWidth
616    *          DOCUMENT ME!
617    * @param canvasHeight
618    *          DOCUMENT ME!
619    * @param startRes
620    *          DOCUMENT ME!
621    */
622   private void drawWrappedPanel(Graphics g, int canvasWidth,
623           int canvasHeight, int startRes)
624   {
625     updateViewport();
626     AlignmentI al = av.getAlignment();
627
628     int labelWidth = 0;
629     if (av.getScaleRightWrapped() || av.getScaleLeftWrapped())
630     {
631       FontMetrics fm = getFontMetrics(av.getFont());
632       labelWidth = getLabelWidth(fm);
633     }
634
635     labelWidthEast = av.getScaleRightWrapped() ? labelWidth : 0;
636     labelWidthWest = av.getScaleLeftWrapped() ? labelWidth : 0;
637
638     int hgap = charHeight;
639     if (av.getScaleAboveWrapped())
640     {
641       hgap += charHeight;
642     }
643
644     int cWidth = (canvasWidth - labelWidthEast - labelWidthWest) / charWidth;
645     int cHeight = av.getAlignment().getHeight() * charHeight;
646
647     av.setWrappedWidth(cWidth);
648
649     av.getRanges().setViewportStartAndWidth(startRes, cWidth);
650
651     int endx;
652     int ypos = hgap;
653     int maxwidth = av.getAlignment().getWidth();
654
655     if (av.hasHiddenColumns())
656     {
657       maxwidth = av.getAlignment().getHiddenColumns()
658               .findColumnPosition(maxwidth);
659     }
660
661     int annotationHeight = getAnnotationHeight();
662
663     while ((ypos <= canvasHeight) && (startRes < maxwidth))
664     {
665       endx = startRes + cWidth - 1;
666
667       if (endx > maxwidth)
668       {
669         endx = maxwidth;
670       }
671
672       g.setFont(av.getFont());
673       g.setColor(Color.black);
674
675       if (av.getScaleLeftWrapped())
676       {
677         drawWestScale(g, startRes, endx, ypos);
678       }
679
680       if (av.getScaleRightWrapped())
681       {
682         g.translate(canvasWidth - labelWidthEast, 0);
683         drawEastScale(g, startRes, endx, ypos);
684         g.translate(-(canvasWidth - labelWidthEast), 0);
685       }
686
687       g.translate(labelWidthWest, 0);
688
689       if (av.getScaleAboveWrapped())
690       {
691         drawNorthScale(g, startRes, endx, ypos);
692       }
693
694       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
695       {
696         g.setColor(Color.blue);
697         int res;
698         HiddenColumns hidden = av.getAlignment().getHiddenColumns();
699
700         Iterator<Integer> it = hidden.getBoundedStartIterator(startRes,
701                 endx + 1, true);
702         while (it.hasNext())
703         {
704           res = it.next() - startRes;
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 }, 3);
712         }
713       }
714
715       // When printing we have an extra clipped region,
716       // the Printable page which we need to account for here
717       Shape clip = g.getClip();
718
719       if (clip == null)
720       {
721         g.setClip(0, 0, cWidth * charWidth, canvasHeight);
722       }
723       else
724       {
725         g.setClip(0, (int) clip.getBounds().getY(), cWidth * charWidth,
726                 (int) clip.getBounds().getHeight());
727       }
728
729       drawPanel(g, startRes, endx, 0, al.getHeight() - 1, ypos);
730
731       if (av.isShowAnnotation())
732       {
733         g.translate(0, cHeight + ypos + 3);
734         if (annotations == null)
735         {
736           annotations = new AnnotationPanel(av);
737         }
738
739         annotations.renderer.drawComponent(annotations, av, g, -1, startRes,
740                 endx + 1);
741         g.translate(0, -cHeight - ypos - 3);
742       }
743       g.setClip(clip);
744       g.translate(-labelWidthWest, 0);
745
746       ypos += cHeight + annotationHeight + hgap;
747
748       startRes += cWidth;
749     }
750   }
751
752   /*
753    * Draw a selection group over a wrapped alignment
754    */
755   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
756           int canvasWidth,
757           int canvasHeight, int startRes)
758   {
759     // height gap above each panel
760     int hgap = charHeight;
761     if (av.getScaleAboveWrapped())
762     {
763       hgap += charHeight;
764     }
765
766     int cWidth = (canvasWidth - labelWidthEast - labelWidthWest)
767             / charWidth;
768     int cHeight = av.getAlignment().getHeight() * charHeight;
769
770     int startx = startRes;
771     int endx;
772     int ypos = hgap; // vertical offset
773     int maxwidth = av.getAlignment().getWidth();
774
775     if (av.hasHiddenColumns())
776     {
777       maxwidth = av.getAlignment().getHiddenColumns()
778               .findColumnPosition(maxwidth);
779     }
780
781     // chop the wrapped alignment extent up into panel-sized blocks and treat
782     // each block as if it were a block from an unwrapped alignment
783     while ((ypos <= canvasHeight) && (startx < maxwidth))
784     {
785       // set end value to be start + width, or maxwidth, whichever is smaller
786       endx = startx + cWidth - 1;
787
788       if (endx > maxwidth)
789       {
790         endx = maxwidth;
791       }
792
793       g.translate(labelWidthWest, 0);
794
795       drawUnwrappedSelection(g, group, startx, endx, 0,
796               av.getAlignment().getHeight() - 1,
797               ypos);
798
799       g.translate(-labelWidthWest, 0);
800
801       // update vertical offset
802       ypos += cHeight + getAnnotationHeight() + hgap;
803
804       // update horizontal offset
805       startx += cWidth;
806     }
807   }
808
809   int getAnnotationHeight()
810   {
811     if (!av.isShowAnnotation())
812     {
813       return 0;
814     }
815
816     if (annotations == null)
817     {
818       annotations = new AnnotationPanel(av);
819     }
820
821     return annotations.adjustPanelHeight();
822   }
823
824   /**
825    * Draws the visible region of the alignment on the graphics context. If there
826    * are hidden column markers in the visible region, then each sub-region
827    * between the markers is drawn separately, followed by the hidden column
828    * marker.
829    * 
830    * @param g1
831    *          Graphics object to draw with
832    * @param startRes
833    *          offset of the first column in the visible region (0..)
834    * @param endRes
835    *          offset of the last column in the visible region (0..)
836    * @param startSeq
837    *          offset of the first sequence in the visible region (0..)
838    * @param endSeq
839    *          offset of the last sequence in the visible region (0..)
840    * @param yOffset
841    *          vertical offset at which to draw (for wrapped alignments)
842    */
843   public void drawPanel(Graphics g1, final int startRes, final int endRes,
844           final int startSeq, final int endSeq, final int yOffset)
845   {
846     updateViewport();
847     if (!av.hasHiddenColumns())
848     {
849       draw(g1, startRes, endRes, startSeq, endSeq, yOffset);
850     }
851     else
852     {
853       int screenY = 0;
854       final int screenYMax = endRes - startRes;
855       int blockStart = startRes;
856       int blockEnd = endRes;
857
858       for (int[] region : av.getAlignment().getHiddenColumns()
859               .getHiddenColumnsCopy())
860       {
861         int hideStart = region[0];
862         int hideEnd = region[1];
863
864         if (hideStart <= blockStart)
865         {
866           blockStart += (hideEnd - hideStart) + 1;
867           continue;
868         }
869
870         /*
871          * draw up to just before the next hidden region, or the end of
872          * the visible region, whichever comes first
873          */
874         blockEnd = Math.min(hideStart - 1, blockStart + screenYMax
875                 - screenY);
876
877         g1.translate(screenY * charWidth, 0);
878
879         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
880
881         /*
882          * draw the downline of the hidden column marker (ScalePanel draws the
883          * triangle on top) if we reached it
884          */
885         if (av.getShowHiddenMarkers() && blockEnd == hideStart - 1)
886         {
887           g1.setColor(Color.blue);
888
889           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
890                   0 + yOffset, (blockEnd - blockStart + 1) * charWidth - 1,
891                   (endSeq - startSeq + 1) * charHeight + yOffset);
892         }
893
894         g1.translate(-screenY * charWidth, 0);
895         screenY += blockEnd - blockStart + 1;
896         blockStart = hideEnd + 1;
897
898         if (screenY > screenYMax)
899         {
900           // already rendered last block
901           return;
902         }
903       }
904
905       if (screenY <= screenYMax)
906       {
907         // remaining visible region to render
908         blockEnd = blockStart + screenYMax - screenY;
909         g1.translate(screenY * charWidth, 0);
910         draw(g1, blockStart, blockEnd, startSeq, endSeq, yOffset);
911
912         g1.translate(-screenY * charWidth, 0);
913       }
914     }
915
916   }
917
918   /**
919    * Draws a region of the visible alignment
920    * 
921    * @param g1
922    * @param startRes
923    *          offset of the first column in the visible region (0..)
924    * @param endRes
925    *          offset of the last column in the visible region (0..)
926    * @param startSeq
927    *          offset of the first sequence in the visible region (0..)
928    * @param endSeq
929    *          offset of the last sequence in the visible region (0..)
930    * @param yOffset
931    *          vertical offset at which to draw (for wrapped alignments)
932    */
933   private void draw(Graphics g, int startRes, int endRes, int startSeq,
934           int endSeq, int offset)
935   {
936     g.setFont(av.getFont());
937     seqRdr.prepare(g, av.isRenderGaps());
938
939     SequenceI nextSeq;
940
941     // / First draw the sequences
942     // ///////////////////////////
943     for (int i = startSeq; i <= endSeq; i++)
944     {
945       nextSeq = av.getAlignment().getSequenceAt(i);
946       if (nextSeq == null)
947       {
948         // occasionally, a race condition occurs such that the alignment row is
949         // empty
950         continue;
951       }
952       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
953               startRes, endRes, offset + ((i - startSeq) * charHeight));
954
955       if (av.isShowSequenceFeatures())
956       {
957         fr.drawSequence(g, nextSeq, startRes, endRes,
958                 offset + ((i - startSeq) * charHeight), false);
959       }
960
961       /*
962        * highlight search Results once sequence has been drawn
963        */
964       if (av.hasSearchResults())
965       {
966         SearchResultsI searchResults = av.getSearchResults();
967         int[] visibleResults = searchResults.getResults(nextSeq,
968                 startRes, endRes);
969         if (visibleResults != null)
970         {
971           for (int r = 0; r < visibleResults.length; r += 2)
972           {
973             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
974                     visibleResults[r + 1], (visibleResults[r] - startRes)
975                             * charWidth, offset
976                             + ((i - startSeq) * charHeight));
977           }
978         }
979       }
980
981       if (av.cursorMode && cursorY == i && cursorX >= startRes
982               && cursorX <= endRes)
983       {
984         seqRdr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
985                 offset + ((i - startSeq) * charHeight));
986       }
987     }
988
989     if (av.getSelectionGroup() != null
990             || av.getAlignment().getGroups().size() > 0)
991     {
992       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
993     }
994
995   }
996
997   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
998           int startSeq, int endSeq, int offset)
999   {
1000     Graphics2D g = (Graphics2D) g1;
1001     //
1002     // ///////////////////////////////////
1003     // Now outline any areas if necessary
1004     // ///////////////////////////////////
1005
1006     SequenceGroup group = null;
1007     int groupIndex = -1;
1008
1009     if (av.getAlignment().getGroups().size() > 0)
1010     {
1011       group = av.getAlignment().getGroups().get(0);
1012       groupIndex = 0;
1013     }
1014
1015     if (group != null)
1016     {
1017       g.setStroke(new BasicStroke());
1018       g.setColor(group.getOutlineColour());
1019       
1020       do
1021       {
1022         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
1023                 endSeq, offset);
1024
1025         groupIndex++;
1026
1027         g.setStroke(new BasicStroke());
1028
1029         if (groupIndex >= av.getAlignment().getGroups().size())
1030         {
1031           break;
1032         }
1033
1034         group = av.getAlignment().getGroups().get(groupIndex);
1035
1036       } while (groupIndex < av.getAlignment().getGroups().size());
1037
1038     }
1039
1040   }
1041
1042
1043   /*
1044    * Draw the selection group as a separate image and overlay
1045    */
1046   private BufferedImage drawSelectionGroup(int startRes, int endRes,
1047           int startSeq, int endSeq)
1048   {
1049     // get a new image of the correct size
1050     BufferedImage selectionImage = setupImage();
1051
1052     if (selectionImage == null)
1053     {
1054       return null;
1055     }
1056
1057     SequenceGroup group = av.getSelectionGroup();
1058     if (group == null)
1059     {
1060       // nothing to draw
1061       return null;
1062     }
1063
1064     // set up drawing colour
1065     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1066
1067     setupSelectionGroup(g, selectionImage);
1068
1069     if (!av.getWrapAlignment())
1070     {
1071       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1072               0);
1073     }
1074     else
1075     {
1076       drawWrappedSelection(g, group, getWidth(), getHeight(),
1077               av.getRanges().getStartRes());
1078     }
1079
1080     g.dispose();
1081     return selectionImage;
1082   }
1083
1084   /*
1085    * Set up graphics for selection group
1086    */
1087   private void setupSelectionGroup(Graphics2D g,
1088           BufferedImage selectionImage)
1089   {
1090     // set background to transparent
1091     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1092     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1093
1094     // set up foreground to draw red dashed line
1095     g.setComposite(AlphaComposite.Src);
1096     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1097             BasicStroke.JOIN_ROUND, 3f, new float[]
1098     { 5f, 3f }, 0f));
1099     g.setColor(Color.RED);
1100   }
1101
1102   /*
1103    * Draw a selection group over an unwrapped alignment
1104    * @param g graphics object to draw with
1105    * @param group selection group
1106    * @param startRes start residue of area to draw
1107    * @param endRes end residue of area to draw
1108    * @param startSeq start sequence of area to draw
1109    * @param endSeq end sequence of area to draw
1110    * @param offset vertical offset (used when called from wrapped alignment code)
1111    */
1112   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1113           int startRes, int endRes, int startSeq, int endSeq, int offset)
1114   {
1115     if (!av.hasHiddenColumns())
1116     {
1117       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1118               offset);
1119     }
1120     else
1121     {
1122       // package into blocks of visible columns
1123       int screenY = 0;
1124       int blockStart = startRes;
1125       int blockEnd = endRes;
1126
1127       for (int[] region : av.getAlignment().getHiddenColumns()
1128               .getHiddenColumnsCopy())
1129       {
1130         int hideStart = region[0];
1131         int hideEnd = region[1];
1132
1133         if (hideStart <= blockStart)
1134         {
1135           blockStart += (hideEnd - hideStart) + 1;
1136           continue;
1137         }
1138
1139         blockEnd = hideStart - 1;
1140
1141         g.translate(screenY * charWidth, 0);
1142         drawPartialGroupOutline(g, group,
1143                 blockStart, blockEnd, startSeq, endSeq, offset);
1144
1145         g.translate(-screenY * charWidth, 0);
1146         screenY += blockEnd - blockStart + 1;
1147         blockStart = hideEnd + 1;
1148
1149         if (screenY > (endRes - startRes))
1150         {
1151           // already rendered last block
1152           break;
1153         }
1154       }
1155
1156       if (screenY <= (endRes - startRes))
1157       {
1158         // remaining visible region to render
1159         blockEnd = blockStart + (endRes - startRes) - screenY;
1160         g.translate(screenY * charWidth, 0);
1161         drawPartialGroupOutline(g, group,
1162                 blockStart, blockEnd, startSeq, endSeq, offset);
1163         
1164         g.translate(-screenY * charWidth, 0);
1165       }
1166     }
1167   }
1168
1169   /*
1170    * Draw the selection group as a separate image and overlay
1171    */
1172   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1173           int startRes, int endRes, int startSeq, int endSeq,
1174           int verticalOffset)
1175   {
1176     int visWidth = (endRes - startRes + 1) * charWidth;
1177
1178     int oldY = -1;
1179     int i = 0;
1180     boolean inGroup = false;
1181     int top = -1;
1182     int bottom = -1;
1183
1184     int sx = -1;
1185     int sy = -1;
1186     int xwidth = -1;
1187
1188     for (i = startSeq; i <= endSeq; i++)
1189     {
1190       // position of start residue of group relative to startRes, in pixels
1191       sx = (group.getStartRes() - startRes) * charWidth;
1192
1193       // width of group in pixels
1194       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1195               - 1;
1196
1197       sy = verticalOffset + (i - startSeq) * charHeight;
1198
1199       if (sx + xwidth < 0 || sx > visWidth)
1200       {
1201         continue;
1202       }
1203
1204       if ((sx <= (endRes - startRes) * charWidth)
1205               && group.getSequences(null)
1206                       .contains(av.getAlignment().getSequenceAt(i)))
1207       {
1208         if ((bottom == -1) && !group.getSequences(null)
1209                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1210         {
1211           bottom = sy + charHeight;
1212         }
1213
1214         if (!inGroup)
1215         {
1216           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1217                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1218           {
1219             top = sy;
1220           }
1221
1222           oldY = sy;
1223           inGroup = true;
1224         }
1225       }
1226       else
1227       {
1228         if (inGroup)
1229         {
1230           // if start position is visible, draw vertical line to left of
1231           // group
1232           if (sx >= 0 && sx < visWidth)
1233           {
1234             g.drawLine(sx, oldY, sx, sy);
1235           }
1236
1237           // if end position is visible, draw vertical line to right of
1238           // group
1239           if (sx + xwidth < visWidth)
1240           {
1241             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1242           }
1243
1244           if (sx < 0)
1245           {
1246             xwidth += sx;
1247             sx = 0;
1248           }
1249
1250           // don't let width extend beyond current block, or group extent
1251           // fixes JAL-2672
1252           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1253           {
1254             xwidth = (endRes - startRes + 1) * charWidth - sx;
1255           }
1256           
1257           // draw horizontal line at top of group
1258           if (top != -1)
1259           {
1260             g.drawLine(sx, top, sx + xwidth, top);
1261             top = -1;
1262           }
1263
1264           // draw horizontal line at bottom of group
1265           if (bottom != -1)
1266           {
1267             g.drawLine(sx, bottom, sx + xwidth, bottom);
1268             bottom = -1;
1269           }
1270
1271           inGroup = false;
1272         }
1273       }
1274     }
1275
1276     if (inGroup)
1277     {
1278       sy = verticalOffset + ((i - startSeq) * charHeight);
1279       if (sx >= 0 && sx < visWidth)
1280       {
1281         g.drawLine(sx, oldY, sx, sy);
1282       }
1283
1284       if (sx + xwidth < visWidth)
1285       {
1286         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1287       }
1288
1289       if (sx < 0)
1290       {
1291         xwidth += sx;
1292         sx = 0;
1293       }
1294
1295       if (sx + xwidth > visWidth)
1296       {
1297         xwidth = visWidth;
1298       }
1299       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1300       {
1301         xwidth = (endRes - startRes + 1) * charWidth;
1302       }
1303
1304       if (top != -1)
1305       {
1306         g.drawLine(sx, top, sx + xwidth, top);
1307         top = -1;
1308       }
1309
1310       if (bottom != -1)
1311       {
1312         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1313         bottom = -1;
1314       }
1315
1316       inGroup = false;
1317     }
1318   }
1319   
1320   /**
1321    * Highlights search results in the visible region by rendering as white text
1322    * on a black background. Any previous highlighting is removed. Answers true
1323    * if any highlight was left on the visible alignment (so status bar should be
1324    * set to match), else false.
1325    * <p>
1326    * Currently fastPaint is not implemented for wrapped alignments. If a wrapped
1327    * alignment had to be scrolled to show the highlighted region, then it should
1328    * be fully redrawn, otherwise a fast paint can be performed. This argument
1329    * could be removed if fast paint of scrolled wrapped alignment is coded in
1330    * future (JAL-2609).
1331    * 
1332    * @param results
1333    * @param noFastPaint
1334    * @return
1335    */
1336   public boolean highlightSearchResults(SearchResultsI results,
1337           boolean noFastPaint)
1338   {
1339     if (fastpainting)
1340     {
1341       return false;
1342     }
1343     boolean wrapped = av.getWrapAlignment();
1344
1345     try
1346     {
1347       fastPaint = !noFastPaint;
1348       fastpainting = fastPaint;
1349
1350       updateViewport();
1351
1352       /*
1353        * to avoid redrawing the whole visible region, we instead
1354        * redraw just the minimal regions to remove previous highlights
1355        * and add new ones
1356        */
1357       SearchResultsI previous = av.getSearchResults();
1358       av.setSearchResults(results);
1359       boolean redrawn = false;
1360       boolean drawn = false;
1361       if (wrapped)
1362       {
1363         redrawn = drawMappedPositionsWrapped(previous);
1364         drawn = drawMappedPositionsWrapped(results);
1365         redrawn |= drawn;
1366       }
1367       else
1368       {
1369         redrawn = drawMappedPositions(previous);
1370         drawn = drawMappedPositions(results);
1371         redrawn |= drawn;
1372       }
1373
1374       /*
1375        * if highlights were either removed or added, repaint
1376        */
1377       if (redrawn)
1378       {
1379         repaint();
1380       }
1381
1382       /*
1383        * return true only if highlights were added
1384        */
1385       return drawn;
1386
1387     } finally
1388     {
1389       fastpainting = false;
1390     }
1391   }
1392
1393   /**
1394    * Redraws the minimal rectangle in the visible region (if any) that includes
1395    * mapped positions of the given search results. Whether or not positions are
1396    * highlighted depends on the SearchResults set on the Viewport. This allows
1397    * this method to be called to either clear or set highlighting. Answers true
1398    * if any positions were drawn (in which case a repaint is still required),
1399    * else false.
1400    * 
1401    * @param results
1402    * @return
1403    */
1404   protected boolean drawMappedPositions(SearchResultsI results)
1405   {
1406     if (results == null)
1407     {
1408       return false;
1409     }
1410
1411     /*
1412      * calculate the minimal rectangle to redraw that 
1413      * includes both new and existing search results
1414      */
1415     int firstSeq = Integer.MAX_VALUE;
1416     int lastSeq = -1;
1417     int firstCol = Integer.MAX_VALUE;
1418     int lastCol = -1;
1419     boolean matchFound = false;
1420
1421     ViewportRanges ranges = av.getRanges();
1422     int firstVisibleColumn = ranges.getStartRes();
1423     int lastVisibleColumn = ranges.getEndRes();
1424     AlignmentI alignment = av.getAlignment();
1425     if (av.hasHiddenColumns())
1426     {
1427       firstVisibleColumn = alignment.getHiddenColumns()
1428               .adjustForHiddenColumns(firstVisibleColumn);
1429       lastVisibleColumn = alignment.getHiddenColumns()
1430               .adjustForHiddenColumns(lastVisibleColumn);
1431     }
1432
1433     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1434             .getEndSeq(); seqNo++)
1435     {
1436       SequenceI seq = alignment.getSequenceAt(seqNo);
1437
1438       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1439               lastVisibleColumn);
1440       if (visibleResults != null)
1441       {
1442         for (int i = 0; i < visibleResults.length - 1; i += 2)
1443         {
1444           int firstMatchedColumn = visibleResults[i];
1445           int lastMatchedColumn = visibleResults[i + 1];
1446           if (firstMatchedColumn <= lastVisibleColumn
1447                   && lastMatchedColumn >= firstVisibleColumn)
1448           {
1449             /*
1450              * found a search results match in the visible region - 
1451              * remember the first and last sequence matched, and the first
1452              * and last visible columns in the matched positions
1453              */
1454             matchFound = true;
1455             firstSeq = Math.min(firstSeq, seqNo);
1456             lastSeq = Math.max(lastSeq, seqNo);
1457             firstMatchedColumn = Math.max(firstMatchedColumn,
1458                     firstVisibleColumn);
1459             lastMatchedColumn = Math.min(lastMatchedColumn,
1460                     lastVisibleColumn);
1461             firstCol = Math.min(firstCol, firstMatchedColumn);
1462             lastCol = Math.max(lastCol, lastMatchedColumn);
1463           }
1464         }
1465       }
1466     }
1467
1468     if (matchFound)
1469     {
1470       if (av.hasHiddenColumns())
1471       {
1472         firstCol = alignment.getHiddenColumns()
1473                 .findColumnPosition(firstCol);
1474         lastCol = alignment.getHiddenColumns().findColumnPosition(lastCol);
1475       }
1476       int transX = (firstCol - ranges.getStartRes()) * av.getCharWidth();
1477       int transY = (firstSeq - ranges.getStartSeq()) * av.getCharHeight();
1478       gg.translate(transX, transY);
1479       drawPanel(gg, firstCol, lastCol, firstSeq, lastSeq, 0);
1480       gg.translate(-transX, -transY);
1481     }
1482
1483     return matchFound;
1484   }
1485
1486   @Override
1487   public void propertyChange(PropertyChangeEvent evt)
1488   {
1489     String eventName = evt.getPropertyName();
1490
1491     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1492     {
1493       fastPaint = true;
1494       repaint();
1495     }
1496     else if (av.getWrapAlignment())
1497     {
1498       if (eventName.equals(ViewportRanges.STARTRES))
1499       {
1500         repaint();
1501       }
1502     }
1503     else
1504     {
1505       int scrollX = 0;
1506       if (eventName.equals(ViewportRanges.STARTRES))
1507       {
1508         // Make sure we're not trying to draw a panel
1509         // larger than the visible window
1510         ViewportRanges vpRanges = av.getRanges();
1511         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1512         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1513         if (scrollX > range)
1514         {
1515           scrollX = range;
1516         }
1517         else if (scrollX < -range)
1518         {
1519           scrollX = -range;
1520         }
1521       }
1522
1523       // Both scrolling and resizing change viewport ranges: scrolling changes
1524       // both start and end points, but resize only changes end values.
1525       // Here we only want to fastpaint on a scroll, with resize using a normal
1526       // paint, so scroll events are identified as changes to the horizontal or
1527       // vertical start value.
1528       if (eventName.equals(ViewportRanges.STARTRES))
1529       {
1530         // scroll - startres and endres both change
1531         fastPaint(scrollX, 0);
1532       }
1533       else if (eventName.equals(ViewportRanges.STARTSEQ))
1534       {
1535         // scroll
1536         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1537       }
1538     }
1539   }
1540
1541   /**
1542    * Redraws any positions in the search results in the visible region of a
1543    * wrapped alignment. Any highlights are drawn depending on the search results
1544    * set on the Viewport, not the <code>results</code> argument. This allows
1545    * this method to be called either to clear highlights (passing the previous
1546    * search results), or to draw new highlights.
1547    * 
1548    * @param results
1549    * @return
1550    */
1551   protected boolean drawMappedPositionsWrapped(SearchResultsI results)
1552   {
1553     if (results == null)
1554     {
1555       return false;
1556     }
1557   
1558     boolean matchFound = false;
1559
1560     int wrappedWidth = av.getWrappedWidth();
1561     int wrappedHeight = getRepeatHeightWrapped();
1562
1563     ViewportRanges ranges = av.getRanges();
1564     int canvasHeight = getHeight();
1565     int repeats = canvasHeight / wrappedHeight;
1566     if (canvasHeight / wrappedHeight > 0)
1567     {
1568       repeats++;
1569     }
1570
1571     int firstVisibleColumn = ranges.getStartRes();
1572     int lastVisibleColumn = ranges.getStartRes() + repeats
1573             * ranges.getViewportWidth() - 1;
1574
1575     AlignmentI alignment = av.getAlignment();
1576     if (av.hasHiddenColumns())
1577     {
1578       firstVisibleColumn = alignment.getHiddenColumns()
1579               .adjustForHiddenColumns(firstVisibleColumn);
1580       lastVisibleColumn = alignment.getHiddenColumns()
1581               .adjustForHiddenColumns(lastVisibleColumn);
1582     }
1583
1584     int gapHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
1585
1586     for (int seqNo = ranges.getStartSeq(); seqNo <= ranges
1587             .getEndSeq(); seqNo++)
1588     {
1589       SequenceI seq = alignment.getSequenceAt(seqNo);
1590
1591       int[] visibleResults = results.getResults(seq, firstVisibleColumn,
1592               lastVisibleColumn);
1593       if (visibleResults != null)
1594       {
1595         for (int i = 0; i < visibleResults.length - 1; i += 2)
1596         {
1597           int firstMatchedColumn = visibleResults[i];
1598           int lastMatchedColumn = visibleResults[i + 1];
1599           if (firstMatchedColumn <= lastVisibleColumn
1600                   && lastMatchedColumn >= firstVisibleColumn)
1601           {
1602             /*
1603              * found a search results match in the visible region
1604              */
1605             firstMatchedColumn = Math.max(firstMatchedColumn,
1606                     firstVisibleColumn);
1607             lastMatchedColumn = Math.min(lastMatchedColumn,
1608                     lastVisibleColumn);
1609
1610             /*
1611              * draw each mapped position separately (as contiguous positions may
1612              * wrap across lines)
1613              */
1614             for (int mappedPos = firstMatchedColumn; mappedPos <= lastMatchedColumn; mappedPos++)
1615             {
1616               int displayColumn = mappedPos;
1617               if (av.hasHiddenColumns())
1618               {
1619                 displayColumn = alignment.getHiddenColumns()
1620                         .findColumnPosition(displayColumn);
1621               }
1622
1623               /*
1624                * transX: offset from left edge of canvas to residue position
1625                */
1626               int transX = labelWidthWest
1627                       + ((displayColumn - ranges.getStartRes()) % wrappedWidth)
1628                       * av.getCharWidth();
1629
1630               /*
1631                * transY: offset from top edge of canvas to residue position
1632                */
1633               int transY = gapHeight;
1634               transY += (displayColumn - ranges.getStartRes())
1635                       / wrappedWidth * wrappedHeight;
1636               transY += (seqNo - ranges.getStartSeq()) * av.getCharHeight();
1637
1638               /*
1639                * yOffset is from graphics origin to start of visible region
1640                */
1641               int yOffset = 0;// (displayColumn / wrappedWidth) * wrappedHeight;
1642               if (transY < getHeight())
1643               {
1644                 matchFound = true;
1645                 gg.translate(transX, transY);
1646                 drawPanel(gg, displayColumn, displayColumn, seqNo, seqNo,
1647                         yOffset);
1648                 gg.translate(-transX, -transY);
1649               }
1650             }
1651           }
1652         }
1653       }
1654     }
1655   
1656     return matchFound;
1657   }
1658
1659   /**
1660    * Answers the height in pixels of a repeating section of the wrapped
1661    * alignment, including space above, scale above if shown, sequences, and
1662    * annotation panel if shown
1663    * 
1664    * @return
1665    */
1666   protected int getRepeatHeightWrapped()
1667   {
1668     // gap (and maybe scale) above
1669     int repeatHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
1670
1671     // add sequences
1672     repeatHeight += av.getRanges().getViewportHeight() * charHeight;
1673
1674     // add annotations panel height if shown
1675     repeatHeight += getAnnotationHeight();
1676
1677     return repeatHeight;
1678   }
1679 }