e9270a0964c3b5a0895471a964322e30b2970682
[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         import mx.core.FlexGlobals;
15         
16     /** Represents a particular state of the controller, such as "dragging a way" or "nothing selected". Key methods are 
17     * processKeyboardEvent and processMouseEvent which take some action, and return a new state for the controller. 
18     * 
19     * This abstract class has some behaviour that applies in most states, and lots of 'null' behaviour. 
20     * */
21     public class ControllerState {
22
23         protected var controller:EditController;
24                 public var layer:MapPaint;
25         protected var previousState:ControllerState;
26
27                 protected var _selection:Array=[];
28
29         public function ControllerState() {}
30
31         public function setController(controller:EditController):void {
32             this.controller=controller;
33             if (!layer) layer=controller.map.editableLayer;
34         }
35
36         public function setPreviousState(previousState:ControllerState):void {
37             if ( this.previousState == null )
38                 this.previousState = previousState;
39         }
40
41                 public function isSelectionState():Boolean {
42                         return true;
43                 }
44
45         /** When triggered by a mouse action such as a click, perform an action on the given entity, then move to a new state. */
46         public function processMouseEvent(event:MouseEvent, entity:Entity):ControllerState {
47             return this;
48         }
49                 
50                 /** When triggered by a keypress, perform an action on the given entity, then move to a new state. */
51         public function processKeyboardEvent(event:KeyboardEvent):ControllerState {
52             return this;
53         }
54
55         /** Retrieves the map associated with the current EditController */
56                 public function get map():Map {
57                         return controller.map;
58                 }
59
60         /** This is called when the EditController sets this ControllerState as the active state.
61         * Override this with whatever is needed, such as adding highlights to entities
62         */
63         public function enterState():void {}
64
65         /** This is called by the EditController as the current controllerstate is exiting.
66         * Override this with whatever cleanup is needed, such as removing highlights from entities
67         */
68         public function exitState(newState:ControllerState):void {}
69
70                 /** Represent the state in text for debugging. */
71                 public function toString():String {
72                         return "(No state)";
73                 }
74                 /** Default behaviour for the current state that should be called if state-specific action has been taken care of or ruled out. */
75                 protected function sharedKeyboardEvents(event:KeyboardEvent):ControllerState {
76                         var editableLayer:MapPaint=controller.map.editableLayer;                                                                // shorthand for this method
77                         switch (event.keyCode) {
78                                 case 48:        removeTags(); break;                                                                                                    // 0 - remove all tags
79                                 case 66:        setSourceTag(); break;                                                                                                  // B - set source tag for current object
80                                 case 67:        editableLayer.connection.closeChangeset(); break;                                               // C - close changeset
81                                 case 68:        editableLayer.alpha=1.3-editableLayer.alpha; return null;                               // D - dim
82                                 case 71:        FlexGlobals.topLevelApplication.trackLoader.load(); break;                              // G - GPS tracks **FIXME: move from Application to Map
83                                 case 83:        SaveManager.saveChanges(editableLayer.connection); break;                               // S - save
84                                 case 84:        controller.tagViewer.togglePanel(); return null;                                                // T - toggle tags panel
85                                 case 90:        if (!event.shiftKey) { MainUndoStack.getGlobalStack().undo(); return null;}// Z - undo
86                                             else { MainUndoStack.getGlobalStack().redo(); return null;  }           // Shift-Z - redo                                           
87                                 case Keyboard.ESCAPE:   revertSelection(); break;                                                                       // ESC - revert to server version
88                                 case Keyboard.NUMPAD_ADD:                                                                                                                       // + - add tag
89                                 case 187:       controller.tagViewer.selectAdvancedPanel();                                                             //   |
90                                                         controller.tagViewer.addNewTag(); return null;                                                  //   |
91                         }
92                         return null;
93                 }
94
95                 /** Default behaviour for the current state that should be called if state-specific action has been taken care of or ruled out. */
96                 protected function sharedMouseEvents(event:MouseEvent, entity:Entity):ControllerState {
97                         var paint:MapPaint = getMapPaint(DisplayObject(event.target));
98             var focus:Entity = getTopLevelFocusEntity(entity);
99
100                         if ( event.type == MouseEvent.MOUSE_UP && focus && map.dragstate!=map.NOT_DRAGGING) {
101                                 map.mouseUpHandler();   // in case the end-drag is over an EntityUI
102                         } else if ( event.type == MouseEvent.ROLL_OVER && paint && paint.interactive ) {
103                                 paint.setHighlight(focus, { hover: true });
104                         } else if ( event.type == MouseEvent.MOUSE_OUT && paint && paint.interactive ) {
105                                 paint.setHighlight(focus, { hover: false });
106                         } else if ( event.type == MouseEvent.MOUSE_WHEEL ) {
107                                 if      (event.delta > 0) { map.zoomIn(); }
108                                 else if (event.delta < 0) { map.zoomOut(); }
109                         }
110
111                         if ( paint && paint.isBackground ) {
112                                 if (event.type == MouseEvent.MOUSE_DOWN && ((event.shiftKey && event.ctrlKey) || event.altKey) ) {
113                                         // alt-click to pull data out of vector background layer
114                                         // extend the current selection (alt-ctrl) or create a new one (alt)?
115                                         var newSelection:Array=(event.altKey && event.ctrlKey) ? _selection : [];
116                                         // create a list of the alt-clicked item, plus anything else already selected (assuming it's in the same layer!)
117                                         var itemsToPullThrough:Array=[]
118                                         if (_selection.length && firstSelected.connection==entity.connection) itemsToPullThrough=_selection.slice();
119                                         if (itemsToPullThrough.indexOf(entity)==-1) itemsToPullThrough.push(entity);
120                                         // make sure they're unhighlighted, and pull them through
121                                         for each (var entity:Entity in itemsToPullThrough) {
122                                                 paint.setHighlight(entity, { hover:false, selected: false });
123                                                 if (entity is Way) paint.setHighlightOnNodes(Way(entity), { selectedway: false });
124                                                 newSelection.push(paint.pullThrough(entity,controller.map.editableLayer));
125                                         }
126                                         return controller.findStateForSelection(newSelection);
127                                 } else if (!paint.interactive) {
128                                         return null;
129                                 } else if (event.type == MouseEvent.MOUSE_DOWN && paint.interactive) {
130                                         if      (entity is Way   ) { return new SelectedWay(entity as Way, paint); }
131                                         else if (entity is Node  ) { if (!entity.hasParentWays) return new SelectedPOINode(entity as Node, paint); }
132                                         else if (entity is Marker) { return new SelectedMarker(entity as Marker, paint); }
133                                 } else if ( event.type == MouseEvent.MOUSE_UP && !event.ctrlKey) {
134                                         return (this is NoSelection) ? null : new NoSelection();
135                                 } else if ( event.type == MouseEvent.CLICK && focus == null && map.dragstate!=map.DRAGGING && !event.ctrlKey) {
136                                         return (this is NoSelection) ? null : new NoSelection();
137                                 }
138                                         
139                         } else if ( event.type == MouseEvent.MOUSE_DOWN ) {
140                                 if ( entity is Node && selectedWay && entity.hasParent(selectedWay) ) {
141                                         // select node within this way
142                                         return new DragWayNode(selectedWay,  getNodeIndex(selectedWay,entity as Node),  event, false);
143                                 } else if ( controller.spaceHeld ) {
144                                         // drag the background imagery to compensate for poor alignment
145                                         return new DragBackground(event);
146                                 } else if (entity && selection.indexOf(entity)>-1) {
147                                         return new DragSelection(selection, event);
148                                 } else if (entity) {
149                                         return controller.findStateForSelection([entity]);
150                                 } else if (event.ctrlKey && !layer.isBackground) {
151                                         return new SelectArea(event.localX,event.localY,selection);
152                                 }
153
154             } else if ( event.type==MouseEvent.MOUSE_UP && focus == null && map.dragstate!=map.DRAGGING && !event.ctrlKey) {
155                 return (this is NoSelection) ? null : new NoSelection();
156             }
157                         return null;
158                 }
159
160                 /** Gets the way that the selected node is part of, if that makes sense. If not, return the node, or the way, or nothing. */
161                 public static function getTopLevelFocusEntity(entity:Entity):Entity {
162                         if ( entity is Node ) {
163                                 for each (var parent:Entity in entity.parentWays) {
164                                         return parent;
165                                 }
166                                 return entity;
167                         } else if ( entity is Way ) {
168                                 return entity;
169                         } else {
170                                 return null;
171                         }
172                 }
173
174                 /** Find the MapPaint object that this DisplayObject belongs to. */
175                 protected function getMapPaint(d:DisplayObject):MapPaint {
176                         while (d) {
177                                 if (d is MapPaint) { return MapPaint(d); }
178                                 d=d.parent;
179                         }
180                         return null;
181                 }
182
183                 protected function getNodeIndex(way:Way,node:Node):uint {
184                         for (var i:uint=0; i<way.length; i++) {
185                                 if (way.getNode(i)==node) { return i; }
186                         }
187                         return null;
188                 }
189
190                 /** Create a "repeat tags" action on the current entity, if possible. */
191                 protected function repeatTags(object:Entity):void {
192                         if (!controller.clipboards[object.getType()]) { return; }
193                         object.suspend();
194
195                     var undo:CompositeUndoableAction = new CompositeUndoableAction("Repeat tags");
196                         for (var k:String in controller.clipboards[object.getType()]) {
197                                 object.setTag(k, controller.clipboards[object.getType()][k], undo.push)
198                         }
199                         MainUndoStack.getGlobalStack().addAction(undo);
200                         controller.updateSelectionUI();
201                         object.resume();
202
203
204                 }
205                 
206                 /** Remove all tags from current selection. */
207                 protected function removeTags():void {
208                         if (selectCount==0) return;
209                         var undo:CompositeUndoableAction = new CompositeUndoableAction("Remove tags");
210                         for each (var item:Entity in _selection) {
211                                 item.suspend();
212                                 var tags:Array=item.getTagArray();
213                                 for each (var tag:Tag in tags) item.setTag(tag.key,null,undo.push);
214                         }
215                         MainUndoStack.getGlobalStack().addAction(undo);
216                         controller.updateSelectionUI();
217                         for each (item in _selection) item.resume();
218                 }
219
220                 /** Create an action to add "source=*" tag to current entity based on background imagery. This is a convenient shorthand for users. */
221                 protected function setSourceTag():void {
222                         if (selectCount!=1) { return; }
223                         if (Imagery.instance().selected && Imagery.instance().selected.sourcetag) {
224                                 if ("sourcekey" in Imagery.instance().selected)
225                                     firstSelected.setTag(Imagery.instance().selected.sourcekey,Imagery.instance().selected.sourcetag, MainUndoStack.getGlobalStack().addAction);
226                                 else
227                                     firstSelected.setTag('source',Imagery.instance().selected.sourcetag, MainUndoStack.getGlobalStack().addAction);
228                         }
229                         controller.updateSelectionUI();
230                 }
231
232                 /** Revert all selected items to previously saved state, via a dialog box. */
233                 protected function revertSelection():void {
234                         var revertable:Boolean=false;
235                         for each (var item:Entity in _selection)
236                                 if (item.id>0) revertable=true;
237                         if (revertable)
238                                 Alert.show("Revert selected items to the last saved version, discarding your changes?","Are you sure?",Alert.YES | Alert.CANCEL,null,revertHandler,null,Alert.CANCEL);
239                 }
240                 protected function revertHandler(event:CloseEvent):void {
241                         if (event.detail==Alert.CANCEL) return;
242                         for each (var item:Entity in _selection) {
243                                 if (item.id>0) item.connection.loadEntity(item);
244                         }
245                 }
246
247                 // Selection getters
248
249                 public function get selectCount():uint {
250                         return _selection.length;
251                 }
252
253                 public function get selection():Array {
254                         return _selection;
255                 }
256
257                 public function get firstSelected():Entity {
258                         if (_selection.length==0) { return null; }
259                         return _selection[0];
260                 }
261
262                 public function get selectedWay():Way {
263                         if (firstSelected is Way) { return firstSelected as Way; }
264                         return null;
265                 }
266
267                 public function get selectedWays():Array {
268                         var selectedWays:Array=[];
269                         for each (var item:Entity in _selection) {
270                                 if (item is Way) { selectedWays.push(item); }
271                         }
272                         return selectedWays;
273                 }
274
275         public function get selectedNodes():Array {
276             var selectedNodes:Array=[];
277             for each (var item:Entity in _selection) {
278                 if (item is Node) { selectedNodes.push(item); }
279             }
280             return selectedNodes;
281         }
282
283                 public function hasSelectedWays():Boolean {
284                         for each (var item:Entity in _selection) {
285                                 if (item is Way) { return true; }
286                         }
287                         return false;
288                 }
289
290                 public function hasSelectedAreas():Boolean {
291                         for each (var item:Entity in _selection) {
292                                 if (item is Way && Way(item).isArea()) { return true; }
293                         }
294                         return false;
295                 }
296
297                 public function hasSelectedUnclosedWays():Boolean {
298                         for each (var item:Entity in _selection) {
299                                 if (item is Way && !Way(item).isArea()) { return true; }
300                         }
301                         return false;
302                 }
303
304         /** Determine whether or not any nodes are selected, and if so whether any of them belong to areas. */
305         public function hasSelectedWayNodesInAreas():Boolean {
306             for each (var item:Entity in _selection) {
307                 if (item is Node) {
308                     var parentWays:Array = Node(item).parentWays;
309                     for each (var way:Entity in parentWays) {
310                         if (Way(way).isArea()) { return true; }
311                     }
312                 }
313             }
314             return false;
315         }
316
317                 public function hasAdjoiningWays():Boolean {
318                         if (_selection.length<2) { return false; }
319                         var endNodes:Object={};
320                         for each (var item:Entity in _selection) {
321                                 if (item is Way && !Way(item).isArea() && Way(item).length>0) {
322                                         var startNode:int=Way(item).getNode(0).id;
323                                         var finishNode:int=Way(item).getLastNode().id;
324                                         if (endNodes[startNode ]) return true;
325                                         if (endNodes[finishNode]) return true;
326                                         endNodes[startNode ]=true;
327                                         endNodes[finishNode]=true;
328                                 }
329                         }
330                         return false;
331                 }
332
333                 /** Identify the inners and outer from the current selection for making a multipolygon. */
334                 
335                 public function multipolygonMembers():Object {
336                         if (_selection.length<2) { return {}; }
337
338                         var entity:Entity;
339                         var relation:Relation;
340                         var outer:Way;
341                         var inners:Array=[];
342
343                         // If there's an existing outer in the selection, use that
344                         for each (entity in selection) {
345                                 if (!(entity is Way)) return {};
346                                 var r:Array=entity.findParentRelationsOfType('multipolygon','outer');
347                                 if (r.length) { outer=Way(entity); relation=r[0]; }
348                         }
349
350                         // Otherwise, find the way with the biggest area
351                         var largest:Number=0;
352                         if (!outer) {
353                                 for each (entity in selection) {
354                                         if (!(entity is Way)) return {};
355                                         if (!Way(entity).isArea()) return {};
356                                         var props:Object=layer.wayUIProperties(entity as Way);
357                                         if (props.patharea>largest) { outer=Way(entity); largest=props.patharea; }
358                                 }
359                         }
360                         if (!outer) return {};
361                         
362                         // Identify the inners
363                         for each (entity in selection) {
364                                 if (entity==outer) continue;
365                                 if (!(entity is Way)) return {};
366                                 if (!Way(entity).isArea()) return {};
367                                 var node:Node=Way(entity).getFirstNode();
368                                 if (outer.pointWithin(node.lon,node.lat)) inners.push(entity);
369                         }
370                         if (inners.length==0) return {};
371                         
372                         return { outer: outer,
373                                  inners: inners,
374                                  relation: relation }
375                 }
376
377
378                 // Selection setters
379
380                 public function set selection(items:Array):void {
381                         _selection=items;
382                 }
383
384                 public function addToSelection(items:Array):void {
385                         for each (var item:Entity in items) {
386                                 if (_selection.indexOf(item)==-1) { _selection.push(item); }
387                         }
388                 }
389
390                 public function removeFromSelection(items:Array):void {
391                         for each (var item:Entity in items) {
392                                 if (_selection.indexOf(item)>-1) {
393                                         _selection.splice(_selection.indexOf(item),1);
394                                 }
395                         }
396                 }
397
398                 public function toggleSelection(item:Entity):Boolean {
399                         if (_selection.indexOf(item)==-1) {
400                                 _selection.push(item); return true;
401                         }
402                         _selection.splice(_selection.indexOf(item),1); return false;
403                 }
404     }
405 }