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