001/*
002 * Copyright 2010-2015 Institut Pasteur.
003 * 
004 * This file is part of Icy.
005 * 
006 * Icy is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 * 
011 * Icy is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014 * GNU General Public License for more details.
015 * 
016 * You should have received a copy of the GNU General Public License
017 * along with Icy. If not, see <http://www.gnu.org/licenses/>.
018 */
019package icy.painter;
020
021import icy.util.EventUtil;
022
023import java.awt.Color;
024import java.awt.event.InputEvent;
025import java.awt.geom.Point2D;
026
027/**
028 * Anchor for rectangular shape.<br>
029 * Support special rectangular drag operation when shift is maintained.
030 * 
031 * @author Stephane
032 */
033public abstract class RectAnchor2D extends Anchor2D
034{
035    public RectAnchor2D(Point2D position, Color color, Color selectedColor)
036    {
037        super(position.getX(), position.getY(), color, selectedColor);
038    }
039
040    
041    @Override
042    protected boolean updateDrag(InputEvent e, double x, double y)
043    {
044        // not dragging --> exit
045        if (startDragMousePosition == null)
046            return false;
047
048        final Anchor2D anchor = getOppositePoint();
049
050        // shift action --> square drag
051        if (EventUtil.isShiftDown(e) && (anchor != null))
052        {
053            final Point2D pos = anchor.getPosition();
054
055            double dx = x - pos.getX();
056            double dy = y - pos.getY();
057
058            final double absDx = Math.abs(dx);
059            final double absDy = Math.abs(dy);
060
061            // align to DY
062            if (absDx > absDy)
063            {
064                if (dx >= 0)
065                    dx = absDy;
066                else
067                    dx = -absDy;
068            }
069            // align to DX
070            else
071            {
072                if (dy >= 0)
073                    dy = absDx;
074                else
075                    dy = -absDx;
076            }
077
078            // set new position
079            setPosition(pos.getX() + dx, pos.getY() + dy);
080        }
081        else
082        {
083            // normal drag
084            final double dx = x - startDragMousePosition.getX();
085            final double dy = y - startDragMousePosition.getY();
086
087            // set new position
088            setPosition(startDragPainterPosition.getX() + dx, startDragPainterPosition.getY() + dy);
089        }
090
091        return true;
092    }
093
094    protected abstract Anchor2D getOppositePoint();
095}