43080a24914765d44ec5b1422c387b8073e05e4c
[potlatch2.git] / net / systemeD / potlatch2 / controller / SelectedWayNode.as
1 package net.systemeD.potlatch2.controller {
2         import flash.events.*;
3         import flash.geom.Point;
4         import flash.ui.Keyboard;
5         
6         import net.systemeD.halcyon.AttentionEvent;
7         import net.systemeD.halcyon.WayUI;
8         import net.systemeD.halcyon.connection.*;
9         import net.systemeD.halcyon.connection.actions.*;
10         import net.systemeD.potlatch2.tools.Quadrilateralise;
11
12     public class SelectedWayNode extends ControllerState {
13                 private var parentWay:Way;
14                 private var initIndex:int;
15                 private var selectedIndex:int;
16         
17         public function SelectedWayNode(way:Way,index:int) {
18             parentWay = way;
19                         initIndex = index;
20         }
21  
22         protected function selectNode(way:Way,index:int):void {
23                         var node:Node=way.getNode(index);
24             if ( way == parentWay && node == firstSelected )
25                 return;
26
27             clearSelection(this);
28             layer.setHighlight(way, { hover: false });
29             layer.setHighlight(node, { selected: true });
30             layer.setHighlightOnNodes(way, { selectedway: true });
31             selection = [node]; parentWay = way;
32             controller.updateSelectionUI();
33                         selectedIndex = index; initIndex = index;
34         }
35                 
36         protected function clearSelection(newState:ControllerState):void {
37             if ( selectCount ) {
38                 layer.setHighlight(parentWay, { selected: false });
39                                 layer.setHighlight(firstSelected, { selected: false });
40                                 layer.setHighlightOnNodes(parentWay, { selectedway: false });
41                                 selection = [];
42                 if (!newState.isSelectionState()) { controller.updateSelectionUI(); }
43             }
44         }
45         
46         override public function processMouseEvent(event:MouseEvent, entity:Entity):ControllerState {
47                         if (event.type==MouseEvent.MOUSE_MOVE || event.type==MouseEvent.ROLL_OVER || event.type==MouseEvent.MOUSE_OUT) { return this; }
48             var focus:Entity = getTopLevelFocusEntity(entity);
49
50             if ( event.type == MouseEvent.MOUSE_UP && entity is Node && event.shiftKey ) {
51                                 // start new way
52                 var way:Way = entity.connection.createWay({}, [entity],
53                     MainUndoStack.getGlobalStack().addAction);
54                 return new DrawWay(way, true, false);
55                         } else if ( event.type == MouseEvent.MOUSE_UP && entity is Node && focus == parentWay ) {
56                                 // select node within way
57                                 return selectOrEdit(parentWay, getNodeIndex(parentWay,Node(entity)));
58             } else if ( event.type == MouseEvent.MOUSE_DOWN && entity is Way && focus==parentWay && event.shiftKey) {
59                                 // insert node within way (shift-click)
60                         var d:DragWayNode=new DragWayNode(parentWay, -1, event, true);
61                                 d.forceDragStart();
62                                 return d;
63                         }
64                         var cs:ControllerState = sharedMouseEvents(event, entity);
65                         return cs ? cs : this;
66         }
67
68                 override public function processKeyboardEvent(event:KeyboardEvent):ControllerState {
69                         switch (event.keyCode) {
70                                 case 189:                                       return removeNode();                                    // '-'
71                                 case 88:                                        return splitWay();                                              // 'X'
72                                 case 79:                                        return replaceNode();                                   // 'O'
73                 case 81:  /* Q */           Quadrilateralise.quadrilateralise(parentWay, MainUndoStack.getGlobalStack().addAction); return this;
74                                 case 82:                                        repeatTags(firstSelected); return this; // 'R'
75                                 case 87:                                        return new SelectedWay(parentWay);              // 'W'
76                                 case 191:                                       return cycleWays();                                             // '/'
77                 case 74:                    if (event.shiftKey) { return unjoin() }; return join();// 'J'
78                                 case Keyboard.BACKSPACE:        return deleteNode();
79                                 case Keyboard.DELETE:           return deleteNode();
80                                 case 188: /* , */           return stepNode(-1);
81                                 case 190: /* . */           return stepNode(+1);           
82                         }
83                         var cs:ControllerState = sharedKeyboardEvents(event);
84                         return cs ? cs : this;
85                 }
86
87                 override public function get selectedWay():Way {
88                         return parentWay;
89                 }
90
91         public function get selectedNode():Node {
92             return parentWay.getNode(selectedIndex);
93         }
94         
95                 private function cycleWays():ControllerState {
96                         var wayList:Array=firstSelected.parentWays;
97                         if (wayList.length==1) { return this; }
98                         wayList.splice(wayList.indexOf(parentWay),1);
99             // find index of this node in the newly selected way, to maintain state for keyboard navigation
100             var newindex:int = Way(wayList[0]).indexOfNode(parentWay.getNode(initIndex));
101                         return new SelectedWay(wayList[0], layer,
102                                                new Point(controller.map.lon2coord(Node(firstSelected).lon),
103                                                          controller.map.latp2coord(Node(firstSelected).latp)),
104                                                wayList.concat(parentWay),
105                                                newindex);
106                 }
107
108                 override public function enterState():void {
109             selectNode(parentWay,initIndex);
110                         layer.setPurgable(selection,false);
111         }
112                 override public function exitState(newState:ControllerState):void {
113             if (firstSelected.hasTags()) {
114               controller.clipboards['node']=firstSelected.getTagsCopy();
115             }
116                         layer.setPurgable(selection,true);
117             clearSelection(newState);
118         }
119
120         override public function toString():String {
121             return "SelectedWayNode";
122         }
123
124                 public static function selectOrEdit(selectedWay:Way, index:int):ControllerState {
125                         var isFirst:Boolean = false;
126                         var isLast:Boolean = false;
127                         var node:Node = selectedWay.getNode(index);
128                         isFirst = selectedWay.getNode(0) == node;
129                         isLast = selectedWay.getLastNode() == node;
130                         if ( isFirst == isLast )    // both == looped, none == central node 
131                             return new SelectedWayNode(selectedWay, index);
132                         else
133                             return new DrawWay(selectedWay, isLast, true);
134         }
135
136                 /** Replace the selected node with a new one created at the mouse position. 
137                         The undo for this is two actions: first, replacement of the old node at the original mouse position; then, moving to the new position.
138                         It's debatable whether this should be one or two but we can leave it as a FIXME for now.  */
139                 public function replaceNode():ControllerState {
140                         // replace old node
141                         var oldNode:Node=firstSelected as Node;
142                         var newNode:Node=oldNode.replaceWithNew(layer.connection,
143                                                                 controller.map.coord2lat(layer.mouseY), 
144                                                                 controller.map.coord2lon(layer.mouseX), {},
145                                                                 MainUndoStack.getGlobalStack().addAction);
146
147                         // start dragging
148                         // we fake a MouseEvent because DragWayNode expects the x/y co-ords to be passed that way
149                         var d:DragWayNode=new DragWayNode(parentWay, parentWay.indexOfNode(newNode), new MouseEvent(MouseEvent.CLICK, true, false, layer.mouseX, layer.mouseY), true);
150                         d.forceDragStart();
151                         return d;
152                 }
153
154                 /** Splits a way into two separate ways, at the currently selected node. Handles simple loops and P-shapes. Untested for anything funkier. */
155                 public function splitWay():ControllerState {
156                         var n:Node=firstSelected as Node;
157                         var ni:uint = parentWay.indexOfNode(n);
158                         // abort if start or end
159                         if (parentWay.isPShape() && !parentWay.hasOnceOnly(n)) {
160                                 // If P-shaped, we want to split at the midway point on the stem, not at the end of the loop
161                                 ni = parentWay.getPJunctionNodeIndex();
162                                 
163                         } else {
164                             if (parentWay.getNode(0)    == n) { return this; }
165                             if (parentWay.getLastNode() == n) { return this; }
166                         }
167
168                         layer.setHighlightOnNodes(parentWay, { selectedway: false } );
169                         layer.setPurgable([parentWay],true);
170             MainUndoStack.getGlobalStack().addAction(new SplitWayAction(parentWay, ni));
171
172                         return new SelectedWay(parentWay);
173                 }
174                 
175                 public function removeNode():ControllerState {
176                         if (firstSelected.numParentWays==1 && parentWay.hasOnceOnly(firstSelected as Node) && !(firstSelected as Node).hasInterestingTags()) {
177                                 return deleteNode();
178                         }
179                         parentWay.removeNodeByIndex(selectedIndex, MainUndoStack.getGlobalStack().addAction);
180                         return new SelectedWay(parentWay);
181                 }
182                 
183                 public function deleteNode():ControllerState {
184                         layer.setPurgable(selection,true);
185                         firstSelected.remove(MainUndoStack.getGlobalStack().addAction);
186                         return new SelectedWay(parentWay);
187                 }
188
189         public function unjoin():ControllerState {
190             Node(firstSelected).unjoin(parentWay, MainUndoStack.getGlobalStack().addAction);
191             return this;
192         }
193
194         /** Attempt to either merge the currently selected node with another very nearby node, or failing that,
195         *   attach it mid-way along a very nearby way. */
196                 // FIXME: why are we only merging one node at once? after all, shift-click to insert a node adds into all ways
197         public function join():ControllerState {
198                         var p:Point = new Point(controller.map.lon2coord(Node(firstSelected).lon),
199                                                 controller.map.latp2coord(Node(firstSelected).latp));
200             var q:Point = map.localToGlobal(p);
201
202             // First, look for POI nodes in 20x20 pixel box around the current node
203                         // FIXME: why aren't we using a hitTest for this?
204             var hitnodes:Array = layer.connection.getObjectsByBbox(
205                 map.coord2lon(p.x-10),
206                 map.coord2lon(p.x+10),
207                 map.coord2lat(p.y-10),
208                 map.coord2lat(p.y+10)).poisInside;
209             
210             for each (var n: Node in hitnodes) {
211                 if (!n.hasParent(selectedWay)) { 
212                    return doMergeNodes(n);
213                 }
214             }
215             
216                         var ways:Array=layer.findWaysAtPoint(q.x, q.y, selectedWay);
217                         for each (var w:Way in ways) {
218                 // hit a way, now let's see if we hit a specific node
219                 for (var i:uint = 0; i < w.length; i++) {
220                                         n = w.getNode(i);
221                                         var x:Number = map.lon2coord(n.lon);
222                                         var y:Number = map.latp2coord(n.latp);
223                                         if (n != selectedNode && Math.abs(x-p.x) + Math.abs(y-p.y) < 10) {
224                                                 return doMergeNodes(n);
225                                         }
226                                 }
227             }
228
229             // No nodes hit, so join our node onto any overlapping ways.
230             Node(firstSelected).join(ways,MainUndoStack.getGlobalStack().addAction);
231             return this;
232         }
233         
234         private function doMergeNodes(n:Node): ControllerState {
235                 n.mergeWith(Node(firstSelected), MainUndoStack.getGlobalStack().addAction);
236             // only merge one node at a time - too confusing otherwise?
237             var msg:String = "Nodes merged"
238             if (MergeNodesAction.lastTagsMerged) msg += ": check conflicting tags";
239             controller.dispatchEvent(new AttentionEvent(AttentionEvent.ALERT, null, msg));
240                         if (n.isDeleted()) n=Node(firstSelected);
241             return new SelectedWayNode(n.parentWays[0], Way(n.parentWays[0]).indexOfNode(n));
242         }
243         
244         /** Move the selection one node further up or down this way, looping if necessary. */
245         public function stepNode(delta:int):ControllerState {
246             var ni:int = (selectedIndex + delta + parentWay.length) %  parentWay.length
247             controller.map.scrollIfNeeded(parentWay.getNode(ni).lat,parentWay.getNode(ni).lon);
248             return new SelectedWayNode(parentWay, ni);
249         }
250
251     }
252     
253     
254 }
255