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