001 /*
002 * Copyright 2006 Mat Gessel <mat.gessel@gmail.com>
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005 * use this file except in compliance with the License. You may obtain a copy of
006 * the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013 * License for the specific language governing permissions and limitations under
014 * the License.
015 */
016 package asquare.gwt.tk.client.ui.behavior;
017
018 import asquare.gwt.tk.client.util.DomUtil;
019
020 import com.google.gwt.user.client.ui.Widget;
021
022 /**
023 * A DragGesture which positions a target widget when the source widget is
024 * dragged.
025 */
026 public class DragWidgetGesture implements DragGesture
027 {
028 private final Widget m_target;
029
030 private int m_startX, m_startY;
031 private int m_startLeft, m_startTop;
032
033 /**
034 * @param target the widget to be dragged
035 */
036 public DragWidgetGesture(Widget target)
037 {
038 m_target = target;
039 }
040
041 protected Widget getDragWidget()
042 {
043 return m_target;
044 }
045
046 /**
047 * A <em>template method</em> which sets the position of the target widget
048 * to the specified coordinates. Coordinates are in the document's
049 * coordinate space (i.e. absolute position).
050 *
051 * @param left the x coordinate in pixels
052 * @param top the y coordinate in pixels
053 */
054 protected void setTargetPosition(int left, int top)
055 {
056 DomUtil.setStyleAttribute(m_target, "position", "absolute");
057 DomUtil.setStyleAttribute(m_target, "left", left + "px");
058 DomUtil.setStyleAttribute(m_target, "top", top + "px");
059 }
060
061 // DragGesture methods
062 public void start(int x, int y)
063 {
064 // Debug.println("start(" + x + "," + y + ")");
065 m_startLeft = m_target.getAbsoluteLeft();
066 m_startTop = m_target.getAbsoluteTop();
067 m_startX = x + m_startLeft;
068 m_startY = y + m_startTop;
069 m_target.addStyleName("Dragging");
070 }
071
072 public void step(int x, int y)
073 {
074 // Debug.println("step(" + x + "," + y + ")");
075 int absX = x + m_target.getAbsoluteLeft();
076 int absY = y + m_target.getAbsoluteTop();
077 int deltaX = absX - m_startX;
078 int deltaY = absY - m_startY;
079 // Debug.println("setAbsolutePosition(" + (m_startLeft + deltaX) + ',' + (m_startTop + deltaY) + ')');
080 setTargetPosition(m_startLeft + deltaX, m_startTop + deltaY);
081 }
082
083 public void finish(int x, int y)
084 {
085 // Debug.println("finish(" + x + "," + y + ")");
086 m_target.removeStyleName("Dragging");
087 }
088 }