JAL-2665 check for null selection group image
[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     drawPanel(g1, startRes, endRes, startSeq, endSeq, 0);
441
442     BufferedImage selectImage = drawSelectionGroup(startRes, endRes,
443             startSeq, endSeq);
444     if (selectImage != null)
445     {
446       ((Graphics2D) g1).setComposite(AlphaComposite
447               .getInstance(AlphaComposite.SRC_OVER));
448       g1.drawImage(selectImage, 0, 0, this);
449     }
450   }
451
452   /**
453    * Draw a wrapped alignment panel for printing
454    * 
455    * @param g
456    *          Graphics object to draw with
457    * @param canvasWidth
458    *          width of drawing area
459    * @param canvasHeight
460    *          height of drawing area
461    * @param startRes
462    *          start residue of print area
463    */
464   public void drawWrappedPanelForPrinting(Graphics g, int canvasWidth,
465           int canvasHeight, int startRes)
466   {
467     SequenceGroup group = av.getSelectionGroup();
468
469     drawWrappedPanel(g, canvasWidth, canvasHeight, startRes);
470
471     if (group != null)
472     {
473       BufferedImage selectImage = null;
474       try
475       {
476         selectImage = new BufferedImage(canvasWidth, canvasHeight,
477                 BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
478       } catch (OutOfMemoryError er)
479       {
480         System.gc();
481         System.err.println("Print image OutOfMemory Error.\n" + er);
482         new OOMWarning("Creating wrapped alignment image for printing", er);
483       }
484       if (selectImage != null)
485       {
486         Graphics2D g2 = selectImage.createGraphics();
487         setupSelectionGroup(g2, selectImage);
488         drawWrappedSelection(g2, group, canvasWidth, canvasHeight,
489                 startRes);
490
491         g2.setComposite(
492                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
493         g.drawImage(selectImage, 0, 0, this);
494         g2.dispose();
495       }
496     }
497   }
498
499   /*
500    * Make a local image by combining the cached image img
501    * with any selection
502    */
503   private BufferedImage buildLocalImage(BufferedImage selectImage)
504   {
505     // clone the cached image
506     BufferedImage lcimg = new BufferedImage(img.getWidth(), img.getHeight(),
507             img.getType());
508     Graphics2D g2d = lcimg.createGraphics();
509     g2d.drawImage(img, 0, 0, null);
510
511     // overlay selection group on lcimg
512     if (selectImage != null)
513     {
514       g2d.setComposite(
515               AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
516       g2d.drawImage(selectImage, 0, 0, this);
517     }
518     g2d.dispose();
519
520     return lcimg;
521   }
522
523   /*
524    * Set up a buffered image of the correct height and size for the sequence canvas
525    */
526   private BufferedImage setupImage()
527   {
528     BufferedImage lcimg = null;
529
530     int width = getWidth();
531     int height = getHeight();
532
533     width -= (width % charWidth);
534     height -= (height % charHeight);
535
536     if ((width < 1) || (height < 1))
537     {
538       return null;
539     }
540
541     try
542     {
543       lcimg = new BufferedImage(width, height,
544               BufferedImage.TYPE_INT_ARGB); // ARGB so alpha compositing works
545     } catch (OutOfMemoryError er)
546     {
547       System.gc();
548       System.err.println(
549               "Group image OutOfMemory Redraw Error.\n" + er);
550       new OOMWarning("Creating alignment image for display", er);
551
552       return null;
553     }
554
555     return lcimg;
556   }
557
558   /**
559    * DOCUMENT ME!
560    * 
561    * @param cwidth
562    *          DOCUMENT ME!
563    * 
564    * @return DOCUMENT ME!
565    */
566   public int getWrappedCanvasWidth(int cwidth)
567   {
568     FontMetrics fm = getFontMetrics(av.getFont());
569
570     LABEL_EAST = 0;
571     LABEL_WEST = 0;
572
573     if (av.getScaleRightWrapped())
574     {
575       LABEL_EAST = fm.stringWidth(getMask());
576     }
577
578     if (av.getScaleLeftWrapped())
579     {
580       LABEL_WEST = fm.stringWidth(getMask());
581     }
582
583     return (cwidth - LABEL_EAST - LABEL_WEST) / charWidth;
584   }
585
586   /**
587    * Generates a string of zeroes.
588    * 
589    * @return String
590    */
591   String getMask()
592   {
593     String mask = "00";
594     int maxWidth = 0;
595     int tmp;
596     for (int i = 0; i < av.getAlignment().getHeight(); i++)
597     {
598       tmp = av.getAlignment().getSequenceAt(i).getEnd();
599       if (tmp > maxWidth)
600       {
601         maxWidth = tmp;
602       }
603     }
604
605     for (int i = maxWidth; i > 0; i /= 10)
606     {
607       mask += "0";
608     }
609     return mask;
610   }
611
612   /**
613    * DOCUMENT ME!
614    * 
615    * @param g
616    *          DOCUMENT ME!
617    * @param canvasWidth
618    *          DOCUMENT ME!
619    * @param canvasHeight
620    *          DOCUMENT ME!
621    * @param startRes
622    *          DOCUMENT ME!
623    */
624   private void drawWrappedPanel(Graphics g, int canvasWidth,
625           int canvasHeight, int startRes)
626   {
627     updateViewport();
628     AlignmentI al = av.getAlignment();
629
630     FontMetrics fm = getFontMetrics(av.getFont());
631
632     LABEL_EAST = 0;
633     LABEL_WEST = 0;
634
635     if (av.getScaleRightWrapped())
636     {
637       LABEL_EAST = fm.stringWidth(getMask());
638     }
639
640     if (av.getScaleLeftWrapped())
641     {
642       LABEL_WEST = fm.stringWidth(getMask());
643     }
644
645     int hgap = charHeight;
646     if (av.getScaleAboveWrapped())
647     {
648       hgap += charHeight;
649     }
650
651     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
652     int cHeight = av.getAlignment().getHeight() * charHeight;
653
654     av.setWrappedWidth(cWidth);
655
656     av.getRanges().setViewportStartAndWidth(startRes, cWidth);
657
658     int endx;
659     int ypos = hgap;
660     int maxwidth = av.getAlignment().getWidth();
661
662     if (av.hasHiddenColumns())
663     {
664       maxwidth = av.getAlignment().getHiddenColumns()
665               .findColumnPosition(maxwidth);
666     }
667
668     while ((ypos <= canvasHeight) && (startRes < maxwidth))
669     {
670       endx = startRes + cWidth - 1;
671
672       if (endx > maxwidth)
673       {
674         endx = maxwidth;
675       }
676
677       g.setFont(av.getFont());
678       g.setColor(Color.black);
679
680       if (av.getScaleLeftWrapped())
681       {
682         drawWestScale(g, startRes, endx, ypos);
683       }
684
685       if (av.getScaleRightWrapped())
686       {
687         g.translate(canvasWidth - LABEL_EAST, 0);
688         drawEastScale(g, startRes, endx, ypos);
689         g.translate(-(canvasWidth - LABEL_EAST), 0);
690       }
691
692       g.translate(LABEL_WEST, 0);
693
694       if (av.getScaleAboveWrapped())
695       {
696         drawNorthScale(g, startRes, endx, ypos);
697       }
698
699       if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
700       {
701         g.setColor(Color.blue);
702         int res;
703         HiddenColumns hidden = av.getAlignment().getHiddenColumns();
704         List<Integer> positions = hidden.findHiddenRegionPositions();
705         for (int pos : positions)
706         {
707           res = pos - startRes;
708
709           if (res < 0 || res > endx - startRes)
710           {
711             continue;
712           }
713
714           gg.fillPolygon(
715                   new int[]
716                   { res * charWidth - charHeight / 4,
717                       res * charWidth + charHeight / 4, res * charWidth },
718                   new int[]
719                   { ypos - (charHeight / 2), ypos - (charHeight / 2),
720                       ypos - (charHeight / 2) + 8 },
721                   3);
722
723         }
724       }
725
726       // When printing we have an extra clipped region,
727       // the Printable page which we need to account for here
728       Shape clip = g.getClip();
729
730       if (clip == null)
731       {
732         g.setClip(0, 0, cWidth * charWidth, canvasHeight);
733       }
734       else
735       {
736         g.setClip(0, (int) clip.getBounds().getY(), cWidth * charWidth,
737                 (int) clip.getBounds().getHeight());
738       }
739
740       drawPanel(g, startRes, endx, 0, al.getHeight() - 1, ypos);
741
742       if (av.isShowAnnotation())
743       {
744         g.translate(0, cHeight + ypos + 3);
745         if (annotations == null)
746         {
747           annotations = new AnnotationPanel(av);
748         }
749
750         annotations.renderer.drawComponent(annotations, av, g, -1, startRes,
751                 endx + 1);
752         g.translate(0, -cHeight - ypos - 3);
753       }
754       g.setClip(clip);
755       g.translate(-LABEL_WEST, 0);
756
757       ypos += cHeight + getAnnotationHeight() + hgap;
758
759       startRes += cWidth;
760     }
761   }
762
763   /*
764    * Draw a selection group over a wrapped alignment
765    */
766   private void drawWrappedSelection(Graphics2D g, SequenceGroup group,
767           int canvasWidth,
768           int canvasHeight, int startRes)
769   {
770     // height gap above each panel
771     int hgap = charHeight;
772     if (av.getScaleAboveWrapped())
773     {
774       hgap += charHeight;
775     }
776
777     int cWidth = (canvasWidth - LABEL_EAST - LABEL_WEST) / charWidth;
778     int cHeight = av.getAlignment().getHeight() * charHeight;
779
780     int startx = startRes;
781     int endx;
782     int ypos = hgap; // vertical offset
783     int maxwidth = av.getAlignment().getWidth();
784
785     if (av.hasHiddenColumns())
786     {
787       maxwidth = av.getAlignment().getHiddenColumns()
788               .findColumnPosition(maxwidth);
789     }
790
791     // chop the wrapped alignment extent up into panel-sized blocks and treat
792     // each block as if it were a block from an unwrapped alignment
793     while ((ypos <= canvasHeight) && (startx < maxwidth))
794     {
795       // set end value to be start + width, or maxwidth, whichever is smaller
796       endx = startx + cWidth - 1;
797
798       if (endx > maxwidth)
799       {
800         endx = maxwidth;
801       }
802
803       g.translate(LABEL_WEST, 0);
804
805       drawUnwrappedSelection(g, group, startx, endx, 0,
806               av.getAlignment().getHeight() - 1,
807               ypos);
808
809       g.translate(-LABEL_WEST, 0);
810
811       // update vertical offset
812       ypos += cHeight + getAnnotationHeight() + hgap;
813
814       // update horizontal offset
815       startx += cWidth;
816     }
817   }
818
819   int getAnnotationHeight()
820   {
821     if (!av.isShowAnnotation())
822     {
823       return 0;
824     }
825
826     if (annotations == null)
827     {
828       annotations = new AnnotationPanel(av);
829     }
830
831     return annotations.adjustPanelHeight();
832   }
833
834   /*
835    * Draw an alignment panel for printing
836    * 
837    * @param g1
838    *          Graphics object to draw with
839    * @param startRes
840    *          start residue of print area
841    * @param endRes
842    *          end residue of print area
843    * @param startSeq
844    *          start sequence of print area
845    * @param endSeq
846    *          end sequence of print area
847    * @param offset
848    *          vertical offset
849    */
850   private void drawPanel(Graphics g1, int startRes, int endRes,
851           int startSeq, int endSeq, int offset)
852   {
853     updateViewport();
854     if (!av.hasHiddenColumns())
855     {
856       draw(g1, startRes, endRes, startSeq, endSeq, offset);
857     }
858     else
859     {
860       int screenY = 0;
861       int blockStart = startRes;
862       int blockEnd = endRes;
863
864       for (int[] region : av.getAlignment().getHiddenColumns()
865               .getHiddenColumnsCopy())
866       {
867         int hideStart = region[0];
868         int hideEnd = region[1];
869
870         if (hideStart <= blockStart)
871         {
872           blockStart += (hideEnd - hideStart) + 1;
873           continue;
874         }
875
876         blockEnd = hideStart - 1;
877
878         g1.translate(screenY * charWidth, 0);
879
880         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
881
882         if (av.getShowHiddenMarkers())
883         {
884           g1.setColor(Color.blue);
885
886           g1.drawLine((blockEnd - blockStart + 1) * charWidth - 1,
887                   0 + offset, (blockEnd - blockStart + 1) * charWidth - 1,
888                   (endSeq - startSeq + 1) * charHeight + offset);
889         }
890
891         g1.translate(-screenY * charWidth, 0);
892         screenY += blockEnd - blockStart + 1;
893         blockStart = hideEnd + 1;
894
895         if (screenY > (endRes - startRes))
896         {
897           // already rendered last block
898           return;
899         }
900       }
901
902       if (screenY <= (endRes - startRes))
903       {
904         // remaining visible region to render
905         blockEnd = blockStart + (endRes - startRes) - screenY;
906         g1.translate(screenY * charWidth, 0);
907         draw(g1, blockStart, blockEnd, startSeq, endSeq, offset);
908
909         g1.translate(-screenY * charWidth, 0);
910       }
911     }
912
913   }
914
915   private void draw(Graphics g, int startRes, int endRes, int startSeq,
916           int endSeq, int offset)
917   {
918     g.setFont(av.getFont());
919     seqRdr.prepare(g, av.isRenderGaps());
920
921     SequenceI nextSeq;
922
923     // / First draw the sequences
924     // ///////////////////////////
925     for (int i = startSeq; i <= endSeq; i++)
926     {
927       nextSeq = av.getAlignment().getSequenceAt(i);
928       if (nextSeq == null)
929       {
930         // occasionally, a race condition occurs such that the alignment row is
931         // empty
932         continue;
933       }
934       seqRdr.drawSequence(nextSeq, av.getAlignment().findAllGroups(nextSeq),
935               startRes, endRes, offset + ((i - startSeq) * charHeight));
936
937       if (av.isShowSequenceFeatures())
938       {
939         fr.drawSequence(g, nextSeq, startRes, endRes,
940                 offset + ((i - startSeq) * charHeight), false);
941       }
942
943       // / Highlight search Results once all sequences have been drawn
944       // ////////////////////////////////////////////////////////
945       if (av.hasSearchResults())
946       {
947         int[] visibleResults = av.getSearchResults().getResults(nextSeq,
948                 startRes, endRes);
949         if (visibleResults != null)
950         {
951           for (int r = 0; r < visibleResults.length; r += 2)
952           {
953             seqRdr.drawHighlightedText(nextSeq, visibleResults[r],
954                     visibleResults[r + 1], (visibleResults[r] - startRes)
955                             * charWidth, offset
956                             + ((i - startSeq) * charHeight));
957           }
958         }
959       }
960
961       if (av.cursorMode && cursorY == i && cursorX >= startRes
962               && cursorX <= endRes)
963       {
964         seqRdr.drawCursor(nextSeq, cursorX, (cursorX - startRes) * charWidth,
965                 offset + ((i - startSeq) * charHeight));
966       }
967     }
968
969     if (av.getSelectionGroup() != null
970             || av.getAlignment().getGroups().size() > 0)
971     {
972       drawGroupsBoundaries(g, startRes, endRes, startSeq, endSeq, offset);
973     }
974
975   }
976
977   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
978           int startSeq, int endSeq, int offset)
979   {
980     Graphics2D g = (Graphics2D) g1;
981     //
982     // ///////////////////////////////////
983     // Now outline any areas if necessary
984     // ///////////////////////////////////
985
986     SequenceGroup group = null;
987     int groupIndex = -1;
988
989     if (av.getAlignment().getGroups().size() > 0)
990     {
991       group = av.getAlignment().getGroups().get(0);
992       groupIndex = 0;
993     }
994
995     if (group != null)
996     {
997       g.setStroke(new BasicStroke());
998       g.setColor(group.getOutlineColour());
999       
1000       do
1001       {
1002         drawPartialGroupOutline(g, group, startRes, endRes, startSeq,
1003                 endSeq, offset);
1004
1005         groupIndex++;
1006
1007         g.setStroke(new BasicStroke());
1008
1009         if (groupIndex >= av.getAlignment().getGroups().size())
1010         {
1011           break;
1012         }
1013
1014         group = av.getAlignment().getGroups().get(groupIndex);
1015
1016       } while (groupIndex < av.getAlignment().getGroups().size());
1017
1018     }
1019
1020   }
1021
1022
1023   /*
1024    * Draw the selection group as a separate image and overlay
1025    */
1026   private BufferedImage drawSelectionGroup(int startRes, int endRes,
1027           int startSeq, int endSeq)
1028   {
1029     // get a new image of the correct size
1030     BufferedImage selectionImage = setupImage();
1031
1032     if (selectionImage == null)
1033     {
1034       return null;
1035     }
1036
1037     SequenceGroup group = av.getSelectionGroup();
1038     if (group == null)
1039     {
1040       // nothing to draw
1041       return null;
1042     }
1043
1044     // set up drawing colour
1045     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1046
1047     setupSelectionGroup(g, selectionImage);
1048
1049     if (!av.getWrapAlignment())
1050     {
1051       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1052               0);
1053     }
1054     else
1055     {
1056       drawWrappedSelection(g, group, getWidth(), getHeight(),
1057               av.getRanges().getStartRes());
1058     }
1059
1060     g.dispose();
1061     return selectionImage;
1062   }
1063
1064   /*
1065    * Set up graphics for selection group
1066    */
1067   private void setupSelectionGroup(Graphics2D g,
1068           BufferedImage selectionImage)
1069   {
1070     // set background to transparent
1071     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1072     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1073
1074     // set up foreground to draw red dashed line
1075     g.setComposite(AlphaComposite.Src);
1076     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1077             BasicStroke.JOIN_ROUND, 3f, new float[]
1078     { 5f, 3f }, 0f));
1079     g.setColor(Color.RED);
1080   }
1081
1082   /*
1083    * Draw a selection group over an unwrapped alignment
1084    * @param g graphics object to draw with
1085    * @param group selection group
1086    * @param startRes start residue of area to draw
1087    * @param endRes end residue of area to draw
1088    * @param startSeq start sequence of area to draw
1089    * @param endSeq end sequence of area to draw
1090    * @param offset vertical offset (used when called from wrapped alignment code)
1091    */
1092   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1093           int startRes, int endRes, int startSeq, int endSeq, int offset)
1094   {
1095     if (!av.hasHiddenColumns())
1096     {
1097       drawPartialGroupOutline(g, group, startRes, endRes, startSeq, endSeq,
1098               offset);
1099     }
1100     else
1101     {
1102       // package into blocks of visible columns
1103       int screenY = 0;
1104       int blockStart = startRes;
1105       int blockEnd = endRes;
1106
1107       for (int[] region : av.getAlignment().getHiddenColumns()
1108               .getHiddenColumnsCopy())
1109       {
1110         int hideStart = region[0];
1111         int hideEnd = region[1];
1112
1113         if (hideStart <= blockStart)
1114         {
1115           blockStart += (hideEnd - hideStart) + 1;
1116           continue;
1117         }
1118
1119         blockEnd = hideStart - 1;
1120
1121         g.translate(screenY * charWidth, 0);
1122         drawPartialGroupOutline(g, group,
1123                 blockStart, blockEnd, startSeq, endSeq, offset);
1124
1125         g.translate(-screenY * charWidth, 0);
1126         screenY += blockEnd - blockStart + 1;
1127         blockStart = hideEnd + 1;
1128
1129         if (screenY > (endRes - startRes))
1130         {
1131           // already rendered last block
1132           break;
1133         }
1134       }
1135
1136       if (screenY <= (endRes - startRes))
1137       {
1138         // remaining visible region to render
1139         blockEnd = blockStart + (endRes - startRes) - screenY;
1140         g.translate(screenY * charWidth, 0);
1141         drawPartialGroupOutline(g, group,
1142                 blockStart, blockEnd, startSeq, endSeq, offset);
1143         
1144         g.translate(-screenY * charWidth, 0);
1145       }
1146     }
1147   }
1148
1149   /*
1150    * Draw the selection group as a separate image and overlay
1151    */
1152   private void drawPartialGroupOutline(Graphics2D g, SequenceGroup group,
1153           int startRes, int endRes, int startSeq, int endSeq,
1154           int verticalOffset)
1155   {
1156     int visWidth = (endRes - startRes + 1) * charWidth;
1157
1158     int oldY = -1;
1159     int i = 0;
1160     boolean inGroup = false;
1161     int top = -1;
1162     int bottom = -1;
1163
1164     int sx = -1;
1165     int sy = -1;
1166     int xwidth = -1;
1167
1168     for (i = startSeq; i <= endSeq; i++)
1169     {
1170       // position of start residue of group relative to startRes, in pixels
1171       sx = (group.getStartRes() - startRes) * charWidth;
1172
1173       // width of group in pixels
1174       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1175               - 1;
1176
1177       sy = verticalOffset + (i - startSeq) * charHeight;
1178
1179       if (sx + xwidth < 0 || sx > visWidth)
1180       {
1181         continue;
1182       }
1183
1184       if ((sx <= (endRes - startRes) * charWidth)
1185               && group.getSequences(null)
1186                       .contains(av.getAlignment().getSequenceAt(i)))
1187       {
1188         if ((bottom == -1) && !group.getSequences(null)
1189                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1190         {
1191           bottom = sy + charHeight;
1192         }
1193
1194         if (!inGroup)
1195         {
1196           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1197                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1198           {
1199             top = sy;
1200           }
1201
1202           oldY = sy;
1203           inGroup = true;
1204         }
1205       }
1206       else
1207       {
1208         if (inGroup)
1209         {
1210           // if start position is visible, draw vertical line to left of
1211           // group
1212           if (sx >= 0 && sx < visWidth)
1213           {
1214             g.drawLine(sx, oldY, sx, sy);
1215           }
1216
1217           // if end position is visible, draw vertical line to right of
1218           // group
1219           if (sx + xwidth < visWidth)
1220           {
1221             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1222           }
1223
1224           if (sx < 0)
1225           {
1226             xwidth += sx;
1227             sx = 0;
1228           }
1229
1230           // don't let width extend beyond current block, or group extent
1231           // fixes JAL-2672
1232           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1233           {
1234             xwidth = (endRes - startRes + 1) * charWidth - sx;
1235           }
1236           
1237           // draw horizontal line at top of group
1238           if (top != -1)
1239           {
1240             g.drawLine(sx, top, sx + xwidth, top);
1241             top = -1;
1242           }
1243
1244           // draw horizontal line at bottom of group
1245           if (bottom != -1)
1246           {
1247             g.drawLine(sx, bottom, sx + xwidth, bottom);
1248             bottom = -1;
1249           }
1250
1251           inGroup = false;
1252         }
1253       }
1254     }
1255
1256     if (inGroup)
1257     {
1258       sy = verticalOffset + ((i - startSeq) * charHeight);
1259       if (sx >= 0 && sx < visWidth)
1260       {
1261         g.drawLine(sx, oldY, sx, sy);
1262       }
1263
1264       if (sx + xwidth < visWidth)
1265       {
1266         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1267       }
1268
1269       if (sx < 0)
1270       {
1271         xwidth += sx;
1272         sx = 0;
1273       }
1274
1275       if (sx + xwidth > visWidth)
1276       {
1277         xwidth = visWidth;
1278       }
1279       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1280       {
1281         xwidth = (endRes - startRes + 1) * charWidth;
1282       }
1283
1284       if (top != -1)
1285       {
1286         g.drawLine(sx, top, sx + xwidth, top);
1287         top = -1;
1288       }
1289
1290       if (bottom != -1)
1291       {
1292         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1293         bottom = -1;
1294       }
1295
1296       inGroup = false;
1297     }
1298   }
1299   
1300   /**
1301    * DOCUMENT ME!
1302    * 
1303    * @param results
1304    *          DOCUMENT ME!
1305    */
1306   public void highlightSearchResults(SearchResultsI results)
1307   {
1308     img = null;
1309
1310     av.setSearchResults(results);
1311
1312     repaint();
1313   }
1314
1315   @Override
1316   public void propertyChange(PropertyChangeEvent evt)
1317   {
1318     String eventName = evt.getPropertyName();
1319
1320     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1321     {
1322       fastPaint = true;
1323       repaint();
1324     }
1325     else if (av.getWrapAlignment())
1326     {
1327       if (eventName.equals(ViewportRanges.STARTRES))
1328       {
1329         repaint();
1330       }
1331     }
1332     else
1333     {
1334       int scrollX = 0;
1335       if (eventName.equals(ViewportRanges.STARTRES))
1336       {
1337         // Make sure we're not trying to draw a panel
1338         // larger than the visible window
1339         ViewportRanges vpRanges = av.getRanges();
1340         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1341         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1342         if (scrollX > range)
1343         {
1344           scrollX = range;
1345         }
1346         else if (scrollX < -range)
1347         {
1348           scrollX = -range;
1349         }
1350       }
1351
1352       // Both scrolling and resizing change viewport ranges: scrolling changes
1353       // both start and end points, but resize only changes end values.
1354       // Here we only want to fastpaint on a scroll, with resize using a normal
1355       // paint, so scroll events are identified as changes to the horizontal or
1356       // vertical start value.
1357       if (eventName.equals(ViewportRanges.STARTRES))
1358       {
1359         // scroll - startres and endres both change
1360         fastPaint(scrollX, 0);
1361       }
1362       else if (eventName.equals(ViewportRanges.STARTSEQ))
1363       {
1364         // scroll
1365         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1366       }
1367     }
1368   }
1369 }