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