Merge remote-tracking branch 'stevage/repeat-relations-3596' into repeatrelations
[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         protected var previousState:ControllerState;
29
30                 protected var _selection:Array=[];
31
32         public function ControllerState() {}
33
34         public function setController(controller:EditController):void {
35             this.controller=controller;
36             if (!layer) layer=controller.map.editableLayer;
37         }
38
39         public function setPreviousState(previousState:ControllerState):void {
40             if ( this.previousState == null )
41                 this.previousState = previousState;
42         }
43
44                 public function isSelectionState():Boolean {
45                         return true;
46                 }
47
48         /** When triggered by a mouse action such as a click, perform an action on the given entity, then move to a new state. */
49         public function processMouseEvent(event:MouseEvent, entity:Entity):ControllerState {
50             return this;
51         }
52                 
53                 /** When triggered by a keypress, perform an action on the given entity, then move to a new state. */
54         public function processKeyboardEvent(event:KeyboardEvent):ControllerState {
55             return this;
56         }
57
58         /** Retrieves the map associated with the current EditController */
59                 public function get map():Map {
60                         return controller.map;
61                 }
62
63         /** This is called when the EditController sets this ControllerState as the active state.
64         * Override this with whatever is needed, such as adding highlights to entities
65         */
66         public function enterState():void {}
67
68         /** This is called by the EditController as the current controllerstate is exiting.
69         * Override this with whatever cleanup is needed, such as removing highlights from entities
70         */
71         public function exitState(newState:ControllerState):void {}
72
73                 /** Represent the state in text for debugging. */
74                 public function toString():String {
75                         return "(No state)";
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);
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: int;
215             for each (var rr:Object in controller.relationClipboards[object.getType()]) {
216                 if (!rr.relation.hasMemberInRole(object, null)) {
217                         rr.relation.appendMember(new RelationMember(object, rr.role), undo.push);
218                         relationsadded ++;
219                         
220                 }
221             }
222             MainUndoStack.getGlobalStack().addAction(undo);
223             controller.updateSelectionUI();
224             object.resume();
225             if (relationsadded > 0) {
226                     var msg:String=relationsadded.toString() + " relation(s) added to " + object.getType() + ".";
227                     controller.dispatchEvent(new AttentionEvent(AttentionEvent.ALERT, null, msg));
228                 }
229         }
230         
231         /** Copy list of relations from current object, for future repeatRelation() call. */
232         protected function copyRelations(object: Entity):void {
233                 // Leave existing relations alone if it doesn't have any
234                 if (object.parentRelations.length == 0)
235                    return;
236                 controller.relationClipboards[object.getType()]=[];
237                 for each (var rm:Object in object.getRelationMemberships() ) {
238                         var rr:Object={
239                           relation: rm.relation,
240                           role: rm.role
241                 };
242                 controller.relationClipboards[object.getType()].push(rr);
243             }
244         }
245                 
246                 /** Remove all tags from current selection. */
247                 protected function removeTags():void {
248                         if (selectCount==0) return;
249                         var undo:CompositeUndoableAction = new CompositeUndoableAction("Remove tags");
250                         for each (var item:Entity in _selection) {
251                                 item.suspend();
252                                 var tags:Array=item.getTagArray();
253                                 for each (var tag:Tag in tags) item.setTag(tag.key,null,undo.push);
254                         }
255                         MainUndoStack.getGlobalStack().addAction(undo);
256                         controller.updateSelectionUI();
257                         for each (item in _selection) item.resume();
258                 }
259
260         /** Show the history dialog, if only one object is selected. */
261         protected function showHistory():void {
262             if (selectCount == 1) {
263                 new HistoryDialog().init(firstSelected);
264             } else if (selectCount == 0) {
265                 controller.dispatchEvent(new AttentionEvent(AttentionEvent.ALERT, null, "Can't show history, nothing selected"));
266             } else {
267                 controller.dispatchEvent(new AttentionEvent(AttentionEvent.ALERT, null, "Can't show history, multiple objects selected"));
268             }
269         }
270
271                 /** Create an action to add "source=*" tag to current entity based on background imagery. This is a convenient shorthand for users. */
272                 protected function setSourceTag():void {
273                         if (selectCount!=1) { return; }
274                         if (Imagery.instance().selected && Imagery.instance().selected.sourcetag) {
275                                 if ("sourcekey" in Imagery.instance().selected)
276                                     firstSelected.setTag(Imagery.instance().selected.sourcekey,Imagery.instance().selected.sourcetag, MainUndoStack.getGlobalStack().addAction);
277                                 else
278                                     firstSelected.setTag('source',Imagery.instance().selected.sourcetag, MainUndoStack.getGlobalStack().addAction);
279                         }
280                         controller.updateSelectionUI();
281                 }
282
283                 /** Revert all selected items to previously saved state, via a dialog box. */
284                 protected function revertSelection():void {
285                         var revertable:Boolean=false;
286                         for each (var item:Entity in _selection)
287                                 if (item.id>0) revertable=true;
288                         if (revertable)
289                                 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);
290                 }
291                 protected function revertHandler(event:CloseEvent):void {
292                         if (event.detail==Alert.CANCEL) return;
293                         for each (var item:Entity in _selection) {
294                                 if (item.id>0) item.connection.loadEntity(item);
295                         }
296                 }
297
298                 // Selection getters
299
300                 public function get selectCount():uint {
301                         return _selection.length;
302                 }
303
304                 public function get selection():Array {
305                         return _selection;
306                 }
307
308                 public function get firstSelected():Entity {
309                         if (_selection.length==0) { return null; }
310                         return _selection[0];
311                 }
312
313                 public function get selectedWay():Way {
314                         if (firstSelected is Way) { return firstSelected as Way; }
315                         return null;
316                 }
317
318                 public function get selectedWays():Array {
319                         var selectedWays:Array=[];
320                         for each (var item:Entity in _selection) {
321                                 if (item is Way) { selectedWays.push(item); }
322                         }
323                         return selectedWays;
324                 }
325
326         public function get selectedNodes():Array {
327             var selectedNodes:Array=[];
328             for each (var item:Entity in _selection) {
329                 if (item is Node) { selectedNodes.push(item); }
330             }
331             return selectedNodes;
332         }
333
334                 public function hasSelectedWays():Boolean {
335                         for each (var item:Entity in _selection) {
336                                 if (item is Way) { return true; }
337                         }
338                         return false;
339                 }
340
341                 public function hasSelectedAreas():Boolean {
342                         for each (var item:Entity in _selection) {
343                                 if (item is Way && Way(item).isArea()) { return true; }
344                         }
345                         return false;
346                 }
347
348                 public function hasSelectedUnclosedWays():Boolean {
349                         for each (var item:Entity in _selection) {
350                                 if (item is Way && !Way(item).isArea()) { return true; }
351                         }
352                         return false;
353                 }
354
355         /** Determine whether or not any nodes are selected, and if so whether any of them belong to areas. */
356         public function hasSelectedWayNodesInAreas():Boolean {
357             for each (var item:Entity in _selection) {
358                 if (item is Node) {
359                     var parentWays:Array = Node(item).parentWays;
360                     for each (var way:Entity in parentWays) {
361                         if (Way(way).isArea()) { return true; }
362                     }
363                 }
364             }
365             return false;
366         }
367
368                 public function hasAdjoiningWays():Boolean {
369                         if (_selection.length<2) { return false; }
370                         var endNodes:Object={};
371                         for each (var item:Entity in _selection) {
372                                 if (item is Way && !Way(item).isArea() && Way(item).length>0) {
373                                         var startNode:int=Way(item).getNode(0).id;
374                                         var finishNode:int=Way(item).getLastNode().id;
375                                         if (endNodes[startNode ]) return true;
376                                         if (endNodes[finishNode]) return true;
377                                         endNodes[startNode ]=true;
378                                         endNodes[finishNode]=true;
379                                 }
380                         }
381                         return false;
382                 }
383
384                 /** Identify the inners and outer from the current selection for making a multipolygon. */
385                 
386                 public function multipolygonMembers():Object {
387                         if (_selection.length<2) { return {}; }
388
389                         var entity:Entity;
390                         var relation:Relation;
391                         var outer:Way;
392                         var inners:Array=[];
393
394                         // If there's an existing outer in the selection, use that
395                         for each (entity in selection) {
396                                 if (!(entity is Way)) return {};
397                                 var r:Array=entity.findParentRelationsOfType('multipolygon','outer');
398                                 if (r.length) { outer=Way(entity); relation=r[0]; }
399                         }
400
401                         // Otherwise, find the way with the biggest area
402                         var largest:Number=0;
403                         if (!outer) {
404                                 for each (entity in selection) {
405                                         if (!(entity is Way)) return {};
406                                         if (!Way(entity).isArea()) return {};
407                                         var props:Object=layer.wayUIProperties(entity as Way);
408                                         if (props.patharea>largest) { outer=Way(entity); largest=props.patharea; }
409                                 }
410                         }
411                         if (!outer) return {};
412                         
413                         // Identify the inners
414                         for each (entity in selection) {
415                                 if (entity==outer) continue;
416                                 if (!(entity is Way)) return {};
417                                 if (!Way(entity).isArea()) return {};
418                                 var node:Node=Way(entity).getFirstNode();
419                                 if (outer.pointWithin(node.lon,node.lat)) inners.push(entity);
420                         }
421                         if (inners.length==0) return {};
422                         
423                         return { outer: outer,
424                                  inners: inners,
425                                  relation: relation }
426                 }
427
428
429                 // Selection setters
430
431                 public function set selection(items:Array):void {
432                         _selection=items;
433                 }
434
435                 public function addToSelection(items:Array):void {
436                         for each (var item:Entity in items) {
437                                 if (_selection.indexOf(item)==-1) { _selection.push(item); }
438                         }
439                 }
440
441                 public function removeFromSelection(items:Array):void {
442                         for each (var item:Entity in items) {
443                                 if (_selection.indexOf(item)>-1) {
444                                         _selection.splice(_selection.indexOf(item),1);
445                                 }
446                         }
447                 }
448
449                 public function toggleSelection(item:Entity):Boolean {
450                         if (_selection.indexOf(item)==-1) {
451                                 _selection.push(item); return true;
452                         }
453                         _selection.splice(_selection.indexOf(item),1); return false;
454                 }
455     }
456 }