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