Merge branch 'master' into icons2
[potlatch2.git] / net / systemeD / potlatch2 / controller / ControllerState.as
1 package net.systemeD.potlatch2.controller {
2         import flash.events.*;
3         import flash.display.*;
4     import net.systemeD.halcyon.Map;
5     import net.systemeD.halcyon.MapPaint;
6     import net.systemeD.halcyon.connection.*;
7     import net.systemeD.potlatch2.collections.Imagery;
8     import net.systemeD.potlatch2.EditController;
9         import net.systemeD.potlatch2.save.SaveManager;
10         import flash.ui.Keyboard;
11         import mx.controls.Alert;
12         import mx.events.CloseEvent;
13         
14     /** Represents a particular state of the controller, such as "dragging a way" or "nothing selected". Key methods are 
15     * processKeyboardEvent and processMouseEvent which take some action, and return a new state for the controller. 
16     * 
17     * This abstract class has some behaviour that applies in most states, and lots of 'null' behaviour. 
18     * */
19     public class ControllerState {
20
21         protected var controller:EditController;
22         protected var previousState:ControllerState;
23
24                 protected var _selection:Array=[];
25
26         public function ControllerState() {}
27
28         public function setController(controller:EditController):void {
29             this.controller = controller;
30         }
31
32         public function setPreviousState(previousState:ControllerState):void {
33             if ( this.previousState == null )
34                 this.previousState = previousState;
35         }
36
37                 public function isSelectionState():Boolean {
38                         return true;
39                 }
40
41         /** When triggered by a mouse action such as a click, perform an action on the given entity, then move to a new state. */
42         public function processMouseEvent(event:MouseEvent, entity:Entity):ControllerState {
43             return this;
44         }
45                 
46                 /** When triggered by a keypress, perform an action on the given entity, then move to a new state. */
47         public function processKeyboardEvent(event:KeyboardEvent):ControllerState {
48             return this;
49         }
50
51                 public function get map():Map {
52                         return controller.map;
53                 }
54
55         public function enterState():void {}
56         public function exitState(newState:ControllerState):void {}
57
58                 /** Represent the state in text for debugging. */
59                 public function toString():String {
60                         return "(No state)";
61                 }
62                 /** Default behaviour for the current state that should be called if state-specific action has been taken care of or ruled out. */
63                 protected function sharedKeyboardEvents(event:KeyboardEvent):ControllerState {
64                         switch (event.keyCode) {
65                                 case 66:        setSourceTag(); break;                                                                                                  // B - set source tag for current object
66                                 case 67:        controller.connection.closeChangeset(); break;                                                  // C - close changeset
67                                 case 68:        controller.map.paint.alpha=1.3-controller.map.paint.alpha; return null; // D - dim
68                                 case 83:        SaveManager.saveChanges(); break;                                                                               // S - save
69                                 case 84:        controller.tagViewer.togglePanel(); return null;                                                // T - toggle tags panel
70                                 case 90:        if (!event.shiftKey) { MainUndoStack.getGlobalStack().undo(); return null;}// Z - undo
71                                             else { MainUndoStack.getGlobalStack().redo(); return null;  }           // Shift-Z - redo                                           
72                                 case Keyboard.ESCAPE:   revertSelection(); break;                                                                       // ESC - revert to server version
73                                 case Keyboard.NUMPAD_ADD:                                                                                                                       // + - add tag
74                                 case 187:       controller.tagViewer.selectAdvancedPanel();                                                             //   |
75                                                         controller.tagViewer.addNewTag(); return null;                                                  //   |
76                         }
77                         return null;
78                 }
79
80                 /** Default behaviour for the current state that should be called if state-specific action has been taken care of or ruled out. */
81                 protected function sharedMouseEvents(event:MouseEvent, entity:Entity):ControllerState {
82                         var paint:MapPaint = getMapPaint(DisplayObject(event.target));
83             var focus:Entity = getTopLevelFocusEntity(entity);
84
85                         if ( paint && paint.isBackground ) {
86                                 if ( event.type == MouseEvent.MOUSE_DOWN && ((event.shiftKey && event.ctrlKey) || event.altKey) ) {
87                                         // alt-click to pull data out of vector background layer
88                                         var newEntity:Entity=paint.findSource().pullThrough(entity,controller.connection);
89                                         if (entity is Way) { return new SelectedWay(newEntity as Way); }
90                                         else if (entity is Node) { return new SelectedPOINode(newEntity as Node); }
91                 } else if (event.type == MouseEvent.MOUSE_DOWN && entity is Marker) {
92                     return new SelectedMarker(entity as Marker, paint.findSource());
93                                 } else if ( event.type == MouseEvent.MOUSE_UP ) {
94                                         return (this is NoSelection) ? null : new NoSelection();
95                                 } else { return null; }
96                         }
97
98                         if ( event.type == MouseEvent.MOUSE_DOWN ) {
99                                 if ( entity is Node && selectedWay && entity.hasParent(selectedWay) ) {
100                                         // select node within this way
101                         return new DragWayNode(selectedWay,  getNodeIndex(selectedWay,entity as Node),  event, false);
102                                 } else if ( entity is Node && focus is Way ) {
103                                         // select way node
104                                         return new DragWayNode(focus as Way, getNodeIndex(focus as Way,entity as Node), event, false);
105                                 } else if ( controller.keyDown(Keyboard.SPACE) ) {
106                                         // drag the background imagery to compensate for poor alignment
107                                         return new DragBackground(event);
108                                 } else if (entity && selection.indexOf(entity)>-1) {
109                                         return new DragSelection(selection, event);
110                                 } else if (entity) {
111                                         return new DragSelection([entity], event);
112                                 }
113             } else if ( event.type == MouseEvent.CLICK && focus == null && map.dragstate!=map.DRAGGING && this is SelectedMarker) {
114                 // this is identical to the below, but needed for unselecting markers on vector background layers.
115                 // Deselecting a POI or way on the main layer emits both CLICK and MOUSE_UP, but markers only CLICK
116                 // I'll leave it to someone who understands to decide whether they are the same thing and should be
117                 // combined with a (CLICK || MOUSE_UP)
118                 
119                 // "&& this is SelectedMarker" added by Steve Bennett. The CLICK event being processed for SelectedWay state
120                 // causes way to get unselected...so restrict the double processing as much as possible.  
121                 
122                 return (this is NoSelection) ? null : new NoSelection();
123                         } else if ( event.type == MouseEvent.MOUSE_UP && focus == null && map.dragstate!=map.DRAGGING) {
124                                 return (this is NoSelection) ? null : new NoSelection();
125                         } else if ( event.type == MouseEvent.MOUSE_UP && focus && map.dragstate!=map.NOT_DRAGGING) {
126                                 map.mouseUpHandler();   // in case the end-drag is over an EntityUI
127                         } else if ( event.type == MouseEvent.ROLL_OVER ) {
128                                 controller.map.setHighlight(focus, { hover: true });
129                         } else if ( event.type == MouseEvent.MOUSE_OUT ) {
130                                 controller.map.setHighlight(focus, { hover: false });
131             } else if ( event.type == MouseEvent.MOUSE_WHEEL ) {
132                 if (event.delta > 0) {
133                   map.zoomIn();
134                 } else if (event.delta < 0) {
135                   map.zoomOut();
136                 }
137             }
138                         return null;
139                 }
140
141                 /** Gets the way that the selected node is part of, if that makes sense. If not, return the node, or the way, or nothing. */
142                 public static function getTopLevelFocusEntity(entity:Entity):Entity {
143                         if ( entity is Node ) {
144                                 for each (var parent:Entity in entity.parentWays) {
145                                         return parent;
146                                 }
147                                 return entity;
148                         } else if ( entity is Way ) {
149                                 return entity;
150                         } else {
151                                 return null;
152                         }
153                 }
154
155                 /** Find the MapPaint object that this DisplayObject belongs to. */
156                 protected function getMapPaint(d:DisplayObject):MapPaint {
157                         while (d) {
158                                 if (d is MapPaint) { return MapPaint(d); }
159                                 d=d.parent;
160                         }
161                         return null;
162                 }
163
164                 protected function getNodeIndex(way:Way,node:Node):uint {
165                         for (var i:uint=0; i<way.length; i++) {
166                                 if (way.getNode(i)==node) { return i; }
167                         }
168                         return null;
169                 }
170
171                 /** Create a "repeat tags" action on the current entity, if possible. */
172                 protected function repeatTags(object:Entity):void {
173                         if (!controller.clipboards[object.getType()]) { return; }
174                         object.suspend();
175
176                     var undo:CompositeUndoableAction = new CompositeUndoableAction("Repeat tags");
177                         for (var k:String in controller.clipboards[object.getType()]) {
178                                 object.setTag(k, controller.clipboards[object.getType()][k], undo.push)
179                         }
180                         MainUndoStack.getGlobalStack().addAction(undo);
181                         controller.updateSelectionUI();
182                         object.resume();
183
184
185                 }
186
187                 /** Create an action to add "source=*" tag to current entity based on background imagery. This is a convenient shorthand for users. */
188                 protected function setSourceTag():void {
189                         if (selectCount!=1) { return; }
190                         if (Imagery.instance().selected && Imagery.instance().selected.sourcetag) {
191                                 if ("sourcekey" in Imagery.instance().selected)
192                                     firstSelected.setTag(Imagery.instance().selected.sourcekey,Imagery.instance().selected.sourcetag, MainUndoStack.getGlobalStack().addAction);
193                                 else
194                                     firstSelected.setTag('source',Imagery.instance().selected.sourcetag, MainUndoStack.getGlobalStack().addAction);
195                         }
196                         controller.updateSelectionUI();
197                 }
198
199                 /** Revert all selected items to previously saved state, via a dialog box. */
200                 protected function revertSelection():void {
201                         if (selectCount==0) return;
202                         Alert.show("Revert selected items to the last saved version, discarding your changes?","Are you sure?",Alert.YES | Alert.CANCEL,null,revertHandler);
203                 }
204                 protected function revertHandler(event:CloseEvent):void {
205                         if (event.detail==Alert.CANCEL) return;
206                         for each (var item:Entity in _selection) {
207                                 controller.connection.loadEntity(item);
208                         }
209                 }
210
211                 // Selection getters
212
213                 public function get selectCount():uint {
214                         return _selection.length;
215                 }
216
217                 public function get selection():Array {
218                         return _selection;
219                 }
220
221                 public function get firstSelected():Entity {
222                         if (_selection.length==0) { return null; }
223                         return _selection[0];
224                 }
225
226                 public function get selectedWay():Way {
227                         if (firstSelected is Way) { return firstSelected as Way; }
228                         return null;
229                 }
230
231                 public function get selectedWays():Array {
232                         var selectedWays:Array=[];
233                         for each (var item:Entity in _selection) {
234                                 if (item is Way) { selectedWays.push(item); }
235                         }
236                         return selectedWays;
237                 }
238
239         public function get selectedNodes():Array {
240             var selectedNodes:Array=[];
241             for each (var item:Entity in _selection) {
242                 if (item is Node) { selectedNodes.push(item); }
243             }
244             return selectedNodes;
245         }
246
247                 public function hasSelectedWays():Boolean {
248                         for each (var item:Entity in _selection) {
249                                 if (item is Way) { return true; }
250                         }
251                         return false;
252                 }
253
254                 public function hasSelectedAreas():Boolean {
255                         for each (var item:Entity in _selection) {
256                                 if (item is Way && Way(item).isArea()) { return true; }
257                         }
258                         return false;
259                 }
260
261                 public function hasSelectedUnclosedWays():Boolean {
262                         for each (var item:Entity in _selection) {
263                                 if (item is Way && !Way(item).isArea()) { return true; }
264                         }
265                         return false;
266                 }
267
268         /** Determine whether or not any nodes are selected, and if so whether any of them belong to areas. */
269         public function hasSelectedWayNodesInAreas():Boolean {
270             for each (var item:Entity in _selection) {
271                 if (item is Node) {
272                     var parentWays:Array = Node(item).parentWays;
273                     for each (var way:Entity in parentWays) {
274                         if (Way(way).isArea()) { return true; }
275                     }
276                 }
277             }
278             return false;
279         }
280
281                 public function hasAdjoiningWays():Boolean {
282                         if (_selection.length<2) { return false; }
283                         var endNodes:Object={};
284                         for each (var item:Entity in _selection) {
285                                 if (item is Way && !Way(item).isArea()) {
286                                         if (endNodes[Way(item).getNode(0).id]) return true;
287                                         if (endNodes[Way(item).getLastNode().id]) return true;
288                                         endNodes[Way(item).getNode(0).id]=true;
289                                         endNodes[Way(item).getLastNode().id]=true;
290                                 }
291                         }
292                         return false;
293                 }
294
295                 // Selection setters
296
297                 public function set selection(items:Array):void {
298                         _selection=items;
299                 }
300
301                 public function addToSelection(items:Array):void {
302                         for each (var item:Entity in items) {
303                                 if (_selection.indexOf(item)==-1) { _selection.push(item); }
304                         }
305                 }
306
307                 public function removeFromSelection(items:Array):void {
308                         for each (var item:Entity in items) {
309                                 if (_selection.indexOf(item)>-1) {
310                                         _selection.splice(_selection.indexOf(item),1);
311                                 }
312                         }
313                 }
314
315                 public function toggleSelection(item:Entity):Boolean {
316                         if (_selection.indexOf(item)==-1) {
317                                 _selection.push(item); return true;
318                         }
319                         _selection.splice(_selection.indexOf(item),1); return false;
320                 }
321     }
322 }