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