Call moveFunction at startup to report the initial position
[potlatch2.git] / net / systemeD / potlatch2 / EditController.as
1 package net.systemeD.potlatch2 {
2     import net.systemeD.halcyon.Map;
3     import net.systemeD.halcyon.MapPaint;
4     import net.systemeD.halcyon.MapController;
5     import net.systemeD.halcyon.MapEvent;
6     import net.systemeD.halcyon.connection.*;
7     import net.systemeD.halcyon.Globals;
8     import net.systemeD.potlatch2.controller.*;
9     import net.systemeD.potlatch2.FunctionKeyManager;
10         import mx.managers.CursorManager;
11     import flash.external.ExternalInterface;
12     import flash.events.*;
13         import flash.geom.*;
14         import flash.display.*;
15         import flash.ui.Keyboard;
16         import flash.ui.Mouse;
17         import flash.ui.MouseCursorData;
18         import flash.system.Capabilities;
19         import flash.text.TextField;
20     import mx.controls.TextArea;
21
22     /** Controller for the main map editing window itself. The logic that responds to mouse and keyboard events is all 
23     * buried in various ControllerState classes. */
24     public class EditController extends EventDispatcher implements MapController {
25
26         private var _map:Map;
27         public var tagViewer:TagViewer;
28                 private var toolbox:Toolbox;
29
30         /** The current ControllerState */
31         public var state:ControllerState;
32         public static var CHANGED_STATE:String="changed_state";
33         
34                 /** Hash of when a key was pressed. A user can keyDown within a TextInput, press Enter (leaving
35                     the TextInput), and then keyup - resulting in the keypress being interpreted again. 
36                     We prevent this by tracking keyDowns within the TextInput and ignoring corresponding keyUps. */
37                 private var keys:Object={};
38
39                 public var spaceHeld:Boolean=false;
40                 public var clipboards:Object={};          // one array of tags to repeat, per object type 
41                 public var relationClipboards:Object={};  // one array of relations to repeat, per object type
42                 public var cursorsEnabled:Boolean=true;
43         private var maximised:Boolean=false;
44         private var maximiseFunction:String;
45         private var minimiseFunction:String;
46         private var moveFunction:String;
47
48                 [Embed(source="../../../embedded/pen.png")]             public var pen:Class;
49                 [Embed(source="../../../embedded/pen_x.png")]           public var pen_x:Class;
50                 [Embed(source="../../../embedded/pen_o.png")]           public var pen_o:Class;
51                 [Embed(source="../../../embedded/pen_so.png")]          public var pen_so:Class;
52                 [Embed(source="../../../embedded/pen_plus.png")]        public var pen_plus:Class;
53                 
54         /** Constructor function: needs the map information, a panel to edit tags with, and the toolbox to manipulate ways with. */
55         public function EditController(map:Map, tagViewer:TagViewer, toolbox:Toolbox) {
56             this._map = map;
57             setState(new NoSelection());
58             this.tagViewer = tagViewer;
59             this.tagViewer.controller = this;
60                         this.toolbox = toolbox;
61                         this.toolbox.init(this);
62                         this.toolbox.updateSelectionUI();
63             this.maximiseFunction = Globals.vars.flashvars["maximise_function"];
64             this.minimiseFunction = Globals.vars.flashvars["minimise_function"];
65             this.moveFunction     = Globals.vars.flashvars["move_function"];
66
67             map.parent.addEventListener(MouseEvent.MOUSE_MOVE, mapMouseEvent);
68             map.parent.addEventListener(MouseEvent.MOUSE_UP, mapMouseEvent);
69             map.parent.addEventListener(MouseEvent.MOUSE_DOWN, mapMouseEvent);
70             map.parent.addEventListener(MouseEvent.MOUSE_WHEEL, mapMouseEvent);
71             map.parent.addEventListener(MouseEvent.CLICK, mapMouseEvent);
72             map.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
73             map.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
74
75             if (this.moveFunction) {
76                 var lon:Number = ( map.edge_r + map.edge_l ) / 2;
77                 var lat:Number = ( map.edge_b + map.edge_t ) / 2;
78
79                 ExternalInterface.call(this.moveFunction, lon, lat, map.scale,
80                                        map.edge_l, map.edge_b, map.edge_r, map.edge_t);
81
82                 map.addEventListener(MapEvent.MOVE, moveHandler);
83             }
84
85                         if (supportsMouseCursors()) {
86                                 createBitmapCursor("pen"     ,new pen());
87                                 createBitmapCursor("pen_x"   ,new pen_x());
88                                 createBitmapCursor("pen_o"   ,new pen_o());
89                                 createBitmapCursor("pen_so"  ,new pen_so());
90                                 createBitmapCursor("pen_plus",new pen_plus());
91                         }
92         }
93
94         public function setActive():void {
95             map.setController(this);
96         }
97
98         /** Accesses map object. */
99         public function get map():Map {
100             return _map;
101         }
102         
103         /**
104         * Updates the various user interfaces that change when the selection changes.
105         * Currently this is the TagViewer and the Toolbox
106         *
107         * @param layer Optionally pass the layer of the currently selected entity, eg for BugLayers
108         */
109                 public function updateSelectionUI(layer:MapPaint = null):void {
110                         tagViewer.setEntity(state.selection, layer);
111                         toolbox.updateSelectionUI();
112                 }
113
114                 public function updateSelectionUIWithoutTagChange():void {
115                         toolbox.updateSelectionUI();
116                 }
117         
118         private function keyDownHandler(event:KeyboardEvent):void {
119                         if ((event.target is TextField) || (event.target is TextArea)) {
120                                 keys[event.keyCode]=new Date().getTime();
121                                 return;
122                         }
123                         delete keys[event.keyCode];
124                         if (event.keyCode==Keyboard.SPACE) spaceHeld=true;
125                 }
126
127         private function keyUpHandler(event:KeyboardEvent):void {
128                         if ((event.target is TextField) || (event.target is TextArea)) return;
129                         if (event.keyCode==Keyboard.SPACE) spaceHeld=false;
130                         if (keys[event.keyCode] && new Date().getTime()-keys[event.keyCode]<300) return;
131                         delete keys[event.keyCode];
132
133                         if (FunctionKeyManager.instance().handleKeypress(event.keyCode)) { return; }
134             
135             if (event.keyCode == 77) { toggleSize(); } // 'M'
136             var newState:ControllerState = state.processKeyboardEvent(event);
137             setState(newState);            
138                 }
139
140         private function mapMouseEvent(event:MouseEvent):void {
141             if (isInteractionEvent(event)) map.stage.focus = map.parent;
142             if (event.type==MouseEvent.MOUSE_UP && map.dragstate==map.DRAGGING) { return; }
143             
144             var mapLoc:Point = map.globalToLocal(new Point(event.stageX, event.stageY));
145             event.localX = mapLoc.x;
146             event.localY = mapLoc.y;
147
148             var newState:ControllerState = state.processMouseEvent(event, null);
149             setState(newState);
150         }
151         
152         public function entityMouseEvent(event:MouseEvent, entity:Entity):void {
153             if (isInteractionEvent(event)) map.stage.focus = map.parent;
154             event.stopPropagation();
155                 
156             var mapLoc:Point = map.globalToLocal(new Point(event.stageX, event.stageY));
157             event.localX = mapLoc.x;
158             event.localY = mapLoc.y;
159
160             var newState:ControllerState = state.processMouseEvent(event, entity);
161             setState(newState);
162         }
163
164                 private function isInteractionEvent(event:MouseEvent):Boolean {
165                         switch (event.type) {
166                                 case MouseEvent.ROLL_OUT:       return false;
167                                 case MouseEvent.ROLL_OVER:      return false;
168                                 case MouseEvent.MOUSE_OUT:      return false;
169                                 case MouseEvent.MOUSE_OVER:     return false;
170                                 case MouseEvent.MOUSE_MOVE:     return false;
171                 }
172                         return true;
173                 }
174
175         /** Exit the current state and switch to a new one.
176         *
177         *   @param newState The ControllerState to switch to. */
178         public function setState(newState:ControllerState):void {
179             if ( newState == state )
180                 return;
181                 
182             if ( state != null )
183                 state.exitState(newState);
184             newState.setController(this);
185             state = newState;
186             state.enterState();
187             dispatchEvent(new Event(CHANGED_STATE));
188         }
189
190                 /** Given what is currently selected (or not), find the matching ControllerState. */
191                 public function findStateForSelection(sel:Array):ControllerState {
192                         if (sel.length==0) { return new NoSelection(); }
193                         var layer:MapPaint=_map.getLayerForEntity(sel[0]);
194                         
195                         if (sel.length>1) { return new SelectedMultiple(sel, layer); }
196                         else if (sel[0] is Way) { return new SelectedWay(sel[0], layer); }
197                         else if (sel[0] is Node && Node(sel[0]).hasParentWays) {
198                                 var way:Way=sel[0].parentWays[0] as Way;
199                                 return new SelectedWayNode(way, way.indexOfNode(sel[0] as Node));
200                         } else {
201                                 return new SelectedPOINode(sel[0] as Node, layer);
202                         }
203                 }
204
205                 /** Set a mouse pointer. */
206                 public function setCursor(name:String=""):void {
207                         if (name && cursorsEnabled && supportsMouseCursors()) { Mouse.cursor=name; }
208                         else { Mouse.cursor=flash.ui.MouseCursor.AUTO; }
209                 }
210
211                 private function createBitmapCursor(name:String, source:Bitmap, hotX:int=4, hotY:int=0):void {
212                         var bitmapVector:Vector.<BitmapData> = new Vector.<BitmapData>(1, true);
213                         bitmapVector[0] = source.bitmapData;
214                         var cursorData:MouseCursorData = new MouseCursorData();
215                         cursorData.hotSpot = new Point(hotX,hotY);
216                         cursorData.data = bitmapVector;
217                         Mouse.registerCursor(name, cursorData);
218                 }
219
220                 private function supportsMouseCursors():Boolean {
221                         var fpArray:Array=Capabilities.version.split(",");
222                         var fpVersion:Number=Number(fpArray[0].split(" ")[1])+Number(fpArray[1])/10;
223                         return (fpVersion>10.1);
224                 }
225
226         private function toggleSize():void {
227             if (maximised) {
228                 if (minimiseFunction) {
229                     ExternalInterface.call(minimiseFunction);
230                 }
231
232                 maximised = false;
233             } else {
234                 if (maximiseFunction) {
235                     ExternalInterface.call(maximiseFunction);
236                 }
237
238                 maximised = true;
239             }
240         }
241
242                 private function moveHandler(event:MapEvent):void {
243                         ExternalInterface.call(this.moveFunction,
244                                    event.params.lon, event.params.lat, event.params.scale,
245                                    event.params.minlon, event.params.minlat,
246                                    event.params.maxlon, event.params.maxlat);
247                 }
248
249     }
250     
251 }