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   final FeatureRenderer fr;
57
58   final SequenceRenderer seqRdr;
59
60   BufferedImage img;
61
62   Graphics2D gg;
63
64   AlignViewport av;
65
66   boolean fastPaint = false;
67
68   int LABEL_WEST;
69
70   int LABEL_EAST;
71
72   int cursorX = 0;
73
74   int cursorY = 0;
75
76   int charHeight = 0;
77
78   int charWidth = 0;
79
80   boolean fastpainting = false;
81
82   AnnotationPanel annotations;
83
84   /**
85    * Creates a new SeqCanvas object.
86    * 
87    * @param av
88    *          DOCUMENT ME!
89    */
90   public SeqCanvas(AlignmentPanel ap)
91   {
92     this.av = ap.av;
93     updateViewport();
94     fr = new FeatureRenderer(ap);
95     seqRdr = new SequenceRenderer(av);
96     setLayout(new BorderLayout());
97     PaintRefresher.Register(this, av.getSequenceSetId());
98     setBackground(Color.white);
99
100     av.getRanges().addPropertyChangeListener(this);
101   }
102
103   public SequenceRenderer getSequenceRenderer()
104   {
105     return seqRdr;
106   }
107
108   public FeatureRenderer getFeatureRenderer()
109   {
110     return fr;
111   }
112
113   private void updateViewport()
114   {
115     charHeight = av.getCharHeight();
116     charWidth = av.getCharWidth();
117   }
118
119   /**
120    * DOCUMENT ME!
121    * 
122    * @param g
123    *          DOCUMENT ME!
124    * @param startx
125    *          DOCUMENT ME!
126    * @param endx
127    *          DOCUMENT ME!
128    * @param ypos
129    *          DOCUMENT ME!
130    */
131   private void drawNorthScale(Graphics g, int startx, int endx, int ypos)
132   {
133     updateViewport();
134     for (ScaleMark mark : new ScaleRenderer().calculateMarks(av, startx,
135             endx))
136     {
137       int mpos = mark.column; // (i - startx - 1)
138       if (mpos < 0)
139       {
140         continue;
141       }
142       String mstring = mark.text;
143
144       if (mark.major)
145       {
146         if (mstring != null)
147         {
148           g.drawString(mstring, mpos * charWidth, ypos - (charHeight / 2));
149         }
150         g.drawLine((mpos * charWidth) + (charWidth / 2),
151                 (ypos + 2) - (charHeight / 2),
152                 (mpos * charWidth) + (charWidth / 2), ypos - 2);
153       }
154     }
155   }
156
157   /**
158    * DOCUMENT ME!
159    * 
160    * @param g
161    *          DOCUMENT ME!
162    * @param startx
163    *          DOCUMENT ME!
164    * @param endx
165    *          DOCUMENT ME!
166    * @param ypos
167    *          DOCUMENT ME!
168    */
169   void drawWestScale(Graphics g, int startx, int endx, int ypos)
170   {
171     FontMetrics fm = getFontMetrics(av.getFont());
172     ypos += charHeight;
173
174     if (av.hasHiddenColumns())
175     {
176       startx = av.getAlignment().getHiddenColumns()
177               .adjustForHiddenColumns(startx);
178       endx = av.getAlignment().getHiddenColumns()
179               .adjustForHiddenColumns(endx);
180     }
181
182     int maxwidth = av.getAlignment().getWidth();
183     if (av.hasHiddenColumns())
184     {
185       maxwidth = av.getAlignment().getHiddenColumns()
186               .findColumnPosition(maxwidth) - 1;
187     }
188
189     // WEST SCALE
190     for (int i = 0; i < av.getAlignment().getHeight(); i++)
191     {
192       SequenceI seq = av.getAlignment().getSequenceAt(i);
193       int index = startx;
194       int value = -1;
195
196       while (index < endx)
197       {
198         if (jalview.util.Comparison.isGap(seq.getCharAt(index)))
199         {
200           index++;
201
202           continue;
203         }
204
205         value = av.getAlignment().getSequenceAt(i).findPosition(index);
206
207         break;
208       }
209
210       if (value != -1)
211       {
212         int x = LABEL_WEST - fm.stringWidth(String.valueOf(value))
213                 - charWidth / 2;
214         g.drawString(value + "", x,
215                 (ypos + (i * charHeight)) - (charHeight / 5));
216       }
217     }
218   }
219
220   /**
221    * DOCUMENT ME!
222    * 
223    * @param g
224    *          DOCUMENT ME!
225    * @param startx
226    *          DOCUMENT ME!
227    * @param endx
228    *          DOCUMENT ME!
229    * @param ypos
230    *          DOCUMENT ME!
231    */
232   void drawEastScale(Graphics g, int startx, int endx, int ypos)
233   {
234     ypos += charHeight;
235
236     if (av.hasHiddenColumns())
237     {
238       endx = av.getAlignment().getHiddenColumns()
239               .adjustForHiddenColumns(endx);
240     }
241
242     SequenceI seq;
243     // EAST SCALE
244     for (int i = 0; i < av.getAlignment().getHeight(); i++)
245     {
246       seq = av.getAlignment().getSequenceAt(i);
247       int index = endx;
248       int value = -1;
249
250       while (index > startx)
251       {
252         if (jalview.util.Comparison.isGap(seq.getCharAt(index)))
253         {
254           index--;
255
256           continue;
257         }
258
259         value = seq.findPosition(index);
260
261         break;
262       }
263
264       if (value != -1)
265       {
266         g.drawString(String.valueOf(value), 0,
267                 (ypos + (i * charHeight)) - (charHeight / 5));
268       }
269     }
270   }
271
272
273   /**
274    * need to make this thread safe move alignment rendering in response to
275    * slider adjustment
276    * 
277    * @param horizontal
278    *          shift along
279    * @param vertical
280    *          shift up or down in repaint
281    */
282   public void fastPaint(int horizontal, int vertical)
283   {
284     if (fastpainting || gg == null)
285     {
286       return;
287     }
288     fastpainting = true;
289     fastPaint = true;
290     updateViewport();
291
292     ViewportRanges ranges = av.getRanges();
293     int sr = ranges.getStartRes();
294     int er = ranges.getEndRes();
295     int ss = ranges.getStartSeq();
296     int es = ranges.getEndSeq();
297     int transX = 0;
298     int transY = 0;
299
300     gg.copyArea(horizontal * charWidth, vertical * charHeight,
301             img.getWidth(), img.getHeight(), -horizontal * charWidth,
302             -vertical * charHeight);
303
304     if (horizontal > 0) // scrollbar pulled right, image to the left
305     {
306       transX = (er - sr - horizontal) * charWidth;
307       sr = er - horizontal;
308     }
309     else if (horizontal < 0)
310     {
311       er = sr - horizontal;
312     }
313     else if (vertical > 0) // scroll down
314     {
315       ss = es - vertical;
316
317       if (ss < ranges.getStartSeq())
318       { // ie scrolling too fast, more than a page at a time
319         ss = ranges.getStartSeq();
320       }
321       else
322       {
323         transY = img.getHeight() - ((vertical + 1) * charHeight);
324       }
325     }
326     else if (vertical < 0)
327     {
328       es = ss - vertical;
329
330       if (es > ranges.getEndSeq())
331       {
332         es = ranges.getEndSeq();
333       }
334     }
335
336     gg.translate(transX, transY);
337     drawPanel(gg, sr, er, ss, es, 0);
338     gg.translate(-transX, -transY);
339
340     repaint();
341     fastpainting = false;
342   }
343
344   /**
345    * Definitions of startx and endx (hopefully): SMJS This is what I'm working
346    * towards! startx is the first residue (starting at 0) to display. endx is
347    * the last residue to display (starting at 0). starty is the first sequence
348    * to display (starting at 0). endy is the last sequence to display (starting
349    * at 0). NOTE 1: The av limits are set in setFont in this class and in the
350    * adjustment listener in SeqPanel when the scrollbars move.
351    */
352
353   // Set this to false to force a full panel paint
354   @Override
355   public void paintComponent(Graphics g)
356   {
357     super.paintComponent(g);
358
359     updateViewport();
360
361     ViewportRanges ranges = av.getRanges();
362
363     int width = getWidth();
364     int height = getHeight();
365
366     width -= (width % charWidth);
367     height -= (height % charHeight);
368
369     // selectImage is the selection group outline image
370     BufferedImage selectImage = drawSelectionGroup(
371             ranges.getStartRes(), ranges.getEndRes(),
372             ranges.getStartSeq(), ranges.getEndSeq());
373
374     if ((img != null) && (fastPaint
375             || (getVisibleRect().width != g.getClipBounds().width)
376             || (getVisibleRect().height != g.getClipBounds().height)))
377     {
378       BufferedImage lcimg = buildLocalImage(selectImage);
379       g.drawImage(lcimg, 0, 0, this);
380       fastPaint = false;
381     }
382     else if ((width > 0) && (height > 0))
383     {
384       // img is a cached version of the last view we drew, if any
385       // if we have no img or the size has changed, make a new one
386       if (img == null || width != img.getWidth()
387               || height != img.getHeight())
388       {
389         img = setupImage();
390         if (img == null)
391         {
392           return;
393         }
394         gg = (Graphics2D) img.getGraphics();
395         gg.setFont(av.getFont());
396       }
397
398       if (av.antiAlias)
399       {
400         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
401                 RenderingHints.VALUE_ANTIALIAS_ON);
402       }
403
404       gg.setColor(Color.white);
405       gg.fillRect(0, 0, img.getWidth(), img.getHeight());
406
407       if (av.getWrapAlignment())
408       {
409         drawWrappedPanel(gg, getWidth(), getHeight(), ranges.getStartRes());
410       }
411       else
412       {
413         drawPanel(gg, ranges.getStartRes(), ranges.getEndRes(),
414                 ranges.getStartSeq(), ranges.getEndSeq(), 0);
415       }
416
417       // lcimg is a local *copy* of img which we'll draw selectImage on top of
418       BufferedImage lcimg = buildLocalImage(selectImage);
419       g.drawImage(lcimg, 0, 0, this);
420     }
421   }
422
423   /**
424    * Draw an alignment panel for printing
425    * 
426    * @param g1
427    *          Graphics object to draw with
428    * @param startRes
429    *          start residue of print area
430    * @param endRes
431    *          end residue of print area
432    * @param startSeq
433    *          start sequence of print area
434    * @param endSeq
435    *          end sequence of print area
436    */
437   public void drawPanelForPrinting(Graphics g1, int startRes, int endRes,
438           int startSeq, int endSeq)
439   {
440     BufferedImage selectImage = drawSelectionGroup(startRes, endRes,
441             startSeq, endSeq);
442     drawPanel(g1, startRes, endRes, startSeq, endSeq, 0);
443     ((Graphics2D) g1).setComposite(
444             AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
445     g1.drawImage(selectImage, 0, 0, this);
446   }
447
448   /**
449    * Draw a wrapped alignment panel for printing
450    * 
451    * @param g
452    *          Graphics object to draw with
453    * @param canvasWidth
454    *          width of drawing area
455    * @param canvasHeight
456    *          height of drawing area
457    * @param startRes
458    *          start residue of print area
459    */
460   public void drawWrappedPanelForPrinting(Graphics g, int canvasWidth,
461           int canvasHeight, int startRes)
462   {
463     SequenceGroup group = av.getSelectionGroup();
464
465     drawWrappedPanel(g, canvasWidth, canvasHeight, startRes);
466
467     if (group != null)
468     {
469       BufferedImage selectImage = null;
470       try
471       {
472         selectImage = new BufferedImage(canvasWidth, canvasHeight,
473                 BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
474       } catch (OutOfMemoryError er)
475       {
476         System.gc();
477         System.err.println("Print image OutOfMemory Error.\n" + er);
478         new OOMWarning("Creating wrapped alignment image for printing", er);
479       }
480       if (selectImage != null)
481       {
482         Graphics2D g2 = selectImage.createGraphics();
483         setupSelectionGroup(g2, selectImage);
484         drawWrappedSelection(g2, group, canvasWidth, canvasHeight,
485                 startRes);
486
487         g2.setComposite(
488                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
489         g.drawImage(selectImage, 0, 0, this);
490         g2.dispose();
491       }
492     }
493   }
494
495   /*
496    * Make a local image by combining the cached image img
497    * with any selection
498    */
499   private BufferedImage buildLocalImage(BufferedImage selectImage)
500   {
501     // clone the cached image
502     BufferedImage lcimg = new BufferedImage(img.getWidth(), img.getHeight(),
503             img.getType());
504     Graphics2D g2d = lcimg.createGraphics();
505     g2d.drawImage(img, 0, 0, null);
506
507     // overlay selection group on lcimg
508     if (selectImage != null)
509     {
510       g2d.setComposite(
511               AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
512       g2d.drawImage(selectImage, 0, 0, this);
513     }
514     g2d.dispose();
515
516     return lcimg;
517   }
518
519   /*
520    * Set up a buffered image of the correct height and size for the sequence canvas
521    */
522   private BufferedImage setupImage()
523   {
524     BufferedImage lcimg = null;
525
526     int width = getWidth();
527     int height = getHeight();
528
529     width -= (width % charWidth);
530     height -= (height % charHeight);
531
532     if ((width < 1) || (height < 1))
533     {
534       return null;
535     }
536
537     try
538     {
539       lcimg = new BufferedImage(width, height,
540               BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
541     } catch (OutOfMemoryError er)
542     {
543       System.gc();
544       System.err.println(
545               "Group image OutOfMemory Redraw Error.\n" + er);
546       new OOMWarning("Creating alignment image for display", er);
547
548       return null;
549     }
550
551     return lcimg;
552   }
553
554   /**
555    * DOCUMENT ME!
556    * 
557    * @param cwidth
558    *          DOCUMENT ME!
559    * 
560    * @return DOCUMENT ME!
561    */
562   public int getWrappedCanvasWidth(int cwidth)
563   {
564     FontMetrics fm = getFontMetrics(av.getFont());
565
566     LABEL_EAST = 0;
567     LABEL_WEST = 0;
568
569     if (av.getScaleRightWrapped())
570     {
571       LABEL_EAST = fm.stringWidth(getMask());
572     }
573
574     if (av.getScaleLeftWrapped())
575     {
576       LABEL_WEST = fm.stringWidth(getMask());
577     }
578
579     return (cwidth - LABEL_EAST - LABEL_WEST) / charWidth;
580   }
581
582   /**
583    * Generates a string of zeroes.
584    * 
585    * @return String
586    */
587   String getMask()
588   {
589     String mask = "00";
590     int maxWidth = 0;
591     int tmp;
592     for (int i = 0; i < av.getAlignment().getHeight(); i++)
593     {
594       tmp = av.getAlignment().getSequenceAt(i).getEnd();
595       if (tmp > maxWidth)
596       {
597         maxWidth = tmp;
598       }
599     }
600
601     for (int i = maxWidth; i > 0; i /= 10)
602     {
603       mask += "0";
604     }
605     return mask;
606   }
607
608   /**
609    * DOCUMENT ME!
610    * 
611    * @param g
612    *          DOCUMENT ME!
613    * @param canvasWidth
614    *          DOCUMENT ME!
615    * @param canvasHeight
616    *          DOCUMENT ME!
617    * @param startRes
618    *          DOCUMENT ME!
619    */
620   private void drawWrappedPanel(Graphics g, int canvasWidth,
621           int canvasHeight, int startRes)
622   {
623     updateViewport();
624     AlignmentI al = av.getAlignment();
625
626     FontMetrics fm = getFontMetrics(av.getFont());
627
628     LABEL_EAST = 0;
629     LABEL_WEST = 0;
630
631     if (av.getScaleRightWrapped())
632     {
633       LABEL_EAST = fm.stringWidth(getMask());
634     }
635
636     if (av.getScaleLeftWrapped())
637     {
638       LABEL_WEST = fm.stringWidth(getMask());
639     }
640
641     int hgap = charHeight;
642     if (av.getScaleAboveWrapped())
643     {
644       hgap += charHeight;
645     }
646
647     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
648     int cHeight = av.getAlignment().getHeight() * charHeight;
649
650     av.setWrappedWidth(cWidth);
651
652     av.getRanges().setViewportStartAndWidth(startRes, cWidth);
653
654     int endx;
655     int ypos = hgap;
656     int maxwidth = av.getAlignment().getWidth();
657
658     if (av.hasHiddenColumns())
659     {
660       maxwidth = av.getAlignment().getHiddenColumns()
661               .findColumnPosition(maxwidth);
662     }
663
664     while ((ypos <= canvasHeight) && (startRes < maxwidth))
665     {
666       endx = startRes + cWidth - 1;
667
668       if (endx > maxwidth)
669       {
670         endx = maxwidth;
671       }
672
673       g.setFont(av.getFont());
674       g.setColor(Color.black);
675
676       if (av.getScaleLeftWrapped())
677       {
678         drawWestScale(g, startRes, endx, ypos);
679       }
680
681       if (av.getScaleRightWrapped())
682       {
683         g.translate(canvasWidth - LABEL_EAST, 0);
684         drawEastScale(g, startRes, endx, ypos);
685         g.translate(-(canvasWidth - LABEL_EAST), 0);
686       }
687
688       g.translate(LABEL_WEST, 0);
689
690       if (av.getScaleAboveWrapped())
691       {
692         drawNorthScale(g, startRes, endx, ypos);
693       }
694
695       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
696       {
697         g.setColor(Color.blue);
698         int res;
699         HiddenColumns hidden = av.getAlignment().getHiddenColumns();
700         List<Integer> positions = hidden.findHiddenRegionPositions();
701         for (int pos : positions)
702         {
703           res = pos - startRes;
704
705           if (res < 0 || res > endx - startRes)
706           {
707             continue;
708           }
709
710           gg.fillPolygon(
711                   new int[]
712                   { res * charWidth - charHeight / 4,
713                       res * charWidth + charHeight / 4, res * charWidth },
714                   new int[]
715                   { ypos - (charHeight / 2), ypos - (charHeight / 2),
716                       ypos - (charHeight / 2) + 8 },
717                   3);
718
719         }
720       }
721
722       // When printing we have an extra clipped region,
723       // the Printable page which we need to account for here
724       Shape clip = g.getClip();
725
726       if (clip == null)
727       {
728         g.setClip(0, 0, cWidth * charWidth, canvasHeight);
729       }
730       else
731       {
732         g.setClip(0, (int) clip.getBounds().getY(), cWidth * charWidth,
733                 (int) clip.getBounds().getHeight());
734       }
735
736       drawPanel(g, startRes, endx, 0, al.getHeight() - 1, ypos);
737
738       if (av.isShowAnnotation())
739       {
740         g.translate(0, cHeight + ypos + 3);
741         if (annotations == null)
742         {
743           annotations = new AnnotationPanel(av);
744         }
745
746         annotations.renderer.drawComponent(annotations, av, g, -1, startRes,
747                 endx + 1);
748         g.translate(0, -cHeight - ypos - 3);
749       }
750       g.setClip(clip);
751       g.translate(-LABEL_WEST, 0);
752
753       ypos += cHeight + getAnnotationHeight() + hgap;
754
755       startRes += cWidth;
756     }
757   }
758
759   /*
760    * Draw a selection group over a wrapped alignment
761    */
762   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
763           int canvasWidth,
764           int canvasHeight, int startRes)
765   {
766     // height gap above each panel
767     int hgap = charHeight;
768     if (av.getScaleAboveWrapped())
769     {
770       hgap += charHeight;
771     }
772
773     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
774     int cHeight = av.getAlignment().getHeight() * charHeight;
775
776     int startx = startRes;
777     int endx;
778     int ypos = hgap; // vertical offset
779     int maxwidth = av.getAlignment().getWidth();
780
781     if (av.hasHiddenColumns())
782     {
783       maxwidth = av.getAlignment().getHiddenColumns()
784               .findColumnPosition(maxwidth);
785     }
786
787     // chop the wrapped alignment extent up into panel-sized blocks and treat
788     // each block as if it were a block from an unwrapped alignment
789     while ((ypos <= canvasHeight) && (startx < maxwidth))
790     {
791       // set end value to be start + width, or maxwidth, whichever is smaller
792       endx = startx + cWidth - 1;
793
794       if (endx > maxwidth)
795       {
796         endx = maxwidth;
797       }
798
799       g.translate(LABEL_WEST, 0);
800
801       drawUnwrappedSelection(g, group, startx, endx, 0,
802               av.getAlignment().getHeight() - 1,
803               ypos);
804
805       g.translate(-LABEL_WEST, 0);
806
807       // update vertical offset
808       ypos += cHeight + getAnnotationHeight() + hgap;
809
810       // update horizontal offset
811       startx += cWidth;
812     }
813   }
814
815   int getAnnotationHeight()
816   {
817     if (!av.isShowAnnotation())
818     {
819       return 0;
820     }
821
822     if (annotations == null)
823     {
824       annotations = new AnnotationPanel(av);
825     }
826
827     return annotations.adjustPanelHeight();
828   }
829
830   /*
831    * Draw an alignment panel for printing
832    * 
833    * @param g1
834    *          Graphics object to draw with
835    * @param startRes
836    *          start residue of print area
837    * @param endRes
838    *          end residue of print area
839    * @param startSeq
840    *          start sequence of print area
841    * @param endSeq
842    *          end sequence of print area
843    * @param offset
844    *          vertical offset
845    */
846   private void drawPanel(Graphics g1, int startRes, int endRes,
847           int startSeq, int endSeq, int offset)
848   {
849     updateViewport();
850     if (!av.hasHiddenColumns())
851     {
852       draw(g1, startRes, endRes, startSeq, endSeq, offset);
853     }
854     else
855     {
856       int screenY = 0;
857       int blockStart = startRes;
858       int blockEnd = endRes;
859
860       for (int[] region : av.getAlignment().getHiddenColumns()
861               .getHiddenColumnsCopy())
862       {
863         int hideStart = region[0];
864         int hideEnd = region[1];
865
866         if (hideStart <= blockStart)
867         {
868           blockStart += (hideEnd - hideStart) + 1;
869           continue;
870         }
871
872         blockEnd = hideStart - 1;
873
874         g1.translate(screenY * charWidth, 0);
875
876         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
877
878         if (av.getShowHiddenMarkers())
879         {
880           g1.setColor(Color.blue);
881
882           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
883                   0 + offset, (blockEnd - blockStart + 1) * charWidth - 1,
884                   (endSeq - startSeq + 1) * charHeight + offset);
885         }
886
887         g1.translate(-screenY * charWidth, 0);
888         screenY += blockEnd - blockStart + 1;
889         blockStart = hideEnd + 1;
890
891         if (screenY > (endRes - startRes))
892         {
893           // already rendered last block
894           return;
895         }
896       }
897
898       if (screenY <= (endRes - startRes))
899       {
900         // remaining visible region to render
901         blockEnd = blockStart + (endRes - startRes) - screenY;
902         g1.translate(screenY * charWidth, 0);
903         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
904
905         g1.translate(-screenY * charWidth, 0);
906       }
907     }
908
909   }
910
911   private void draw(Graphics g, int startRes, int endRes, int startSeq,
912           int endSeq, int offset)
913   {
914     g.setFont(av.getFont());
915     seqRdr.prepare(g, av.isRenderGaps());
916
917     SequenceI nextSeq;
918
919     // / First draw the sequences
920     // ///////////////////////////
921     for (int i = startSeq; i <= endSeq; i++)
922     {
923       nextSeq = av.getAlignment().getSequenceAt(i);
924       if (nextSeq == null)
925       {
926         // occasionally, a race condition occurs such that the alignment row is
927         // empty
928         continue;
929       }
930       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
931               startRes, endRes, offset + ((i - startSeq) * charHeight));
932
933       if (av.isShowSequenceFeatures())
934       {
935         fr.drawSequence(g, nextSeq, startRes, endRes,
936                 offset + ((i - startSeq) * charHeight), false);
937       }
938
939       // / Highlight search Results once all sequences have been drawn
940       // ////////////////////////////////////////////////////////
941       if (av.hasSearchResults())
942       {
943         int[] visibleResults = av.getSearchResults().getResults(nextSeq,
944                 startRes, endRes);
945         if (visibleResults != null)
946         {
947           for (int r = 0; r < visibleResults.length; r += 2)
948           {
949             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
950                     visibleResults[r + 1], (visibleResults[r] - startRes)
951                             * charWidth, offset
952                             + ((i - startSeq) * charHeight));
953           }
954         }
955       }
956
957       if (av.cursorMode && cursorY == i && cursorX >= startRes
958               && cursorX <= endRes)
959       {
960         seqRdr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
961                 offset + ((i - startSeq) * charHeight));
962       }
963     }
964
965     if (av.getSelectionGroup() != null
966             || av.getAlignment().getGroups().size() > 0)
967     {
968       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
969     }
970
971   }
972
973   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
974           int startSeq, int endSeq, int offset)
975   {
976     Graphics2D g = (Graphics2D) g1;
977     //
978     // ///////////////////////////////////
979     // Now outline any areas if necessary
980     // ///////////////////////////////////
981
982     SequenceGroup group = null;
983     int groupIndex = -1;
984
985     if (av.getAlignment().getGroups().size() > 0)
986     {
987       group = av.getAlignment().getGroups().get(0);
988       groupIndex = 0;
989     }
990
991     if (group != null)
992     {
993       g.setStroke(new BasicStroke());
994       g.setColor(group.getOutlineColour());
995       
996       do
997       {
998         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
999                 endSeq, offset);
1000
1001         groupIndex++;
1002
1003         g.setStroke(new BasicStroke());
1004
1005         if (groupIndex >= av.getAlignment().getGroups().size())
1006         {
1007           break;
1008         }
1009
1010         group = av.getAlignment().getGroups().get(groupIndex);
1011
1012       } while (groupIndex < av.getAlignment().getGroups().size());
1013
1014     }
1015
1016   }
1017
1018
1019   /*
1020    * Draw the selection group as a separate image and overlay
1021    */
1022   private BufferedImage drawSelectionGroup(int startRes, int endRes,
1023           int startSeq, int endSeq)
1024   {
1025     // get a new image of the correct size
1026     BufferedImage selectionImage = setupImage();
1027
1028     if (selectionImage == null)
1029     {
1030       return null;
1031     }
1032
1033     SequenceGroup group = av.getSelectionGroup();
1034     if (group == null)
1035     {
1036       // nothing to draw
1037       return null;
1038     }
1039
1040     // set up drawing colour
1041     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1042
1043     setupSelectionGroup(g, selectionImage);
1044
1045     if (!av.getWrapAlignment())
1046     {
1047       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1048               0);
1049     }
1050     else
1051     {
1052       drawWrappedSelection(g, group, getWidth(), getHeight(),
1053               av.getRanges().getStartRes());
1054     }
1055
1056     g.dispose();
1057     return selectionImage;
1058   }
1059
1060   /*
1061    * Set up graphics for selection group
1062    */
1063   private void setupSelectionGroup(Graphics2D g,
1064           BufferedImage selectionImage)
1065   {
1066     // set background to transparent
1067     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1068     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1069
1070     // set up foreground to draw red dashed line
1071     g.setComposite(AlphaComposite.Src);
1072     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1073             BasicStroke.JOIN_ROUND, 3f, new float[]
1074     { 5f, 3f }, 0f));
1075     g.setColor(Color.RED);
1076   }
1077
1078   /*
1079    * Draw a selection group over an unwrapped alignment
1080    * @param g graphics object to draw with
1081    * @param group selection group
1082    * @param startRes start residue of area to draw
1083    * @param endRes end residue of area to draw
1084    * @param startSeq start sequence of area to draw
1085    * @param endSeq end sequence of area to draw
1086    * @param offset vertical offset (used when called from wrapped alignment code)
1087    */
1088   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1089           int startRes, int endRes, int startSeq, int endSeq, int offset)
1090   {
1091     if (!av.hasHiddenColumns())
1092     {
1093       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1094               offset);
1095     }
1096     else
1097     {
1098       // package into blocks of visible columns
1099       int screenY = 0;
1100       int blockStart = startRes;
1101       int blockEnd = endRes;
1102
1103       for (int[] region : av.getAlignment().getHiddenColumns()
1104               .getHiddenColumnsCopy())
1105       {
1106         int hideStart = region[0];
1107         int hideEnd = region[1];
1108
1109         if (hideStart <= blockStart)
1110         {
1111           blockStart += (hideEnd - hideStart) + 1;
1112           continue;
1113         }
1114
1115         blockEnd = hideStart - 1;
1116
1117         g.translate(screenY * charWidth, 0);
1118         drawPartialGroupOutline(g, group,
1119                 blockStart, blockEnd, startSeq, endSeq, offset);
1120
1121         g.translate(-screenY * charWidth, 0);
1122         screenY += blockEnd - blockStart + 1;
1123         blockStart = hideEnd + 1;
1124
1125         if (screenY > (endRes - startRes))
1126         {
1127           // already rendered last block
1128           break;
1129         }
1130       }
1131
1132       if (screenY <= (endRes - startRes))
1133       {
1134         // remaining visible region to render
1135         blockEnd = blockStart + (endRes - startRes) - screenY;
1136         g.translate(screenY * charWidth, 0);
1137         drawPartialGroupOutline(g, group,
1138                 blockStart, blockEnd, startSeq, endSeq, offset);
1139         
1140         g.translate(-screenY * charWidth, 0);
1141       }
1142     }
1143   }
1144
1145   /*
1146    * Draw the selection group as a separate image and overlay
1147    */
1148   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1149           int startRes, int endRes, int startSeq, int endSeq,
1150           int verticalOffset)
1151   {
1152     int visWidth = (endRes - startRes + 1) * charWidth;
1153
1154     int oldY = -1;
1155     int i = 0;
1156     boolean inGroup = false;
1157     int top = -1;
1158     int bottom = -1;
1159
1160     int sx = -1;
1161     int sy = -1;
1162     int xwidth = -1;
1163
1164     for (i = startSeq; i <= endSeq; i++)
1165     {
1166       // position of start residue of group relative to startRes, in pixels
1167       sx = (group.getStartRes() - startRes) * charWidth;
1168
1169       // width of group in pixels
1170       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1171               - 1;
1172
1173       sy = verticalOffset + (i - startSeq) * charHeight;
1174
1175       if (sx + xwidth < 0 || sx > visWidth)
1176       {
1177         continue;
1178       }
1179
1180       if ((sx <= (endRes - startRes) * charWidth)
1181               && group.getSequences(null)
1182                       .contains(av.getAlignment().getSequenceAt(i)))
1183       {
1184         if ((bottom == -1) && !group.getSequences(null)
1185                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1186         {
1187           bottom = sy + charHeight;
1188         }
1189
1190         if (!inGroup)
1191         {
1192           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1193                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1194           {
1195             top = sy;
1196           }
1197
1198           oldY = sy;
1199           inGroup = true;
1200         }
1201       }
1202       else
1203       {
1204         if (inGroup)
1205         {
1206           // if start position is visible, draw vertical line to left of
1207           // group
1208           if (sx >= 0 && sx < visWidth)
1209           {
1210             g.drawLine(sx, oldY, sx, sy);
1211           }
1212
1213           // if end position is visible, draw vertical line to right of
1214           // group
1215           if (sx + xwidth < visWidth)
1216           {
1217             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1218           }
1219
1220           if (sx < 0)
1221           {
1222             xwidth += sx;
1223             sx = 0;
1224           }
1225
1226           // don't let width extend beyond current block, or group extent
1227           // fixes JAL-2672
1228           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1229           {
1230             xwidth = (endRes - startRes + 1) * charWidth - sx;
1231           }
1232           
1233           // draw horizontal line at top of group
1234           if (top != -1)
1235           {
1236             g.drawLine(sx, top, sx + xwidth, top);
1237             top = -1;
1238           }
1239
1240           // draw horizontal line at bottom of group
1241           if (bottom != -1)
1242           {
1243             g.drawLine(sx, bottom, sx + xwidth, bottom);
1244             bottom = -1;
1245           }
1246
1247           inGroup = false;
1248         }
1249       }
1250     }
1251
1252     if (inGroup)
1253     {
1254       sy = verticalOffset + ((i - startSeq) * charHeight);
1255       if (sx >= 0 && sx < visWidth)
1256       {
1257         g.drawLine(sx, oldY, sx, sy);
1258       }
1259
1260       if (sx + xwidth < visWidth)
1261       {
1262         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1263       }
1264
1265       if (sx < 0)
1266       {
1267         xwidth += sx;
1268         sx = 0;
1269       }
1270
1271       if (sx + xwidth > visWidth)
1272       {
1273         xwidth = visWidth;
1274       }
1275       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1276       {
1277         xwidth = (endRes - startRes + 1) * charWidth;
1278       }
1279
1280       if (top != -1)
1281       {
1282         g.drawLine(sx, top, sx + xwidth, top);
1283         top = -1;
1284       }
1285
1286       if (bottom != -1)
1287       {
1288         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1289         bottom = -1;
1290       }
1291
1292       inGroup = false;
1293     }
1294   }
1295   
1296   /**
1297    * DOCUMENT ME!
1298    * 
1299    * @param results
1300    *          DOCUMENT ME!
1301    */
1302   public void highlightSearchResults(SearchResultsI results)
1303   {
1304     img = null;
1305
1306     av.setSearchResults(results);
1307
1308     repaint();
1309   }
1310
1311   @Override
1312   public void propertyChange(PropertyChangeEvent evt)
1313   {
1314     String eventName = evt.getPropertyName();
1315
1316     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1317     {
1318       fastPaint = true;
1319       repaint();
1320     }
1321     else if (av.getWrapAlignment())
1322     {
1323       if (eventName.equals(ViewportRanges.STARTRES))
1324       {
1325         repaint();
1326       }
1327     }
1328     else
1329     {
1330       int scrollX = 0;
1331       if (eventName.equals(ViewportRanges.STARTRES))
1332       {
1333         // Make sure we're not trying to draw a panel
1334         // larger than the visible window
1335         ViewportRanges vpRanges = av.getRanges();
1336         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1337         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1338         if (scrollX > range)
1339         {
1340           scrollX = range;
1341         }
1342         else if (scrollX < -range)
1343         {
1344           scrollX = -range;
1345         }
1346       }
1347
1348       // Both scrolling and resizing change viewport ranges: scrolling changes
1349       // both start and end points, but resize only changes end values.
1350       // Here we only want to fastpaint on a scroll, with resize using a normal
1351       // paint, so scroll events are identified as changes to the horizontal or
1352       // vertical start value.
1353       if (eventName.equals(ViewportRanges.STARTRES))
1354       {
1355         // scroll - startres and endres both change
1356         fastPaint(scrollX, 0);
1357       }
1358       else if (eventName.equals(ViewportRanges.STARTSEQ))
1359       {
1360         // scroll
1361         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1362       }
1363     }
1364   }
1365 }