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   * HSliderBar 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-HSliderBar-shell { primary style } </li>
50   * <li>.gwt-HSliderBar-shell-focused { primary style when focused } </li>
51   * <li>.gwt-HSliderBar-shell gwt-HSliderBar-line { the line that the knob moves
52   * along } </li>
53   * <li>.gwt-HSliderBar-shell gwt-HSliderBar-line-sliding { the line that the knob
54   * moves along when sliding } </li>
55   * <li>.gwt-HSliderBar-shell .gwt-HSliderBar-knob { the sliding knob } </li>
56   * <li>.gwt-HSliderBar-shell .gwt-HSliderBar-knob-sliding { the sliding knob when
57   * sliding } </li>
58   * <li>.gwt-HSliderBar-shell .gwt-HSliderBar-tick { the ticks along the line }
59   * </li>
60   * <li>.gwt-HSliderBar-shell .gwt-HSliderBar-label { the text labels along the
61   * line } </li>
62   * </ul>
63   */
64  public class HSliderBar extends SliderBar {
65    /**
66     * An {@link ImageBundle} that provides images for {@link HSliderBar}.
67     */
68    static interface HSliderBarImages extends ImageBundle {
69      /**
70       * An image used for the sliding knob.
71       * 
72       * @return a prototype of this image
73       */
74      AbstractImagePrototype hslider();
75  
76      /**
77       * An image used for the sliding knob while sliding.
78       * 
79       * @return a prototype of this image
80       */
81      AbstractImagePrototype hsliderSliding();
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 HSliderBar(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 HSliderBar(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 HSliderBar(double minValue, double maxValue,
116       LabelFormatter labelFormatter, AbstractImagePrototype[] images) {
117 	  this(minValue, maxValue, labelFormatter,
118 	            images, "gwt-HSliderBar");
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 HSliderBar(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       HSliderBarImages defaultImages = (HSliderBarImages) GWT.create(HSliderBarImages.class);
141       this.images[0] = defaultImages.hslider();
142       this.images[1] = defaultImages.hsliderSliding();
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   /**
170    * Listen for events that will move the knob.
171    * 
172    * @param event the event that occurred
173    */
174   public void onBrowserEvent(Event event) {
175     super.onBrowserEvent(event);
176     switch (DOM.eventGetType(event)) {
177       // Unhighlight and cancel keyboard events
178       case Event.ONBLUR:
179         keyTimer.cancel();
180         if (slidingMouse) {
181           DOM.releaseCapture(getElement());
182           slidingMouse = false;
183           slideKnob(event);
184           stopSliding(true, true);
185         } else if (slidingKeyboard) {
186           slidingKeyboard = false;
187           stopSliding(true, true);
188         }
189         unhighlight();
190         break;
191 
192       // Highlight on focus
193       case Event.ONFOCUS:
194         highlight();
195         break;
196 
197       // Mousewheel events
198       case Event.ONMOUSEWHEEL:
199         int velocityY = DOM.eventGetMouseWheelVelocityY(event);
200         DOM.eventPreventDefault(event);
201         if (velocityY > 0) {
202           shiftRight(1);
203         } else {
204           shiftLeft(1);
205         }
206         break;
207 
208       // Shift left or right on key press
209       case Event.ONKEYDOWN:
210         if (!slidingKeyboard) {
211           int multiplier = 1;
212           if (DOM.eventGetCtrlKey(event)) {
213             multiplier = (int) (getTotalRange() / stepSize / 10);
214           }
215 
216           switch (DOM.eventGetKeyCode(event)) {
217             case KeyboardListener.KEY_HOME:
218               DOM.eventPreventDefault(event);
219               setCurrentValue(minValue);
220               break;
221             case KeyboardListener.KEY_END:
222               DOM.eventPreventDefault(event);
223               setCurrentValue(maxValue);
224               break;
225             case KeyboardListener.KEY_LEFT:
226               DOM.eventPreventDefault(event);
227               slidingKeyboard = true;
228               startSliding(false, true);
229               shiftLeft(multiplier);
230               keyTimer.schedule(400, false, multiplier);
231               break;
232             case KeyboardListener.KEY_RIGHT:
233               DOM.eventPreventDefault(event);
234               slidingKeyboard = true;
235               startSliding(false, true);
236               shiftRight(multiplier);
237               keyTimer.schedule(400, true, multiplier);
238               break;
239             case 32:
240               DOM.eventPreventDefault(event);
241               setCurrentValue(minValue + getTotalRange() / 2);
242               break;
243           }
244         }
245         break;
246       // Stop shifting on key up
247       case Event.ONKEYUP:
248         keyTimer.cancel();
249         if (slidingKeyboard) {
250           slidingKeyboard = false;
251           stopSliding(true, true);
252         }
253         break;
254 
255       // Mouse Events
256       case Event.ONMOUSEDOWN:
257         setFocus(true);
258         slidingMouse = true;
259         DOM.setCapture(getElement());
260         startSliding(true, true);
261         DOM.eventPreventDefault(event);
262         slideKnob(event);
263         break;
264       case Event.ONMOUSEUP:
265         if (slidingMouse) {
266           DOM.releaseCapture(getElement());
267           slidingMouse = false;
268           slideKnob(event);
269           stopSliding(true, true);
270         }
271         break;
272       case Event.ONMOUSEMOVE:
273         if (slidingMouse) {
274           slideKnob(event);
275         }
276         break;
277     }
278   }
279 
280   /**
281    * This method is called when the dimensions of the parent element change.
282    * Subclasses should override this method as needed.
283    * 
284    * @param width the new client width of the element
285    * @param height the new client height of the element
286    */
287   public void onResize(int width, int height) {
288     // Center the line in the shell
289     int lineWidth = DOM.getElementPropertyInt(lineElement, "offsetWidth");
290     lineOffset = (width / 2) - (lineWidth / 2);
291     DOM.setStyleAttribute(lineElement, "left", lineOffset + "px");
292 
293     // Draw the other components
294     drawLabels();
295     drawTicks();
296     drawKnob();
297   }
298 
299   /**
300    * Shift to the left (smaller value).
301    * 
302    * @param numSteps the number of steps to shift
303    */
304   public void shiftLeft(int numSteps) {
305     setCurrentValue(getCurrentValue() - numSteps * stepSize);
306   }
307 
308   /**
309    * Shift to the right (greater value).
310    * 
311    * @param numSteps the number of steps to shift
312    */
313   public void shiftRight(int numSteps) {
314     setCurrentValue(getCurrentValue() + numSteps * stepSize);
315   }
316 
317   /**
318    * Draw the knob where it is supposed to be relative to the line.
319    */
320   protected void drawKnob() {
321     // Abort if not attached
322     if (!isAttached()) {
323       return;
324     }
325 
326     // Move the knob to the correct position
327     Element knobElement = knobImage.getElement();
328     int lineWidth = DOM.getElementPropertyInt(lineElement, "offsetWidth");
329     int knobWidth = DOM.getElementPropertyInt(knobElement, "offsetWidth");
330     int knobLeftOffset = (int) (lineOffset + (getKnobPercent() * lineWidth) - (knobWidth / 2));
331     knobLeftOffset = Math.min(knobLeftOffset, lineOffset + lineWidth
332         - (knobWidth / 2) - 1);
333     DOM.setStyleAttribute(knobElement, "left", knobLeftOffset + "px");
334   }
335 
336   /**
337    * Draw the labels along the line.
338    */
339   protected void drawLabels() {
340     // Abort if not attached
341     if (!isAttached()) {
342       return;
343     }
344 
345     // Draw the labels
346     int lineWidth = DOM.getElementPropertyInt(lineElement, "offsetWidth");
347     if (numLabels > 0) {
348       // Create the labels or make them visible
349       for (int i = 0; i <= numLabels; i++) {
350         Element label = null;
351         if (i < labelElements.size()) {
352           label = (Element) labelElements.get(i);
353         } else { // Create the new label
354           label = DOM.createDiv();
355           DOM.setStyleAttribute(label, "position", "absolute");
356           DOM.setStyleAttribute(label, "display", "none");
357           DOM.setElementProperty(label, "className",  styleBaseName + "-label");
358           DOM.appendChild(getElement(), label);
359           labelElements.add(label);
360         }
361 
362         // Set the label text
363         double value = minValue + (getTotalRange() * i / numLabels);
364         DOM.setStyleAttribute(label, "visibility", "hidden");
365         DOM.setStyleAttribute(label, "display", "");
366         DOM.setElementProperty(label, "innerHTML", formatLabel(value));
367 
368         // Move to the left so the label width is not clipped by the shell
369         DOM.setStyleAttribute(label, "left", "0px");
370 
371         // Position the label and make it visible
372         int labelWidth = DOM.getElementPropertyInt(label, "offsetWidth");
373         int labelLeftOffset = lineOffset + (lineWidth * i / numLabels)
374             - (labelWidth / 2);
375         labelLeftOffset = Math.min(labelLeftOffset, lineOffset + lineWidth
376             - labelWidth);
377         labelLeftOffset = Math.max(labelLeftOffset, lineOffset);
378         DOM.setStyleAttribute(label, "left", labelLeftOffset + "px");
379         DOM.setStyleAttribute(label, "visibility", "visible");
380       }
381 
382       // Hide unused labels
383       for (int i = (numLabels + 1); i < labelElements.size(); i++) {
384         DOM.setStyleAttribute((Element) labelElements.get(i), "display", "none");
385       }
386     } else { // Hide all labels
387       Iterator it = labelElements.iterator();
388       while (it.hasNext()) {
389         DOM.setStyleAttribute((Element) it.next(), "display", "none");
390       }
391     }
392   }
393 
394   /**
395    * Draw the tick along the line.
396    */
397   protected void drawTicks() {
398     // Abort if not attached
399     if (!isAttached()) {
400       return;
401     }
402 
403     // Draw the ticks
404     int lineWidth = DOM.getElementPropertyInt(lineElement, "offsetWidth");
405     if (numTicks > 0) {
406       // Create the ticks or make them visible
407       for (int i = 0; i <= numTicks; i++) {
408         Element tick = null;
409         if (i < tickElements.size()) {
410           tick = (Element) tickElements.get(i);
411         } else { // Create the new tick
412           tick = DOM.createDiv();
413           DOM.setStyleAttribute(tick, "position", "absolute");
414           DOM.setStyleAttribute(tick, "display", "none");
415           DOM.setElementProperty(tick, "className",  styleBaseName + "-tick");
416           DOM.appendChild(getElement(), tick);
417           tickElements.add(tick);
418         }
419 
420         // Position the tick and make it visible
421         DOM.setStyleAttribute(tick, "visibility", "hidden");
422         DOM.setStyleAttribute(tick, "display", "");
423         int tickWidth = DOM.getElementPropertyInt(tick, "offsetWidth");
424         int tickLeftOffset = lineOffset + (lineWidth * i / numTicks)
425             - (tickWidth / 2);
426         tickLeftOffset = Math.min(tickLeftOffset, lineOffset + lineWidth
427             - tickWidth);
428         DOM.setStyleAttribute(tick, "left", tickLeftOffset + "px");
429         DOM.setStyleAttribute(tick, "visibility", "visible");
430       }
431 
432       // Hide unused ticks
433       for (int i = (numTicks + 1); i < tickElements.size(); i++) {
434         DOM.setStyleAttribute((Element) tickElements.get(i), "display", "none");
435       }
436     } else { // Hide all ticks
437       Iterator it = tickElements.iterator();
438       while (it.hasNext()) {
439         DOM.setStyleAttribute((Element) it.next(), "display", "none");
440       }
441     }
442   }
443 
444   /**
445    * Slide the knob to a new location.
446    * 
447    * @param event the mouse event
448    */
449   private void slideKnob(Event event) {
450     int x = DOM.eventGetClientX(event);
451     if (x > 0) {
452       int lineWidth = DOM.getElementPropertyInt(lineElement, "offsetWidth");
453       int lineLeft = DOM.getAbsoluteLeft(lineElement);
454       double percent = (double) (x - lineLeft) / lineWidth * 1.0;
455       setCurrentValue(getTotalRange() * percent + minValue, true);
456     }
457   }
458 
459   /**
460    * Start sliding the knob.
461    * 
462    * @param highlight true to change the style
463    * @param fireEvent true to fire the event
464    */
465   protected void startSliding(boolean highlight, boolean fireEvent) {
466     if (highlight) {
467       DOM.setElementProperty(lineElement, "className",
468     		  styleBaseName + "-line " + styleBaseName + "-line-sliding");
469       DOM.setElementProperty(knobImage.getElement(), "className",
470     		  styleBaseName + "-knob " + styleBaseName + "-knob-sliding");
471       images[1].applyTo(knobImage);
472     }
473     if (fireEvent && (sliderListeners != null)) {
474       sliderListeners.fireStartSliding(this);
475     }
476   }
477 
478   /**
479    * Stop sliding the knob.
480    * 
481    * @param unhighlight true to change the style
482    * @param fireEvent true to fire the event
483    */
484   protected void stopSliding(boolean unhighlight, boolean fireEvent) {
485     if (unhighlight) {
486       DOM.setElementProperty(lineElement, "className", styleBaseName + "-line");
487 
488       DOM.setElementProperty(knobImage.getElement(), "className",
489     		  styleBaseName + "-knob");
490       images[0].applyTo(knobImage);
491     }
492     if (fireEvent && (sliderListeners != null)) {
493       sliderListeners.fireStopSliding(this);
494     }
495   }
496 }