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