--- /dev/null
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ * VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.scenegraph.g2d.snap;\r
+\r
+import java.awt.geom.Point2D;\r
+import java.io.Serializable;\r
+\r
+import org.simantics.scl.runtime.function.Function1;\r
+\r
+/**\r
+ * @author Tuukka Lehtonen\r
+ */\r
+public class GridSnapAdvisor implements ISnapAdvisor, Serializable {\r
+\r
+ private static final long serialVersionUID = 2411311098028229134L;\r
+\r
+ double resolution;\r
+ Function1<Object, Boolean> enabled;\r
+\r
+ public GridSnapAdvisor(double resolution) {\r
+ this.resolution = resolution;\r
+ }\r
+\r
+ public void setEnabledFunction(Function1<Object, Boolean> function) {\r
+ this.enabled = function;\r
+ }\r
+\r
+ public void setResolution(double resolution) {\r
+ this.resolution = resolution;\r
+ }\r
+ \r
+ public double getResolution() {\r
+ return resolution;\r
+ }\r
+\r
+ @Override\r
+ public void snap(Point2D point) {\r
+ if (enabled != null && !enabled.apply(null))\r
+ return;\r
+ point.setLocation(\r
+ Math.round(point.getX() / resolution) * resolution, \r
+ Math.round(point.getY() / resolution) * resolution);\r
+ }\r
+\r
+ @Override\r
+ public void snap(Point2D point, Point2D[] features) {\r
+ if (enabled != null && !enabled.apply(null))\r
+ return;\r
+ double dx = features[0].getX();\r
+ double dy = features[0].getY();\r
+ point.setLocation(\r
+ Math.round((point.getX()-dx) / resolution) * resolution + dx, \r
+ Math.round((point.getY()-dy) / resolution) * resolution + dy);\r
+ }\r
+\r
+ @Override\r
+ public String toString() {\r
+ return getClass().getSimpleName() + "[resolution=" + resolution + "]";\r
+ }\r
+\r
+ @Override\r
+ public int hashCode() {\r
+ long temp = Double.doubleToLongBits(resolution);\r
+ return (int) (temp ^ (temp >>> 32));\r
+ }\r
+\r
+ @Override\r
+ public boolean equals(Object obj) {\r
+ if (this == obj)\r
+ return true;\r
+ if (obj == null)\r
+ return false;\r
+ if (getClass() != obj.getClass())\r
+ return false;\r
+ GridSnapAdvisor other = (GridSnapAdvisor) obj;\r
+ return Double.doubleToLongBits(resolution) != Double.doubleToLongBits(other.resolution);\r
+ }\r
+\r
+}\r