JAL-2665 tidies
[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       g.setStroke(new BasicStroke());
927       g.setColor(group.getOutlineColour());
928       
929       do
930       {
931         
932         // drawSelectionGroupPart(g, group, startRes, endRes, startSeq,
933         // endSeq,offset);
934         int oldY = -1;
935         int i = 0;
936         boolean inGroup = false;
937         int top = -1;
938         int bottom = -1;
939
940         for (i = startSeq; i <= endSeq; i++)
941         {
942           // position of start residue of group relative to startRes, in pixels
943           sx = (group.getStartRes() - startRes) * charWidth;
944           sy = offset + ((i - startSeq) * charHeight);
945           // width of group in pixels
946           ex = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
947                   - 1;
948
949           if (sx + ex < 0 || sx > visWidth)
950           {
951             continue;
952           }
953
954           if ((sx <= (endRes - startRes) * charWidth)
955                   && group.getSequences(null).contains(
956                           av.getAlignment().getSequenceAt(i)))
957           {
958             if ((bottom == -1)
959                     && !group.getSequences(null).contains(
960                             av.getAlignment().getSequenceAt(i + 1)))
961             {
962               bottom = sy + charHeight;
963             }
964
965             if (!inGroup)
966             {
967               if (((top == -1) && (i == 0))
968                       || !group.getSequences(null).contains(
969                               av.getAlignment().getSequenceAt(i - 1)))
970               {
971                 top = sy;
972               }
973
974               oldY = sy;
975               inGroup = true;
976
977               g.setStroke(new BasicStroke());
978               g.setColor(group.getOutlineColour());
979             }
980           }
981           else
982           {
983             if (inGroup)
984             {
985               // if start position is visible, draw vertical line to left of
986               // group
987               if (sx >= 0 && sx < visWidth)
988               {
989                 g.drawLine(sx, oldY, sx, sy);
990               }
991
992               // if end position is visible, draw vertical line to right of
993               // group
994               if (sx + ex < visWidth)
995               {
996                 g.drawLine(sx + ex, oldY, sx + ex, sy);
997               }
998
999               if (sx < 0)
1000               {
1001                 ex += sx;
1002                 sx = 0;
1003               }
1004
1005               if (sx + ex > visWidth)
1006               {
1007                 ex = visWidth;
1008               }
1009               else if (sx + ex >= (endRes - startRes + 1) * charWidth)
1010               {
1011                 ex = (endRes - startRes + 1) * charWidth;
1012               }
1013
1014               // draw horizontal line at top of group
1015               if (top != -1)
1016               {
1017                 g.drawLine(sx, top, sx + ex, top);
1018                 top = -1;
1019               }
1020
1021               // draw horizontal line at bottom of group
1022               if (bottom != -1)
1023               {
1024                 g.drawLine(sx, bottom, sx + ex, bottom);
1025                 bottom = -1;
1026               }
1027
1028               inGroup = false;
1029             }
1030           }
1031         }
1032
1033         if (inGroup)
1034         {
1035           sy = offset + ((i - startSeq) * charHeight);
1036           if (sx >= 0 && sx < visWidth)
1037           {
1038             g.drawLine(sx, oldY, sx, sy);
1039           }
1040
1041           if (sx + ex < visWidth)
1042           {
1043             g.drawLine(sx + ex, oldY, sx + ex, sy);
1044           }
1045
1046           if (sx < 0)
1047           {
1048             ex += sx;
1049             sx = 0;
1050           }
1051
1052           if (sx + ex > visWidth)
1053           {
1054             ex = visWidth;
1055           }
1056           else if (sx + ex >= (endRes - startRes + 1) * charWidth)
1057           {
1058             ex = (endRes - startRes + 1) * charWidth;
1059           }
1060
1061           if (top != -1)
1062           {
1063             g.drawLine(sx, top, sx + ex, top);
1064             top = -1;
1065           }
1066
1067           if (bottom != -1)
1068           {
1069             g.drawLine(sx, bottom - 1, sx + ex, bottom - 1);
1070             bottom = -1;
1071           }
1072
1073           inGroup = false;
1074         }
1075
1076         groupIndex++;
1077
1078         g.setStroke(new BasicStroke());
1079
1080         if (groupIndex >= av.getAlignment().getGroups().size())
1081         {
1082           break;
1083         }
1084
1085         group = av.getAlignment().getGroups().get(groupIndex);
1086
1087       } while (groupIndex < av.getAlignment().getGroups().size());
1088
1089     }
1090
1091   }
1092
1093
1094   /*
1095    * Draw the selection group as a separate image and overlay
1096    */
1097   private BufferedImage drawSelectionGroup(int startRes, int endRes,
1098           int startSeq, int endSeq)
1099   {
1100     // get a new image of the correct size
1101     BufferedImage selectionImage = setupImage();
1102
1103     if (selectionImage == null)
1104     {
1105       return null;
1106     }
1107
1108     SequenceGroup group = av.getSelectionGroup();
1109     if (group == null)
1110     {
1111       // nothing to draw
1112       return null;
1113     }
1114
1115     // set up drawing colour
1116     Graphics2D g = (Graphics2D) selectionImage.getGraphics();
1117
1118     // set background to transparent
1119     g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
1120     g.fillRect(0, 0, selectionImage.getWidth(), selectionImage.getHeight());
1121
1122     // set up foreground to draw red dashed line
1123     g.setComposite(AlphaComposite.Src);
1124     g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
1125             BasicStroke.JOIN_ROUND, 3f, new float[]
1126     { 5f, 3f }, 0f));
1127     g.setColor(Color.RED);
1128
1129     if (!av.getWrapAlignment())
1130     {
1131       drawUnwrappedSelection(g, group, startRes, endRes, startSeq, endSeq,
1132               0);
1133     }
1134     else
1135     {
1136       drawWrappedSelection(g, group, getWidth(), getHeight(),
1137               av.getRanges().getStartRes());
1138     }
1139
1140     g.dispose();
1141     return selectionImage;
1142   }
1143
1144   /*
1145    * Draw a selection group over an unwrapped alignment
1146    * @param g graphics object to draw with
1147    * @param group selection group
1148    * @param startRes start residue of area to draw
1149    * @param endRes end residue of area to draw
1150    * @param startSeq start sequence of area to draw
1151    * @param endSeq end sequence of area to draw
1152    * @param offset vertical offset (used when called from wrapped alignment code)
1153    */
1154   private void drawUnwrappedSelection(Graphics2D g, SequenceGroup group,
1155           int startRes, int endRes, int startSeq, int endSeq, int offset)
1156   {
1157     if (!av.hasHiddenColumns())
1158     {
1159       drawSelectionGroupPart(g, group, startRes, endRes, startSeq, endSeq,
1160               offset);
1161     }
1162     else
1163     {
1164       // package into blocks of visible columns
1165       int screenY = 0;
1166       int blockStart = startRes;
1167       int blockEnd = endRes;
1168
1169       for (int[] region : av.getAlignment().getHiddenColumns()
1170               .getHiddenColumnsCopy())
1171       {
1172         int hideStart = region[0];
1173         int hideEnd = region[1];
1174
1175         if (hideStart <= blockStart)
1176         {
1177           blockStart += (hideEnd - hideStart) + 1;
1178           continue;
1179         }
1180
1181         blockEnd = hideStart - 1;
1182
1183         g.translate(screenY * charWidth, 0);
1184         drawSelectionGroupPart(g, group,
1185                 blockStart, blockEnd, startSeq, endSeq, offset);
1186
1187         g.translate(-screenY * charWidth, 0);
1188         screenY += blockEnd - blockStart + 1;
1189         blockStart = hideEnd + 1;
1190
1191         if (screenY > (endRes - startRes))
1192         {
1193           // already rendered last block
1194           break;
1195         }
1196       }
1197
1198       if (screenY <= (endRes - startRes))
1199       {
1200         // remaining visible region to render
1201         blockEnd = blockStart + (endRes - startRes) - screenY;
1202         g.translate(screenY * charWidth, 0);
1203         drawSelectionGroupPart(g, group,
1204                 blockStart, blockEnd, startSeq, endSeq, offset);
1205         
1206         g.translate(-screenY * charWidth, 0);
1207       }
1208     }
1209   }
1210
1211   /*
1212    * Draw the selection group as a separate image and overlay
1213    */
1214   private void drawSelectionGroupPart(Graphics2D g, SequenceGroup group,
1215           int startRes, int endRes, int startSeq, int endSeq,
1216           int verticalOffset)
1217   {
1218     int visWidth = (endRes - startRes + 1) * charWidth;
1219
1220     int oldY = -1;
1221     int i = 0;
1222     boolean inGroup = false;
1223     int top = -1;
1224     int bottom = -1;
1225
1226     int sx = -1;
1227     int sy = -1;
1228     int xwidth = -1;
1229
1230     for (i = startSeq; i <= endSeq; i++)
1231     {
1232       // position of start residue of group relative to startRes, in pixels
1233       sx = (group.getStartRes() - startRes) * charWidth;
1234
1235       // width of group in pixels
1236       xwidth = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
1237               - 1;
1238
1239       sy = verticalOffset + (i - startSeq) * charHeight;
1240
1241       if (sx + xwidth < 0 || sx > visWidth)
1242       {
1243         continue;
1244       }
1245
1246       if ((sx <= (endRes - startRes) * charWidth)
1247               && group.getSequences(null)
1248                       .contains(av.getAlignment().getSequenceAt(i)))
1249       {
1250         if ((bottom == -1) && !group.getSequences(null)
1251                 .contains(av.getAlignment().getSequenceAt(i + 1)))
1252         {
1253           bottom = sy + charHeight;
1254         }
1255
1256         if (!inGroup)
1257         {
1258           if (((top == -1) && (i == 0)) || !group.getSequences(null)
1259                   .contains(av.getAlignment().getSequenceAt(i - 1)))
1260           {
1261             top = sy;
1262           }
1263
1264           oldY = sy;
1265           inGroup = true;
1266         }
1267       }
1268       else
1269       {
1270         if (inGroup)
1271         {
1272           // if start position is visible, draw vertical line to left of
1273           // group
1274           if (sx >= 0 && sx < visWidth)
1275           {
1276             g.drawLine(sx, oldY, sx, sy);
1277           }
1278
1279           // if end position is visible, draw vertical line to right of
1280           // group
1281           if (sx + xwidth < visWidth)
1282           {
1283             g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1284           }
1285
1286           if (sx < 0)
1287           {
1288             xwidth += sx;
1289             sx = 0;
1290           }
1291
1292           if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1293           {
1294             xwidth = (endRes - startRes + 1) * charWidth - sx;
1295           }
1296           
1297           // draw horizontal line at top of group
1298           if (top != -1)
1299           {
1300             g.drawLine(sx, top, sx + xwidth, top);
1301             top = -1;
1302           }
1303
1304           // draw horizontal line at bottom of group
1305           if (bottom != -1)
1306           {
1307             g.drawLine(sx, bottom, sx + xwidth, bottom);
1308             bottom = -1;
1309           }
1310
1311           inGroup = false;
1312         }
1313       }
1314     }
1315
1316     if (inGroup)
1317     {
1318       sy = verticalOffset + ((i - startSeq) * charHeight);
1319       if (sx >= 0 && sx < visWidth)
1320       {
1321         g.drawLine(sx, oldY, sx, sy);
1322       }
1323
1324       if (sx + xwidth < visWidth)
1325       {
1326         g.drawLine(sx + xwidth, oldY, sx + xwidth, sy);
1327       }
1328
1329       if (sx < 0)
1330       {
1331         xwidth += sx;
1332         sx = 0;
1333       }
1334
1335       if (sx + xwidth > visWidth)
1336       {
1337         xwidth = visWidth;
1338       }
1339       else if (sx + xwidth >= (endRes - startRes + 1) * charWidth)
1340       {
1341         xwidth = (endRes - startRes + 1) * charWidth;
1342       }
1343
1344       if (top != -1)
1345       {
1346         g.drawLine(sx, top, sx + xwidth, top);
1347         top = -1;
1348       }
1349
1350       if (bottom != -1)
1351       {
1352         g.drawLine(sx, bottom - 1, sx + xwidth, bottom - 1);
1353         bottom = -1;
1354       }
1355
1356       inGroup = false;
1357     }
1358   }
1359   
1360   /**
1361    * DOCUMENT ME!
1362    * 
1363    * @param results
1364    *          DOCUMENT ME!
1365    */
1366   public void highlightSearchResults(SearchResultsI results)
1367   {
1368     img = null;
1369
1370     av.setSearchResults(results);
1371
1372     repaint();
1373   }
1374
1375   @Override
1376   public void propertyChange(PropertyChangeEvent evt)
1377   {
1378     String eventName = evt.getPropertyName();
1379
1380     if (eventName.equals(SequenceGroup.SEQ_GROUP_CHANGED))
1381     {
1382       paintSeqGroup();
1383     }
1384     else if (av.getWrapAlignment())
1385     {
1386       if (eventName.equals(ViewportRanges.STARTRES))
1387       {
1388         repaint();
1389       }
1390     }
1391     else
1392     {
1393       int scrollX = 0;
1394       if (eventName.equals(ViewportRanges.STARTRES))
1395       {
1396         // Make sure we're not trying to draw a panel
1397         // larger than the visible window
1398         ViewportRanges vpRanges = av.getRanges();
1399         scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
1400         int range = vpRanges.getEndRes() - vpRanges.getStartRes();
1401         if (scrollX > range)
1402         {
1403           scrollX = range;
1404         }
1405         else if (scrollX < -range)
1406         {
1407           scrollX = -range;
1408         }
1409       }
1410
1411       // Both scrolling and resizing change viewport ranges: scrolling changes
1412       // both start and end points, but resize only changes end values.
1413       // Here we only want to fastpaint on a scroll, with resize using a normal
1414       // paint, so scroll events are identified as changes to the horizontal or
1415       // vertical start value.
1416       if (eventName.equals(ViewportRanges.STARTRES))
1417       {
1418         // scroll - startres and endres both change
1419         fastPaint(scrollX, 0);
1420       }
1421       else if (eventName.equals(ViewportRanges.STARTSEQ))
1422       {
1423         // scroll
1424         fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
1425       }
1426     }
1427   }
1428 }