5a4fc57e3316de5b68ad1d07f67054cded78feb6
[jalview.git] / src / jalview / viewmodel / ViewportRanges.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.viewmodel;
22
23 import jalview.datamodel.AlignmentI;
24 import jalview.datamodel.HiddenColumns;
25
26 /**
27  * Supplies and updates viewport properties relating to position such as: start
28  * and end residues and sequences; ideally will serve hidden columns/rows too.
29  * Intention also to support calculations for positioning, scrolling etc. such
30  * as finding the middle of the viewport, checking for scrolls off screen
31  */
32 public class ViewportRanges extends ViewportProperties
33 {
34   public static final String STARTRES = "startres";
35
36   public static final String ENDRES = "endres";
37
38   public static final String STARTSEQ = "startseq";
39
40   public static final String ENDSEQ = "endseq";
41
42   public static final String STARTRESANDSEQ = "startresandseq";
43
44   public static final String MOVE_VIEWPORT = "move_viewport";
45
46   private boolean wrappedMode = false;
47
48   // start residue of viewport
49   private int startRes;
50
51   // end residue of viewport
52   private int endRes;
53
54   // start sequence of viewport
55   private int startSeq;
56
57   // end sequence of viewport
58   private int endSeq;
59
60   // alignment
61   private AlignmentI al;
62
63   /**
64    * Constructor
65    * 
66    * @param alignment
67    *          the viewport's alignment
68    */
69   public ViewportRanges(AlignmentI alignment)
70   {
71     // initial values of viewport settings
72     this.startRes = 0;
73     this.endRes = alignment.getWidth() - 1;
74     this.startSeq = 0;
75     this.endSeq = alignment.getHeight() - 1;
76     this.al = alignment;
77   }
78
79   /**
80    * Get alignment width in cols, including hidden cols
81    */
82   public int getAbsoluteAlignmentWidth()
83   {
84     return al.getWidth();
85   }
86
87   /**
88    * Get alignment height in rows, including hidden rows
89    */
90   public int getAbsoluteAlignmentHeight()
91   {
92     return al.getHeight() + al.getHiddenSequences().getSize();
93   }
94
95   /**
96    * Get alignment width in cols, excluding hidden cols
97    */
98   public int getVisibleAlignmentWidth()
99   {
100     return al.getVisibleWidth();
101   }
102
103   /**
104    * Get alignment height in rows, excluding hidden rows
105    */
106   public int getVisibleAlignmentHeight()
107   {
108     return al.getHeight();
109   }
110
111   /**
112    * Set first residue visible in the viewport, and retain the current width.
113    * Fires a property change event.
114    * 
115    * @param res
116    *          residue position
117    */
118   public void setStartRes(int res)
119   {
120     int width = getViewportWidth();
121     setStartEndRes(res, res + width - 1);
122   }
123
124   /**
125    * Set start and end residues at the same time. This method only fires one
126    * event for the two changes, and should be used in preference to separate
127    * calls to setStartRes and setEndRes.
128    * 
129    * @param start
130    *          the start residue
131    * @param end
132    *          the end residue
133    */
134   public void setStartEndRes(int start, int end)
135   {
136     int[] oldvalues = updateStartEndRes(start, end);
137     int oldstartres = oldvalues[0];
138     int oldendres = oldvalues[1];
139     
140     if (oldstartres == startRes && oldendres == endRes)
141     {
142       return; // BH 2019.07.27 standard check for no changes
143     }
144
145     // "STARTRES" is a misnomer here -- really "STARTORENDRES"
146     // note that this could be "no change" if the range is just being expanded
147     changeSupport.firePropertyChange(STARTRES, oldstartres, startRes);
148     if (oldstartres == startRes)
149     {
150       // only caught in ViewportRangesTest
151       // No listener cares about this
152       // "ENDRES" is a misnomer here -- really "ENDONLYRES"
153       // BH 2019.07.27 adds end change check
154       // fire only if only the end is changed
155       // event won't be fired if start positions are same
156       // fire an event for the end positions in case they changed
157      changeSupport.firePropertyChange(ENDRES, oldendres, endRes);
158     }
159   }
160
161   /**
162    * Update start and end residue values, adjusting for width constraints if
163    * necessary
164    * 
165    * @param start
166    *          start residue
167    * @param end
168    *          end residue
169    * @return array containing old start and end residue values
170    */
171   private int[] updateStartEndRes(int start, int end)
172   {
173     int oldstartres = this.startRes;
174
175     /*
176      * if not wrapped, don't leave white space at the right margin
177      */
178     int lastColumn = getVisibleAlignmentWidth() - 1;
179     if (!wrappedMode && (start > lastColumn))
180     {
181       startRes = Math.max(lastColumn, 0);
182     }
183     else if (start < 0)
184     {
185       startRes = 0;
186     }
187     else
188     {
189       startRes = start;
190     }
191
192     int oldendres = this.endRes;
193     if (end < 0)
194     {
195       endRes = 0;
196     }
197     else if (!wrappedMode && (end > lastColumn))
198     {
199       endRes = Math.max(lastColumn, 0);
200     }
201     else
202     {
203       endRes = end;
204     }
205     return new int[] { oldstartres, oldendres };
206   }
207
208   /**
209    * Set the first sequence visible in the viewport, maintaining the height. If
210    * the viewport would extend past the last sequence, sets the viewport so it
211    * sits at the bottom of the alignment. Fires a property change event.
212    * 
213    * @param seq
214    *          sequence position
215    */
216   public void setStartSeq(int seq)
217   {
218     int startseq = seq;
219     int height = getViewportHeight();
220     if (startseq + height - 1 > getVisibleAlignmentHeight() - 1)
221     {
222       startseq = getVisibleAlignmentHeight() - height;
223     }
224     setStartEndSeq(startseq, startseq + height - 1);
225   }
226
227   /**
228    * Set start and end sequences at the same time. The viewport height may
229    * change. This method only fires one event for the two changes, and should be
230    * used in preference to separate calls to setStartSeq and setEndSeq.
231    * 
232    * @param start
233    *          the start sequence
234    * @param end
235    *          the end sequence
236    */
237   public void setStartEndSeq(int start, int end)
238   {
239     // System.out.println("ViewportRange setStartEndSeq " + start + " " + end);
240     int[] oldvalues = updateStartEndSeq(start, end);
241     int oldstartseq = oldvalues[0];
242     int oldendseq = oldvalues[1];
243
244     changeSupport.firePropertyChange(STARTSEQ, oldstartseq, startSeq);
245     if (oldstartseq == startSeq)
246     {
247       // event won't be fired if start positions are the same
248       // fire in case the end positions changed
249       changeSupport.firePropertyChange(ENDSEQ, oldendseq, endSeq);
250     }
251   }
252
253   /**
254    * Update start and end sequence values, adjusting for height constraints if
255    * necessary
256    * 
257    * @param start
258    *          start sequence
259    * @param end
260    *          end sequence
261    * @return array containing old start and end sequence values
262    */
263   private int[] updateStartEndSeq(int start, int end)
264   {
265     int oldstartseq = this.startSeq;
266     int visibleHeight = getVisibleAlignmentHeight();
267     if (start > visibleHeight - 1)
268     {
269       startSeq = Math.max(visibleHeight - 1, 0);
270     }
271     else if (start < 0)
272     {
273       startSeq = 0;
274     }
275     else
276     {
277       startSeq = start;
278     }
279
280     int oldendseq = this.endSeq;
281     if (end >= visibleHeight)
282     {
283       endSeq = Math.max(visibleHeight - 1, 0);
284     }
285     else if (end < 0)
286     {
287       endSeq = 0;
288     }
289     else
290     {
291       endSeq = end;
292     }
293     return new int[] { oldstartseq, oldendseq };
294   }
295
296   /**
297    * Set the last sequence visible in the viewport. Fires a property change
298    * event.
299    * 
300    * @param seq
301    *          sequence position in the range [0, height)
302    */
303   public void setEndSeq(int seq)
304   {
305     // BH 2018.04.18 added safety for seq < 0; comment about not being >= height
306     setStartEndSeq(Math.max(0, seq + 1 - getViewportHeight()), seq);
307   }
308
309   /**
310    * Set start residue and start sequence together (fires single event). The
311    * event supplies a pair of old values and a pair of new values: [old start
312    * residue, old start sequence] and [new start residue, new start sequence]
313    * 
314    * @param res
315    *          the start residue
316    * @param seq
317    *          the start sequence
318    */
319   public void setStartResAndSeq(int res, int seq)
320   {
321     int width = getViewportWidth();
322     int[] oldresvalues = updateStartEndRes(res, res + width - 1);
323
324     int startseq = seq;
325     int height = getViewportHeight();
326     if (startseq + height - 1 > getVisibleAlignmentHeight() - 1)
327     {
328       startseq = getVisibleAlignmentHeight() - height;
329     }
330     int[] oldseqvalues = updateStartEndSeq(startseq, startseq + height - 1);
331
332     int[] old = new int[] { oldresvalues[0], oldseqvalues[0] };
333     int[] newresseq = new int[] { startRes, startSeq };
334     changeSupport.firePropertyChange(STARTRESANDSEQ, old, newresseq);
335   }
336
337   /**
338    * Get start residue of viewport
339    */
340   public int getStartRes()
341   {
342     return startRes;
343   }
344
345   /**
346    * Get end residue of viewport
347    */
348   public int getEndRes()
349   {
350     return endRes;
351   }
352
353   /**
354    * Get start sequence of viewport
355    */
356   public int getStartSeq()
357   {
358     return startSeq;
359   }
360
361   /**
362    * Get end sequence of viewport
363    */
364   public int getEndSeq()
365   {
366     return endSeq;
367   }
368
369   /**
370    * Set viewport width in residues, without changing startRes. Use in
371    * preference to calculating endRes from the width, to avoid out by one
372    * errors! Fires a property change event.
373    * 
374    * @param w
375    *          width in residues
376    */
377   public void setViewportWidth(int w)
378   {
379     setStartEndRes(startRes, startRes + w - 1);
380   }
381
382   /**
383    * Set viewport height in residues, without changing startSeq. Use in
384    * preference to calculating endSeq from the height, to avoid out by one
385    * errors! Fires a property change event.
386    * 
387    * @param h
388    *          height in sequences
389    */
390   public void setViewportHeight(int h)
391   {
392     setStartEndSeq(startSeq, startSeq + h - 1);
393   }
394
395   /**
396    * Set viewport horizontal start position and width. Use in preference to
397    * calculating endRes from the width, to avoid out by one errors! Fires a
398    * property change event.
399    * 
400    * @param start
401    *          start residue
402    * @param w
403    *          width in residues
404    */
405   public void setViewportStartAndWidth(int start, int w)
406   {
407     int vpstart = start;
408     if (vpstart < 0)
409     {
410       vpstart = 0;
411     }
412
413     /*
414      * if not wrapped, don't leave white space at the right margin
415      */
416     if (!wrappedMode)
417     {
418       if ((w <= getVisibleAlignmentWidth())
419               && (vpstart + w - 1 > getVisibleAlignmentWidth() - 1))
420       {
421         vpstart = getVisibleAlignmentWidth() - w;
422       }
423
424     }
425     setStartEndRes(vpstart, vpstart + w - 1);
426   }
427
428   /**
429    * Set viewport vertical start position and height. Use in preference to
430    * calculating endSeq from the height, to avoid out by one errors! Fires a
431    * property change event.
432    * 
433    * @param start
434    *          start sequence
435    * @param h
436    *          height in sequences
437    */
438   public void setViewportStartAndHeight(int start, int h)
439   {
440     int vpstart = start;
441
442     int visHeight = getVisibleAlignmentHeight();
443     if (vpstart < 0)
444     {
445       vpstart = 0;
446     }
447     else if (h <= visHeight && vpstart + h > visHeight)
448     // viewport height is less than the full alignment and we are running off
449     // the bottom
450     {
451       vpstart = visHeight - h;
452     }
453     // System.out.println("ViewportRanges setviewportStartAndHeight " + vpstart
454     // + " " + start + " " + h + " " + getVisibleAlignmentHeight());
455
456     setStartEndSeq(vpstart, vpstart + h - 1);
457   }
458
459   /**
460    * Get width of viewport in residues
461    * 
462    * @return width of viewport
463    */
464   public int getViewportWidth()
465   {
466     return (endRes - startRes + 1);
467   }
468
469   /**
470    * Get height of viewport in residues
471    * 
472    * @return height of viewport
473    */
474   public int getViewportHeight()
475   {
476     return (endSeq - startSeq + 1);
477   }
478
479   /**
480    * Scroll the viewport range vertically. Fires a property change event.
481    * 
482    * @param up
483    *          true if scrolling up, false if down
484    * 
485    * @return true if the scroll is valid
486    */
487   public boolean scrollUp(boolean up)
488   {
489     /*
490      * if in unwrapped mode, scroll up or down one sequence row;
491      * if in wrapped mode, scroll by one visible width of columns
492      */
493     if (up)
494     {
495       if (wrappedMode)
496       {
497         pageUp();
498       }
499       else
500       {
501         if (startSeq < 1)
502         {
503           return false;
504         }
505         setStartSeq(startSeq - 1);
506       }
507     }
508     else
509     {
510       if (wrappedMode)
511       {
512         pageDown();
513       }
514       else
515       {
516         if (endSeq >= getVisibleAlignmentHeight() - 1)
517         {
518           return false;
519         }
520         setStartSeq(startSeq + 1);
521       }
522     }
523     return true;
524   }
525
526   /**
527    * Scroll the viewport range horizontally. Fires a property change event.
528    * 
529    * @param right
530    *          true if scrolling right, false if left
531    * 
532    * @return true if the scroll is valid
533    */
534   public boolean scrollRight(boolean right)
535   {
536     if (!right)
537     {
538       if (startRes < 1)
539       {
540         return false;
541       }
542
543       setStartRes(startRes - 1);
544     }
545     else
546     {
547       if (endRes >= getVisibleAlignmentWidth() - 1)
548       {
549         return false;
550       }
551
552       setStartRes(startRes + 1);
553     }
554
555     return true;
556   }
557
558   /**
559    * Scroll a wrapped alignment so that the specified residue is in the first
560    * repeat of the wrapped view. Fires a property change event. Answers true if
561    * the startRes changed, else false.
562    * 
563    * @param res
564    *          residue position to scroll to NB visible position not absolute
565    *          alignment position
566    * @return
567    */
568   public boolean scrollToWrappedVisible(int res)
569   {
570     int newStartRes = calcWrappedStartResidue(res);
571     if (newStartRes == startRes)
572     {
573       return false;
574     }
575     setStartRes(newStartRes);
576
577     return true;
578   }
579
580   /**
581    * Calculate wrapped start residue from visible start residue
582    * 
583    * @param res
584    *          visible start residue
585    * @return left column of panel res will be located in
586    */
587   private int calcWrappedStartResidue(int res)
588   {
589     int oldStartRes = startRes;
590     int width = getViewportWidth();
591
592     boolean up = res < oldStartRes;
593     int widthsToScroll = Math.abs((res - oldStartRes) / width);
594     if (up)
595     {
596       widthsToScroll++;
597     }
598
599     int residuesToScroll = width * widthsToScroll;
600     int newStartRes = up ? oldStartRes - residuesToScroll : oldStartRes
601             + residuesToScroll;
602     if (newStartRes < 0)
603     {
604       newStartRes = 0;
605     }
606     return newStartRes;
607   }
608
609   /**
610    * Scroll so that (x,y) is visible. Fires a property change event.
611    * 
612    * @param x
613    *          x position in alignment (absolute position)
614    * @param y
615    *          y position in alignment (absolute position)
616    */
617   public void scrollToVisible(int x, int y)
618   {
619     while (y < startSeq)
620     {
621       scrollUp(true);
622     }
623     while (y > endSeq)
624     {
625       scrollUp(false);
626     }
627     
628     HiddenColumns hidden = al.getHiddenColumns();
629     while (x < hidden.visibleToAbsoluteColumn(startRes))
630     {
631       if (!scrollRight(false))
632       {
633         break;
634       }
635     }
636     while (x > hidden.visibleToAbsoluteColumn(endRes))
637     {
638       if (!scrollRight(true))
639       {
640         break;
641       }
642     }
643   }
644
645   /**
646    * Set the viewport location so that a position is visible
647    * 
648    * @param x
649    *          column to be visible: absolute position in alignment
650    * @param y
651    *          row to be visible: absolute position in alignment
652    */
653   public boolean setViewportLocation(int x, int y)
654   {
655     boolean changedLocation = false;
656
657     // convert the x,y location to visible coordinates
658     int visX = al.getHiddenColumns().absoluteToVisibleColumn(x);
659     int visY = al.getHiddenSequences().findIndexWithoutHiddenSeqs(y);
660
661     // if (vis_x,vis_y) is already visible don't do anything
662     if (startRes > visX || visX > endRes
663             || startSeq > visY && visY > endSeq)
664     {
665       int[] old = new int[] { startRes, startSeq };
666       int[] newresseq;
667       if (wrappedMode)
668       {
669         int newstartres = calcWrappedStartResidue(visX);
670         setStartRes(newstartres);
671         newresseq = new int[] { startRes, startSeq };
672       }
673       else
674       {
675         // set the viewport x location to contain vis_x
676         int newstartres = visX;
677         int width = getViewportWidth();
678         if (newstartres + width - 1 > getVisibleAlignmentWidth() - 1)
679         {
680           newstartres = getVisibleAlignmentWidth() - width;
681         }
682         updateStartEndRes(newstartres, newstartres + width - 1);
683
684         // set the viewport y location to contain vis_y
685         int newstartseq = visY;
686         int height = getViewportHeight();
687         if (newstartseq + height - 1 > getVisibleAlignmentHeight() - 1)
688         {
689           newstartseq = getVisibleAlignmentHeight() - height;
690         }
691         updateStartEndSeq(newstartseq, newstartseq + height - 1);
692
693         newresseq = new int[] { startRes, startSeq };
694       }
695       changedLocation = true;
696       changeSupport.firePropertyChange(MOVE_VIEWPORT, old, newresseq);
697     }
698     return changedLocation;
699   }
700
701   /**
702    * Adjust sequence position for page up. Fires a property change event.
703    */
704   public void pageUp()
705   {
706     if (wrappedMode)
707     {
708       setStartRes(Math.max(0, getStartRes() - getViewportWidth()));
709     }
710     else
711     {
712       setViewportStartAndHeight(startSeq - (endSeq - startSeq),
713               getViewportHeight());
714     }
715   }
716
717   /**
718    * Adjust sequence position for page down. Fires a property change event.
719    */
720   public void pageDown()
721   {
722     if (wrappedMode)
723     {
724       /*
725        * if height is more than width (i.e. not all sequences fit on screen),
726        * increase page down to height
727        */
728       int newStart = getStartRes()
729               + Math.max(getViewportHeight(), getViewportWidth());
730
731       /*
732        * don't page down beyond end of alignment, or if not all
733        * sequences fit in the visible height
734        */
735       if (newStart < getVisibleAlignmentWidth())
736       {
737         setStartRes(newStart);
738       }
739     }
740     else
741     {
742       setViewportStartAndHeight(endSeq, getViewportHeight());
743     }
744   }
745
746   public void setWrappedMode(boolean wrapped)
747   {
748     wrappedMode = wrapped;
749   }
750
751   public boolean isWrappedMode()
752   {
753     return wrappedMode;
754   }
755
756   /**
757    * Answers the vertical scroll position (0..) to set, given the visible column
758    * that is at top left.
759    * 
760    * <pre>
761    * Example:
762    *    viewport width 40 columns (0-39, 40-79, 80-119...)
763    *    column 0 returns scroll position 0
764    *    columns 1-40 return scroll position 1
765    *    columns 41-80 return scroll position 2
766    *    etc
767    * </pre>
768    * 
769    * @param topLeftColumn
770    *          (0..)
771    * @return
772    */
773   public int getWrappedScrollPosition(final int topLeftColumn)
774   {
775     int w = getViewportWidth();
776
777     /*
778      * visible whole widths
779      */
780     int scroll = topLeftColumn / w;
781
782     /*
783      * add 1 for a part width if there is one
784      */
785     scroll += topLeftColumn % w > 0 ? 1 : 0;
786
787     return scroll;
788   }
789
790   /**
791    * Answers the maximum wrapped vertical scroll value, given the column
792    * position (0..) to show at top left of the visible region.
793    * 
794    * @param topLeftColumn
795    * @return
796    */
797   public int getWrappedMaxScroll(int topLeftColumn)
798   {
799     int scrollPosition = getWrappedScrollPosition(topLeftColumn);
800
801     /*
802      * how many more widths could be drawn after this one?
803      */
804     int columnsRemaining = getVisibleAlignmentWidth() - topLeftColumn;
805     int width = getViewportWidth();
806     int widthsRemaining = columnsRemaining / width
807             + (columnsRemaining % width > 0 ? 1 : 0) - 1;
808     int maxScroll = scrollPosition + widthsRemaining;
809
810     return maxScroll;
811   }
812   
813
814   @Override
815   public String toString() {
816      return "[ViewportRange " + startSeq + "-" + endSeq + ", "+ startRes + "-" + endRes + "]";
817   }
818 }