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