ADD keyboard shortcuts , and . (< and >) to step node by node along a way. Maintain...
[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.Globals;
8         import net.systemeD.halcyon.WayUI;
9         import net.systemeD.halcyon.connection.*;
10         import net.systemeD.halcyon.connection.actions.*;
11         import net.systemeD.potlatch2.tools.Quadrilateralise;
12
13     public class SelectedWayNode extends ControllerState {
14                 private var parentWay:Way;
15                 private var initIndex:int;
16                 private var selectedIndex:int;
17         
18         public function SelectedWayNode(way:Way,index:int) {
19             parentWay = way;
20                         initIndex = index;
21         }
22  
23         protected function selectNode(way:Way,index:int):void {
24                         var node:Node=way.getNode(index);
25             if ( way == parentWay && node == firstSelected )
26                 return;
27
28             clearSelection(this);
29             controller.map.setHighlight(way, { hover: false });
30             controller.map.setHighlight(node, { selected: true });
31             controller.map.setHighlightOnNodes(way, { selectedway: true });
32             selection = [node]; parentWay = way;
33             controller.updateSelectionUI();
34                         selectedIndex = index; initIndex = index;
35         }
36                 
37         protected function clearSelection(newState:ControllerState):void {
38             if ( selectCount ) {
39                 controller.map.setHighlight(parentWay, { selected: false });
40                                 controller.map.setHighlight(firstSelected, { selected: false });
41                                 controller.map.setHighlightOnNodes(parentWay, { selectedway: false });
42                                 selection = [];
43                 if (!newState.isSelectionState()) { controller.updateSelectionUI(); }
44             }
45         }
46         
47         override public function processMouseEvent(event:MouseEvent, entity:Entity):ControllerState {
48                         if (event.type==MouseEvent.MOUSE_MOVE || event.type==MouseEvent.ROLL_OVER || event.type==MouseEvent.MOUSE_OUT) { return this; }
49             var focus:Entity = getTopLevelFocusEntity(entity);
50
51             if ( event.type == MouseEvent.MOUSE_UP && entity is Node && event.shiftKey ) {
52                                 // start new way
53                 var way:Way = controller.connection.createWay({}, [entity],
54                     MainUndoStack.getGlobalStack().addAction);
55                 return new DrawWay(way, true, false);
56                         } else if ( event.type == MouseEvent.MOUSE_UP && entity is Node && focus == parentWay ) {
57                                 // select node within way
58                                 return selectOrEdit(parentWay, getNodeIndex(parentWay,Node(entity)));
59             } else if ( event.type == MouseEvent.MOUSE_DOWN && entity is Way && focus==parentWay && event.shiftKey) {
60                                 // insert node within way (shift-click)
61                         var d:DragWayNode=new DragWayNode(parentWay, -1, event, true);
62                                 d.forceDragStart();
63                                 return d;
64                         }
65                         var cs:ControllerState = sharedMouseEvents(event, entity);
66                         return cs ? cs : this;
67         }
68
69                 override public function processKeyboardEvent(event:KeyboardEvent):ControllerState {
70                         switch (event.keyCode) {
71                                 case 189:                                       return removeNode();                                    // '-'
72                                 case 88:                                        return splitWay();                                              // 'X'
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],
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                         controller.map.setPurgable(selection,false);
111                         Globals.vars.root.addDebug("**** -> "+this);
112         }
113                 override public function exitState(newState:ControllerState):void {
114             if (firstSelected.hasTags()) {
115               controller.clipboards['node']=firstSelected.getTagsCopy();
116             }
117                         controller.map.setPurgable(selection,true);
118             clearSelection(newState);
119                         Globals.vars.root.addDebug("**** <- "+this);
120         }
121
122         override public function toString():String {
123             return "SelectedWayNode";
124         }
125
126                 public static function selectOrEdit(selectedWay:Way, index:int):ControllerState {
127                         var isFirst:Boolean = false;
128                         var isLast:Boolean = false;
129                         var node:Node = selectedWay.getNode(index);
130                         isFirst = selectedWay.getNode(0) == node;
131                         isLast = selectedWay.getLastNode() == node;
132                         if ( isFirst == isLast )    // both == looped, none == central node 
133                             return new SelectedWayNode(selectedWay, index);
134                         else
135                             return new DrawWay(selectedWay, isLast, true);
136         }
137
138                 /** Splits a way into two separate ways, at the currently selected node. Handles simple loops and P-shapes. Untested for anything funkier. */
139                 public function splitWay():ControllerState {
140                         var n:Node=firstSelected as Node;
141                         var ni:uint = parentWay.indexOfNode(n);
142                         // abort if start or end
143                         if (parentWay.isPShape() && !parentWay.hasOnceOnly(n)) {
144                                 // If P-shaped, we want to split at the midway point on the stem, not at the end of the loop
145                                 ni = parentWay.getPJunctionNodeIndex();
146                                 
147                         } else {
148                             if (parentWay.getNode(0)    == n) { return this; }
149                             if (parentWay.getLastNode() == n) { return this; }
150                         }
151
152                         controller.map.setHighlightOnNodes(parentWay, { selectedway: false } );
153                         controller.map.setPurgable([parentWay],true);
154             MainUndoStack.getGlobalStack().addAction(new SplitWayAction(parentWay, ni));
155
156                         return new SelectedWay(parentWay);
157                 }
158                 
159                 public function removeNode():ControllerState {
160                         if (firstSelected.numParentWays==1 && parentWay.hasOnceOnly(firstSelected as Node) && !(firstSelected as Node).hasInterestingTags()) {
161                                 return deleteNode();
162                         }
163                         parentWay.removeNodeByIndex(selectedIndex, MainUndoStack.getGlobalStack().addAction);
164                         return new SelectedWay(parentWay);
165                 }
166                 
167                 public function deleteNode():ControllerState {
168                         controller.map.setPurgable(selection,true);
169                         firstSelected.remove(MainUndoStack.getGlobalStack().addAction);
170                         return new SelectedWay(parentWay);
171                 }
172
173         public function unjoin():ControllerState {
174             Node(firstSelected).unjoin(parentWay, MainUndoStack.getGlobalStack().addAction);
175             return this;
176         }
177
178         /** Attempt to either merge the currently selected node with another very nearby node, or failing that,
179         *   attach it mid-way along a very nearby way. */
180         public function join():ControllerState {
181             var p:Point = new Point(controller.map.lon2coord(Node(firstSelected).lon),
182                                              controller.map.latp2coord(Node(firstSelected).latp));
183             var q:Point = map.localToGlobal(p);
184
185             // First, look for POI nodes in 20x20 pixel box around the current node
186             var hitnodes:Array = map.connection.getObjectsByBbox(
187                 map.coord2lon(p.x-10),
188                 map.coord2lon(p.x+10),
189                 map.coord2lat(p.y-10),
190                 map.coord2lat(p.y+10)).poisInside;
191             
192             for each (var n: Node in hitnodes) {
193                 if (!n.hasParent(selectedWay)) { 
194                    return doMergeNodes(n);
195                 }
196             }
197             
198             var ways:Array=[]; var w:Way;
199             for each (var wayui:WayUI in controller.map.paint.wayuis) {
200                 w=wayui.hitTest(q.x, q.y);
201                 if (w && w!=selectedWay) { 
202                 // hit a way, now let's see if we hit a specific node
203                     for (var i:uint = 0; i < w.length; i++) {
204                         n = w.getNode(i);
205                         var x:Number = map.lon2coord(n.lon);
206                         var y:Number = map.latp2coord(n.latp);
207                         if (n != selectedNode && Math.abs(x-p.x) + Math.abs(y-p.y) < 10) {
208                             return doMergeNodes(n);
209                         }    
210                     }
211                     ways.push(w); 
212                 }
213             }
214
215             // No nodes hit, so join our node onto any overlapping ways.
216             Node(firstSelected).join(ways,MainUndoStack.getGlobalStack().addAction);
217             return this;
218         }
219         
220         private function doMergeNodes(n:Node): ControllerState {
221                 n.mergeWith(Node(firstSelected), MainUndoStack.getGlobalStack().addAction);
222             // only merge one node at a time - too confusing otherwise?
223             var msg:String = "Nodes merged."
224             if (MergeNodesAction.lastProblemTags) {
225                 msg += " *Warning* The following tags conflicted and need attention: " + MergeNodesAction.lastProblemTags;
226             }
227             map.connection.dispatchEvent(new AttentionEvent(AttentionEvent.ALERT, null, msg));
228             return new SelectedWayNode(n.parentWays[0], Way(n.parentWays[0]).indexOfNode(n));
229         }
230         
231         /** Move the selection one node further up or down this way, looping if necessary. */
232         public function stepNode(delta:int):ControllerState {
233             var ni:int = (selectedIndex + delta + parentWay.length) %  parentWay.length
234             controller.map.scrollIfNeeded(parentWay.getNode(ni).lat,parentWay.getNode(ni).lon);
235             return new SelectedWayNode(parentWay, ni);
236         }
237
238     }
239     
240     
241 }
242