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