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