View Javadoc

1   /*
2    * Copyright 2007 Google Inc.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at
7    * 
8    * http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  package com.google.gwt.widgetideas.client;
17  
18  import java.util.Iterator;
19  
20  import com.google.gwt.core.client.GWT;
21  import com.google.gwt.user.client.DOM;
22  import com.google.gwt.user.client.Element;
23  import com.google.gwt.user.client.Event;
24  import com.google.gwt.user.client.ui.AbstractImagePrototype;
25  import com.google.gwt.user.client.ui.ImageBundle;
26  import com.google.gwt.user.client.ui.KeyboardListener;
27  
28  /**
29   * A widget that allows the user to select a value within a range of possible
30   * values using a sliding bar that responds to mouse events.
31   * 
32   * <h3>Keyboard Events</h3>
33   * <p>
34   * VSliderBar listens for the following key events. Holding down a key will
35   * repeat the action until the key is released.
36   * <ul class='css'>
37   * <li>left arrow - shift left one step</li>
38   * <li>right arrow - shift right one step</li>
39   * <li>ctrl+left arrow - jump left 10% of the distance</li>
40   * <li>ctrl+right arrow - jump right 10% of the distance</li>
41   * <li>home - jump to min value</li>
42   * <li>end - jump to max value</li>
43   * <li>space - jump to middle value</li>
44   * </ul>
45   * </p>
46   * 
47   * <h3>CSS Style Rules</h3>
48   * <ul class='css'>
49   * <li>.gwt-VSliderBar-shell { primary style } </li>
50   * <li>.gwt-VSliderBar-shell-focused { primary style when focused } </li>
51   * <li>.gwt-VSliderBar-shell gwt-VSliderBar-line { the line that the knob moves
52   * along } </li>
53   * <li>.gwt-VSliderBar-shell gwt-VSliderBar-line-sliding { the line that the knob
54   * moves along when sliding } </li>
55   * <li>.gwt-VSliderBar-shell .gwt-VSliderBar-knob { the sliding knob } </li>
56   * <li>.gwt-VSliderBar-shell .gwt-VSliderBar-knob-sliding { the sliding knob when
57   * sliding } </li>
58   * <li>.gwt-VSliderBar-shell .gwt-VSliderBar-tick { the ticks along the line }
59   * </li>
60   * <li>.gwt-VSliderBar-shell .gwt-VSliderBar-label { the text labels along the
61   * line } </li>
62   * </ul>
63   */
64  public class VSliderBar extends SliderBar {
65    /**
66     * An {@link ImageBundle} that provides images for {@link VSliderBar}.
67     */
68    static interface VSliderBarImages extends ImageBundle {
69      /**
70       * An image used for the sliding knob.
71       * 
72       * @return a prototype of this image
73       */
74      AbstractImagePrototype vslider();
75  
76      /**
77       * An image used for the sliding knob while sliding.
78       * 
79       * @return a prototype of this image
80       */
81      AbstractImagePrototype vsliderSliding();
82    }
83    
84    /**
85     * Create a slider bar.
86     * 
87     * @param minValue the minimum value in the range
88     * @param maxValue the maximum value in the range
89     */
90    public VSliderBar(double minValue, double maxValue) {
91      this(minValue, maxValue, null);
92    }
93  
94    /**
95     * Create a slider bar.
96     * 
97     * @param minValue the minimum value in the range
98     * @param maxValue the maximum value in the range
99     * @param labelFormatter the label formatter
100    */
101   public VSliderBar(double minValue, double maxValue,
102       LabelFormatter labelFormatter) {
103     this(minValue, maxValue, labelFormatter,
104         null);
105   }
106 
107   /**
108    * Create a slider bar.
109    * 
110    * @param minValue the minimum value in the range
111    * @param maxValue the maximum value in the range
112    * @param labelFormatter the label formatter
113    * @param images the images to use for the slider
114    */
115   public VSliderBar(double minValue, double maxValue,
116       LabelFormatter labelFormatter, AbstractImagePrototype[] images) {
117 	    this(minValue, maxValue, labelFormatter,
118 	            images, "gwt-VSliderBar");
119   }
120   
121   /**
122    * Create a slider bar.
123    * 
124    * @param minValue the minimum value in the range
125    * @param maxValue the maximum value in the range
126    * @param labelFormatter the label formatter
127    * @param images the images to use for the slider
128    * @param styleBaseName the base name from which CSS style
129    * names for the slider are derived
130    */
131   public VSliderBar(double minValue, double maxValue,
132       LabelFormatter labelFormatter, AbstractImagePrototype[] images, String styleBaseName) {
133     super();
134     this.minValue = minValue;
135     this.maxValue = maxValue;
136     if (images != null) {
137       this.images = images;
138     } else {
139       this.images = new AbstractImagePrototype[2];
140       VSliderBarImages defaultImages = (VSliderBarImages) GWT.create(VSliderBarImages.class);
141       this.images[0] = defaultImages.vslider();
142       this.images[1] = defaultImages.vsliderSliding();
143     }
144     this.styleBaseName = styleBaseName;
145     setLabelFormatter(labelFormatter);
146 
147     // Create the outer shell
148     DOM.setStyleAttribute(getElement(), "position", "relative");
149     setStyleName(styleBaseName + "-shell");
150 
151     // Create the line
152     lineElement = DOM.createDiv();
153     DOM.appendChild(getElement(), lineElement);
154     DOM.setStyleAttribute(lineElement, "position", "absolute");
155     DOM.setElementProperty(lineElement, "className", styleBaseName + "-line");
156 
157     // Create the knob
158     this.images[0].applyTo(knobImage);
159     Element knobElement = knobImage.getElement();
160     DOM.appendChild(getElement(), knobElement);
161     DOM.setStyleAttribute(knobElement, "position", "absolute");
162     DOM.setElementProperty(knobElement, "className", styleBaseName + "-knob");
163 
164     // Make this a resizable widget
165     ResizableWidgetCollection.get().add(this);
166   }
167 
168   /**
169    * Listen for events that will move the knob.
170    * 
171    * @param event the event that occurred
172    */
173   public void onBrowserEvent(Event event) {
174     super.onBrowserEvent(event);
175     switch (DOM.eventGetType(event)) {
176       // Unhighlight and cancel keyboard events
177       case Event.ONBLUR:
178         keyTimer.cancel();
179         if (slidingMouse) {
180           DOM.releaseCapture(getElement());
181           slidingMouse = false;
182           slideKnob(event);
183           stopSliding(true, true);
184         } else if (slidingKeyboard) {
185           slidingKeyboard = false;
186           stopSliding(true, true);
187         }
188         unhighlight();
189         break;
190 
191       // Highlight on focus
192       case Event.ONFOCUS:
193         highlight();
194         break;
195 
196       // Mousewheel events
197       case Event.ONMOUSEWHEEL:
198         int velocityY = DOM.eventGetMouseWheelVelocityY(event);
199         DOM.eventPreventDefault(event);
200         if (velocityY > 0) {
201           shiftBottom(1);
202         } else {
203           shiftTop(1);
204         }
205         break;
206 
207       // Shift left or right on key press
208       case Event.ONKEYDOWN:
209         if (!slidingKeyboard) {
210           int multiplier = 1;
211           if (DOM.eventGetCtrlKey(event)) {
212             multiplier = (int) (getTotalRange() / stepSize / 10);
213           }
214 
215           switch (DOM.eventGetKeyCode(event)) {
216             case KeyboardListener.KEY_HOME:
217               DOM.eventPreventDefault(event);
218               setCurrentValue(minValue);
219               break;
220             case KeyboardListener.KEY_END:
221               DOM.eventPreventDefault(event);
222               setCurrentValue(maxValue);
223               break;
224             case KeyboardListener.KEY_UP:
225               DOM.eventPreventDefault(event);
226               slidingKeyboard = true;
227               startSliding(false, true);
228               shiftTop(multiplier);
229               keyTimer.schedule(400, false, multiplier);
230               break;
231             case KeyboardListener.KEY_DOWN:
232               DOM.eventPreventDefault(event);
233               slidingKeyboard = true;
234               startSliding(false, true);
235               shiftBottom(multiplier);
236               keyTimer.schedule(400, true, multiplier);
237               break;
238             case 32:
239               DOM.eventPreventDefault(event);
240               setCurrentValue(minValue + getTotalRange() / 2);
241               break;
242           }
243         }
244         break;
245       // Stop shifting on key up
246       case Event.ONKEYUP:
247         keyTimer.cancel();
248         if (slidingKeyboard) {
249           slidingKeyboard = false;
250           stopSliding(true, true);
251         }
252         break;
253 
254       // Mouse Events
255       case Event.ONMOUSEDOWN:
256         setFocus(true);
257         slidingMouse = true;
258         DOM.setCapture(getElement());
259         startSliding(true, true);
260         DOM.eventPreventDefault(event);
261         slideKnob(event);
262         break;
263       case Event.ONMOUSEUP:
264         if (slidingMouse) {
265           DOM.releaseCapture(getElement());
266           slidingMouse = false;
267           slideKnob(event);
268           stopSliding(true, true);
269         }
270         break;
271       case Event.ONMOUSEMOVE:
272         if (slidingMouse) {
273           slideKnob(event);
274         }
275         break;
276     }
277   }
278 
279   /**
280    * This method is called when the dimensions of the parent element change.
281    * Subclasses should override this method as needed.
282    * 
283    * @param width the new client width of the element
284    * @param height the new client height of the element
285    */
286   public void onResize(int width, int height) {
287     // Center the line in the shell
288     int lineHeight = DOM.getElementPropertyInt(lineElement, "offsetHeight");
289     lineOffset = (height / 2) - (lineHeight / 2);
290     DOM.setStyleAttribute(lineElement, "top", lineOffset + "px");
291 
292     // Draw the other components
293     drawLabels();
294     drawTicks();
295     drawKnob();
296   }
297 
298    /**
299    * Shift to the left (smaller value).
300    * 
301    * @param numSteps the number of steps to shift
302    */
303   public void shiftTop(int numSteps) {
304     setCurrentValue(getCurrentValue() - numSteps * stepSize);
305   }
306 
307   /**
308    * Shift to the right (greater value).
309    * 
310    * @param numSteps the number of steps to shift
311    */
312   public void shiftBottom(int numSteps) {
313     setCurrentValue(getCurrentValue() + numSteps * stepSize);
314   }
315 
316   /**
317    * Draw the knob where it is supposed to be relative to the line.
318    */
319   protected void drawKnob() {
320     // Abort if not attached
321     if (!isAttached()) {
322       return;
323     }
324 
325     // Move the knob to the correct position
326     Element knobElement = knobImage.getElement();
327     int lineHeight = DOM.getElementPropertyInt(lineElement, "offsetHeight");
328     int knobHeight = DOM.getElementPropertyInt(knobElement, "offsetHeight");
329     int knobTopOffset = (int) (lineOffset + (getKnobPercent() * lineHeight) - (knobHeight / 2));
330     knobTopOffset = Math.min(knobTopOffset, lineOffset + lineHeight
331         - (knobHeight / 2) - 1);
332     DOM.setStyleAttribute(knobElement, "top", knobTopOffset + "px");
333   }
334 
335   /**
336    * Draw the labels along the line.
337    */
338   protected void drawLabels() {
339     // Abort if not attached
340     if (!isAttached()) {
341       return;
342     }
343 
344     // Draw the labels
345     int lineHeight = DOM.getElementPropertyInt(lineElement, "offsetHeight");
346     if (numLabels > 0) {
347       // Create the labels or make them visible
348       for (int i = 0; i <= numLabels; i++) {
349         Element label = null;
350         if (i < labelElements.size()) {
351           label = (Element) labelElements.get(i);
352         } else { // Create the new label
353           label = DOM.createDiv();
354           DOM.setStyleAttribute(label, "position", "absolute");
355           DOM.setStyleAttribute(label, "display", "none");
356           DOM.setElementProperty(label, "className", styleBaseName + "-label");
357           DOM.appendChild(getElement(), label);
358           labelElements.add(label);
359         }
360 
361         // Set the label text
362         double value = minValue + (getTotalRange() * i / numLabels);
363         DOM.setStyleAttribute(label, "visibility", "hidden");
364         DOM.setStyleAttribute(label, "display", "");
365         DOM.setElementProperty(label, "innerHTML", formatLabel(value));
366 
367         // Move to the left so the label width is not clipped by the shell
368         DOM.setStyleAttribute(label, "top", "0px");
369 
370         // Position the label and make it visible
371         int labelHeight = DOM.getElementPropertyInt(label, "offsetHeight");
372         int labelTopOffset = lineOffset + (lineHeight * i / numLabels)
373             - (labelHeight / 2);
374         labelTopOffset = Math.min(labelTopOffset, lineOffset + lineHeight
375             - labelHeight);
376         labelTopOffset = Math.max(labelTopOffset, lineOffset);
377         DOM.setStyleAttribute(label, "top", labelTopOffset + "px");
378         DOM.setStyleAttribute(label, "visibility", "visible");
379       }
380 
381       // Hide unused labels
382       for (int i = (numLabels + 1); i < labelElements.size(); i++) {
383         DOM.setStyleAttribute((Element) labelElements.get(i), "display", "none");
384       }
385     } else { // Hide all labels
386       Iterator it = labelElements.iterator();
387       while (it.hasNext()) {
388         DOM.setStyleAttribute((Element) it.next(), "display", "none");
389       }
390     }
391   }
392 
393   /**
394    * Draw the tick along the line.
395    */
396   protected void drawTicks() {
397     // Abort if not attached
398     if (!isAttached()) {
399       return;
400     }
401 
402     // Draw the ticks
403     int lineHeight = DOM.getElementPropertyInt(lineElement, "offsetHeight");
404     if (numTicks > 0) {
405       // Create the ticks or make them visible
406       for (int i = 0; i <= numTicks; i++) {
407         Element tick = null;
408         if (i < tickElements.size()) {
409           tick = (Element) tickElements.get(i);
410         } else { // Create the new tick
411           tick = DOM.createDiv();
412           DOM.setStyleAttribute(tick, "position", "absolute");
413           DOM.setStyleAttribute(tick, "display", "none");
414           DOM.setElementProperty(tick, "className", styleBaseName + "-tick");
415           DOM.appendChild(getElement(), tick);
416           tickElements.add(tick);
417         }
418 
419         // Position the tick and make it visible
420         DOM.setStyleAttribute(tick, "visibility", "hidden");
421         DOM.setStyleAttribute(tick, "display", "");
422         int tickHeight = DOM.getElementPropertyInt(tick, "offsetHeight");
423         int tickTopOffset = lineOffset + (lineHeight * i / numTicks)
424             - (tickHeight / 2);
425         tickTopOffset = Math.min(tickTopOffset, lineOffset + lineHeight
426             - tickHeight);
427         DOM.setStyleAttribute(tick, "top", tickTopOffset + "px");
428         DOM.setStyleAttribute(tick, "visibility", "visible");
429       }
430 
431       // Hide unused ticks
432       for (int i = (numTicks + 1); i < tickElements.size(); i++) {
433         DOM.setStyleAttribute((Element) tickElements.get(i), "display", "none");
434       }
435     } else { // Hide all ticks
436       Iterator it = tickElements.iterator();
437       while (it.hasNext()) {
438         DOM.setStyleAttribute((Element) it.next(), "display", "none");
439       }
440     }
441   }
442 
443   /**
444    * Slide the knob to a new location.
445    * 
446    * @param event the mouse event
447    */
448   private void slideKnob(Event event) {
449     int y = DOM.eventGetClientY(event);
450     if (y > 0) {
451       int lineHeight = DOM.getElementPropertyInt(lineElement, "offsetHeight");
452       int lineTop = getAbsoluteTop2(lineElement);
453       //int lineTop = DOM.getAbsoluteTop(lineElement);
454       double percent = (double) (y - lineTop) / lineHeight * 1.0;
455       setCurrentValue(getTotalRange() * percent + minValue, true);
456     }
457   }
458   
459   private native int getAbsoluteTop2(Element elem) /*-{
460     var top = 0;
461     var curr = elem;
462     // This intentionally excludes body which has a null offsetParent.    
463     while (curr) {
464       top -= curr.scrollTop;
465       curr = curr.offsetParent;
466     }
467     while (elem) {
468       top += elem.offsetTop;
469       elem = elem.offsetParent;
470     }
471     return top;
472   }-*/;
473 
474   /**
475    * Start sliding the knob.
476    * 
477    * @param highlight true to change the style
478    * @param fireEvent true to fire the event
479    */
480   protected void startSliding(boolean highlight, boolean fireEvent) {
481     if (highlight) {
482       DOM.setElementProperty(lineElement, "className",
483         styleBaseName + "-line " + styleBaseName + "-line-sliding");
484       DOM.setElementProperty(knobImage.getElement(), "className",
485     	styleBaseName + "-knob " + styleBaseName + "-knob-sliding");
486       images[1].applyTo(knobImage);
487     }
488     if (fireEvent && (sliderListeners != null)) {
489       sliderListeners.fireStartSliding(this);
490     }
491   }
492 
493   /**
494    * Stop sliding the knob.
495    * 
496    * @param unhighlight true to change the style
497    * @param fireEvent true to fire the event
498    */
499   protected void stopSliding(boolean unhighlight, boolean fireEvent) {
500     if (unhighlight) {
501       DOM.setElementProperty(lineElement, "className", styleBaseName + "-line");
502 
503       DOM.setElementProperty(knobImage.getElement(), "className",
504     		  styleBaseName + "-knob");
505       images[0].applyTo(knobImage);
506     }
507     if (fireEvent && (sliderListeners != null)) {
508       sliderListeners.fireStopSliding(this);
509     }
510   }
511 }