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