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