]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalCanvas.cxx
Canvas: Keyboard events and input focus.
[flightgear.git] / src / Scripting / NasalCanvas.cxx
1 // NasalCanvas.cxx -- expose Canvas classes to Nasal
2 //
3 // Written by James Turner, started 2012.
4 //
5 // Copyright (C) 2012 James Turner
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 #include "NasalCanvas.hxx"
26 #include <Canvas/canvas_mgr.hxx>
27 #include <Canvas/gui_mgr.hxx>
28 #include <Main/globals.hxx>
29 #include <Scripting/NasalSys.hxx>
30
31 #include <osgGA/GUIEventAdapter>
32
33 #include <simgear/sg_inlines.h>
34
35 #include <simgear/canvas/Canvas.hxx>
36 #include <simgear/canvas/CanvasWindow.hxx>
37 #include <simgear/canvas/elements/CanvasElement.hxx>
38 #include <simgear/canvas/elements/CanvasText.hxx>
39 #include <simgear/canvas/layout/BoxLayout.hxx>
40 #include <simgear/canvas/layout/NasalWidget.hxx>
41 #include <simgear/canvas/events/CustomEvent.hxx>
42 #include <simgear/canvas/events/KeyboardEvent.hxx>
43 #include <simgear/canvas/events/MouseEvent.hxx>
44
45 #include <simgear/nasal/cppbind/from_nasal.hxx>
46 #include <simgear/nasal/cppbind/to_nasal.hxx>
47 #include <simgear/nasal/cppbind/NasalHash.hxx>
48 #include <simgear/nasal/cppbind/Ghost.hxx>
49
50 extern naRef propNodeGhostCreate(naContext c, SGPropertyNode* n);
51
52 namespace sc = simgear::canvas;
53
54 template<class Element>
55 naRef elementGetNode(Element& element, naContext c)
56 {
57   return propNodeGhostCreate(c, element.getProps());
58 }
59
60 typedef nasal::Ghost<sc::EventPtr> NasalEvent;
61 typedef nasal::Ghost<sc::CustomEventPtr> NasalCustomEvent;
62 typedef nasal::Ghost<sc::DeviceEventPtr> NasalDeviceEvent;
63 typedef nasal::Ghost<sc::KeyboardEventPtr> NasalKeyboardEvent;
64 typedef nasal::Ghost<sc::MouseEventPtr> NasalMouseEvent;
65
66 struct CustomEventDetailWrapper;
67 typedef SGSharedPtr<CustomEventDetailWrapper> CustomEventDetailPtr;
68 typedef nasal::Ghost<CustomEventDetailPtr> NasalCustomEventDetail;
69
70 typedef nasal::Ghost<simgear::PropertyBasedElementPtr> NasalPropertyBasedElement;
71 typedef nasal::Ghost<sc::CanvasPtr> NasalCanvas;
72 typedef nasal::Ghost<sc::ElementPtr> NasalElement;
73 typedef nasal::Ghost<sc::GroupPtr> NasalGroup;
74 typedef nasal::Ghost<sc::TextPtr> NasalText;
75
76 typedef nasal::Ghost<sc::LayoutItemRef> NasalLayoutItem;
77 typedef nasal::Ghost<sc::LayoutRef> NasalLayout;
78 typedef nasal::Ghost<sc::BoxLayoutRef> NasalBoxLayout;
79
80 typedef nasal::Ghost<sc::WindowPtr> NasalWindow;
81
82 naRef to_nasal_helper(naContext c, const osg::BoundingBox& bb)
83 {
84   std::vector<float> bb_vec(4);
85   bb_vec[0] = bb._min.x();
86   bb_vec[1] = bb._min.y();
87   bb_vec[2] = bb._max.x();
88   bb_vec[3] = bb._max.y();
89
90   return nasal::to_nasal(c, bb_vec);
91 }
92
93 SGPropertyNode* from_nasal_helper(naContext c, naRef ref, SGPropertyNode**)
94 {
95   SGPropertyNode* props = ghostToPropNode(ref);
96   if( !props )
97     naRuntimeError(c, "Not a SGPropertyNode ghost.");
98
99   return props;
100 }
101
102 CanvasMgr& requireCanvasMgr(naContext c)
103 {
104   CanvasMgr* canvas_mgr =
105     static_cast<CanvasMgr*>(globals->get_subsystem("Canvas"));
106   if( !canvas_mgr )
107     naRuntimeError(c, "Failed to get Canvas subsystem");
108
109   return *canvas_mgr;
110 }
111
112 GUIMgr& requireGUIMgr(naContext c)
113 {
114   GUIMgr* mgr =
115     static_cast<GUIMgr*>(globals->get_subsystem("CanvasGUI"));
116   if( !mgr )
117     naRuntimeError(c, "Failed to get CanvasGUI subsystem");
118
119   return *mgr;
120 }
121
122 /**
123  * Create new Canvas and get ghost for it.
124  */
125 static naRef f_createCanvas(const nasal::CallContext& ctx)
126 {
127   return ctx.to_nasal(requireCanvasMgr(ctx.c).createCanvas());
128 }
129
130 /**
131  * Create new Window and get ghost for it.
132  */
133 static naRef f_createWindow(const nasal::CallContext& ctx)
134 {
135   return nasal::to_nasal<sc::WindowWeakPtr>
136   (
137     ctx.c,
138     requireGUIMgr(ctx.c).createWindow( ctx.getArg<std::string>(0) )
139   );
140 }
141
142 /**
143  * Get ghost for existing Canvas.
144  */
145 static naRef f_getCanvas(const nasal::CallContext& ctx)
146 {
147   SGPropertyNode& props = *ctx.requireArg<SGPropertyNode*>(0);
148   CanvasMgr& canvas_mgr = requireCanvasMgr(ctx.c);
149
150   sc::CanvasPtr canvas;
151   if( canvas_mgr.getPropertyRoot() == props.getParent() )
152   {
153     // get a canvas specified by its root node
154     canvas = canvas_mgr.getCanvas( props.getIndex() );
155     if( !canvas || canvas->getProps() != &props )
156       return naNil();
157   }
158   else
159   {
160     // get a canvas by name
161     if( props.hasValue("name") )
162       canvas = canvas_mgr.getCanvas( props.getStringValue("name") );
163     else if( props.hasValue("index") )
164       canvas = canvas_mgr.getCanvas( props.getIntValue("index") );
165   }
166
167   return ctx.to_nasal(canvas);
168 }
169
170 naRef f_canvasCreateGroup(sc::Canvas& canvas, const nasal::CallContext& ctx)
171 {
172   return ctx.to_nasal( canvas.createGroup(ctx.getArg<std::string>(0)) );
173 }
174
175 /**
176  * Get group containing all gui windows
177  */
178 naRef f_getDesktop(naContext c, naRef me, int argc, naRef* args)
179 {
180   return nasal::to_nasal(c, requireGUIMgr(c).getDesktop());
181 }
182
183 naRef f_setInputFocus(const nasal::CallContext& ctx)
184 {
185   requireGUIMgr(ctx.c).setInputFocus(ctx.requireArg<sc::WindowPtr>(0));
186   return naNil();
187 }
188
189 static naRef f_groupCreateChild(sc::Group& group, const nasal::CallContext& ctx)
190 {
191   return ctx.to_nasal( group.createChild( ctx.requireArg<std::string>(0),
192                                           ctx.getArg<std::string>(1) ) );
193 }
194
195 static sc::ElementPtr f_groupGetChild(sc::Group& group, SGPropertyNode* node)
196 {
197   return group.getChild(node);
198 }
199
200 static void propElementSetData( simgear::PropertyBasedElement& el,
201                                 const std::string& name,
202                                 naContext c,
203                                 naRef ref )
204 {
205   if( naIsNil(ref) )
206     return el.removeDataProp(name);
207
208   std::string val = nasal::from_nasal<std::string>(c, ref);
209
210   char* end = NULL;
211
212   long val_long = strtol(val.c_str(), &end, 10);
213   if( !*end )
214     return el.setDataProp(name, val_long);
215
216   double val_double = strtod(val.c_str(), &end);
217   if( !*end )
218     return el.setDataProp(name, val_double);
219
220   el.setDataProp(name, val);
221 }
222
223 /**
224  * Accessor for HTML5 data properties.
225  *
226  * # set single property:
227  * el.data("myKey", 5);
228  *
229  * # set multiple properties
230  * el.data({myProp1: 12, myProp2: "test"});
231  *
232  * # get value of properties
233  * el.data("myKey");   # 5
234  * el.data("myProp2"); # "test"
235  *
236  * # remove a single property
237  * el.data("myKey", nil);
238  *
239  * # remove multiple properties
240  * el.data({myProp1: nil, myProp2: nil});
241  *
242  * # set and remove multiple properties
243  * el.data({newProp: "some text...", removeProp: nil});
244  *
245  *
246  * @see http://api.jquery.com/data/
247  */
248 static naRef f_propElementData( simgear::PropertyBasedElement& el,
249                                 const nasal::CallContext& ctx )
250 {
251   if( ctx.isHash(0) )
252   {
253     // Add/delete properties given as hash
254     nasal::Hash obj = ctx.requireArg<nasal::Hash>(0);
255     for(nasal::Hash::iterator it = obj.begin(); it != obj.end(); ++it)
256       propElementSetData(el, it->getKey(), ctx.c, it->getValue<naRef>());
257
258     return ctx.to_nasal(&el);
259   }
260
261   std::string name = ctx.getArg<std::string>(0);
262   if( !name.empty() )
263   {
264     if( ctx.argc == 1 )
265     {
266       // name + additional argument -> add/delete property
267       SGPropertyNode* node = el.getDataProp<SGPropertyNode*>(name);
268       if( !node )
269         return naNil();
270
271       return ctx.to_nasal( node->getStringValue() );
272     }
273     else
274     {
275       // only name -> get property
276       propElementSetData(el, name, ctx.c, ctx.requireArg<naRef>(1));
277       return ctx.to_nasal(&el);
278     }
279   }
280
281   return naNil();
282 }
283
284 static naRef f_createCustomEvent(const nasal::CallContext& ctx)
285 {
286   std::string const& type = ctx.requireArg<std::string>(0);
287   if( type.empty() )
288     return naNil();
289
290   bool bubbles = false;
291   simgear::StringMap detail;
292   if( ctx.isHash(1) )
293   {
294     nasal::Hash const& cfg = ctx.requireArg<nasal::Hash>(1);
295     naRef na_detail = cfg.get("detail");
296     if( naIsHash(na_detail) )
297       detail = ctx.from_nasal<simgear::StringMap>(na_detail);
298     bubbles = cfg.get<bool>("bubbles");
299   }
300
301   return ctx.to_nasal(
302     sc::CustomEventPtr(new sc::CustomEvent(type, bubbles, detail))
303   );
304 }
305
306 struct CustomEventDetailWrapper:
307   public SGReferenced
308 {
309   sc::CustomEventPtr _event;
310
311   CustomEventDetailWrapper(const sc::CustomEventPtr& event):
312     _event(event)
313   {
314
315   }
316
317   bool _get( const std::string& key,
318              std::string& value_out ) const
319   {
320     if( !_event )
321       return false;
322
323     simgear::StringMap::const_iterator it = _event->detail.find(key);
324     if( it == _event->detail.end() )
325       return false;
326
327     value_out = it->second;
328     return true;
329   }
330
331   bool _set( const std::string& key,
332              const std::string& value )
333   {
334     if( !_event )
335       return false;
336
337     _event->detail[ key ] = value;
338     return true;
339   }
340 };
341
342 static naRef f_customEventGetDetail( sc::CustomEvent& event,
343                                      naContext c )
344 {
345   return nasal::to_nasal(
346     c,
347     CustomEventDetailPtr(new CustomEventDetailWrapper(&event))
348   );
349 }
350
351 static naRef f_boxLayoutAddItem( sc::BoxLayout& box,
352                                  const nasal::CallContext& ctx )
353 {
354   box.addItem( ctx.requireArg<sc::LayoutItemRef>(0),
355                ctx.getArg<int>(1) );
356   return naNil();
357 }
358 static naRef f_boxLayoutInsertItem( sc::BoxLayout& box,
359                                     const nasal::CallContext& ctx )
360 {
361   box.insertItem( ctx.requireArg<int>(0),
362                   ctx.requireArg<sc::LayoutItemRef>(1),
363                   ctx.getArg<int>(2) );
364   return naNil();
365 }
366
367 static naRef f_boxLayoutAddStretch( sc::BoxLayout& box,
368                                     const nasal::CallContext& ctx )
369 {
370   box.addStretch( ctx.getArg<int>(0) );
371   return naNil();
372 }
373 static naRef f_boxLayoutInsertStretch( sc::BoxLayout& box,
374                                        const nasal::CallContext& ctx )
375 {
376   box.insertStretch( ctx.requireArg<int>(0),
377                      ctx.getArg<int>(1) );
378   return naNil();
379 }
380
381 template<class Type, class Base>
382 static naRef f_newAsBase(const nasal::CallContext& ctx)
383 {
384   return ctx.to_nasal<Base*>(new Type());
385 }
386
387 naRef initNasalCanvas(naRef globals, naContext c)
388 {
389   nasal::Hash globals_module(globals, c),
390               canvas_module = globals_module.createHash("canvas");
391
392   nasal::Object::setupGhost();
393
394   //----------------------------------------------------------------------------
395   // Events
396
397   using osgGA::GUIEventAdapter;
398   NasalEvent::init("canvas.Event")
399     .member("type", &sc::Event::getTypeString)
400     .member("target", &sc::Event::getTarget)
401     .member("currentTarget", &sc::Event::getCurrentTarget)
402     .method("stopPropagation", &sc::Event::stopPropagation);
403
404   NasalCustomEvent::init("canvas.CustomEvent")
405     .bases<NasalEvent>()
406     .member("detail", &f_customEventGetDetail, &sc::CustomEvent::setDetail);
407   NasalCustomEventDetail::init("canvas.CustomEventDetail")
408     ._get(&CustomEventDetailWrapper::_get)
409     ._set(&CustomEventDetailWrapper::_set);
410
411   canvas_module.createHash("CustomEvent")
412                .set("new", &f_createCustomEvent);
413
414   NasalDeviceEvent::init("canvas.DeviceEvent")
415     .bases<NasalEvent>()
416     .member("modifiers", &sc::DeviceEvent::getModifiers)
417     .member("ctrlKey", &sc::DeviceEvent::ctrlKey)
418     .member("shiftKey", &sc::DeviceEvent::shiftKey)
419     .member("altKey",  &sc::DeviceEvent::altKey)
420     .member("metaKey",  &sc::DeviceEvent::metaKey);
421
422   NasalKeyboardEvent::init("canvas.KeyboardEvent")
423     .bases<NasalDeviceEvent>()
424     .member("key", &sc::KeyboardEvent::key)
425     .member("location", &sc::KeyboardEvent::location)
426     .member("repeat", &sc::KeyboardEvent::repeat)
427     .member("charCode", &sc::KeyboardEvent::charCode)
428     .member("keyCode", &sc::KeyboardEvent::keyCode);
429
430   NasalMouseEvent::init("canvas.MouseEvent")
431     .bases<NasalDeviceEvent>()
432     .member("screenX", &sc::MouseEvent::getScreenX)
433     .member("screenY", &sc::MouseEvent::getScreenY)
434     .member("clientX", &sc::MouseEvent::getClientX)
435     .member("clientY", &sc::MouseEvent::getClientY)
436     .member("localX", &sc::MouseEvent::getLocalX)
437     .member("localY", &sc::MouseEvent::getLocalY)
438     .member("deltaX", &sc::MouseEvent::getDeltaX)
439     .member("deltaY", &sc::MouseEvent::getDeltaY)
440     .member("button", &sc::MouseEvent::getButton)
441     .member("buttons", &sc::MouseEvent::getButtonMask)
442     .member("click_count", &sc::MouseEvent::getCurrentClickCount);
443
444   //----------------------------------------------------------------------------
445   // Canvas & elements
446
447   NasalPropertyBasedElement::init("PropertyBasedElement")
448     .method("data", &f_propElementData);
449   NasalCanvas::init("Canvas")
450     .bases<NasalPropertyBasedElement>()
451     .bases<nasal::ObjectRef>()
452     .member("_node_ghost", &elementGetNode<sc::Canvas>)
453     .member("size_x", &sc::Canvas::getSizeX)
454     .member("size_y", &sc::Canvas::getSizeY)
455     .method("_createGroup", &f_canvasCreateGroup)
456     .method("_getGroup", &sc::Canvas::getGroup)
457     .method( "addEventListener",
458              static_cast<bool (sc::Canvas::*)( const std::string&,
459                                                const sc::EventListener& )>
460              (&sc::Canvas::addEventListener) )
461     .method("dispatchEvent", &sc::Canvas::dispatchEvent)
462     .method("setLayout", &sc::Canvas::setLayout);
463
464   canvas_module.set("_newCanvasGhost", f_createCanvas);
465   canvas_module.set("_getCanvasGhost", f_getCanvas);
466
467   NasalElement::init("canvas.Element")
468     .bases<NasalPropertyBasedElement>()
469     .member("_node_ghost", &elementGetNode<sc::Element>)
470     .method("_getParent", &sc::Element::getParent)
471     .method("_getCanvas", &sc::Element::getCanvas)
472     .method("addEventListener", &sc::Element::addEventListener)
473     .method("dispatchEvent", &sc::Element::dispatchEvent)
474     .method("getBoundingBox", &sc::Element::getBoundingBox)
475     .method("getTightBoundingBox", &sc::Element::getTightBoundingBox);
476
477   NasalGroup::init("canvas.Group")
478     .bases<NasalElement>()
479     .method("_createChild", &f_groupCreateChild)
480     .method( "_getChild", &f_groupGetChild)
481     .method("_getElementById", &sc::Group::getElementById);
482   NasalText::init("canvas.Text")
483     .bases<NasalElement>()
484     .method("heightForWidth", &sc::Text::heightForWidth)
485     .method("maxWidth", &sc::Text::maxWidth)
486     .method("getNearestCursor", &sc::Text::getNearestCursor);
487
488   //----------------------------------------------------------------------------
489   // Layouting
490
491   NasalLayoutItem::init("canvas.LayoutItem")
492     .method("getCanvas", &sc::LayoutItem::getCanvas)
493     .method("setCanvas", &sc::LayoutItem::setCanvas)
494     .method("getParent", &sc::LayoutItem::getParent)
495     .method("setParent", &sc::LayoutItem::setParent)
496     .method("sizeHint", &sc::LayoutItem::sizeHint)
497     .method("minimumSize", &sc::LayoutItem::minimumSize)
498     .method("maximumSize", &sc::LayoutItem::maximumSize)
499     .method("hasHeightForWidth", &sc::LayoutItem::hasHeightForWidth)
500     .method("heightForWidth", &sc::LayoutItem::heightForWidth)
501     .method("minimumHeightForWidth", &sc::LayoutItem::minimumHeightForWidth)
502     .method("setVisible", &sc::LayoutItem::setVisible)
503     .method("isVisible", &sc::LayoutItem::isVisible)
504     .method("isExplicitlyHidden", &sc::LayoutItem::isExplicitlyHidden)
505     .method("show", &sc::LayoutItem::show)
506     .method("hide", &sc::LayoutItem::hide)
507     .method("setGeometry", &sc::LayoutItem::setGeometry)
508     .method("geometry", &sc::LayoutItem::geometry);
509   sc::NasalWidget::setupGhost(canvas_module);
510
511   NasalLayout::init("canvas.Layout")
512     .bases<NasalLayoutItem>()
513     .method("addItem", &sc::Layout::addItem)
514     .method("setSpacing", &sc::Layout::setSpacing)
515     .method("spacing", &sc::Layout::spacing)
516     .method("count", &sc::Layout::count)
517     .method("itemAt", &sc::Layout::itemAt)
518     .method("takeAt", &sc::Layout::takeAt)
519     .method("removeItem", &sc::Layout::removeItem)
520     .method("clear", &sc::Layout::clear);
521
522   NasalBoxLayout::init("canvas.BoxLayout")
523     .bases<NasalLayout>()
524     .method("addItem", &f_boxLayoutAddItem)
525     .method("addSpacing", &sc::BoxLayout::addSpacing)
526     .method("addStretch", &f_boxLayoutAddStretch)
527     .method("insertItem", &f_boxLayoutInsertItem)
528     .method("insertSpacing", &sc::BoxLayout::insertSpacing)
529     .method("insertStretch", &f_boxLayoutInsertStretch)
530     .method("setStretch", &sc::BoxLayout::setStretch)
531     .method("setStretchFactor", &sc::BoxLayout::setStretchFactor)
532     .method("stretch", &sc::BoxLayout::stretch);
533
534   canvas_module.createHash("HBoxLayout")
535                .set("new", &f_newAsBase<sc::HBoxLayout, sc::BoxLayout>);
536   canvas_module.createHash("VBoxLayout")
537                .set("new", &f_newAsBase<sc::VBoxLayout, sc::BoxLayout>);
538
539   //----------------------------------------------------------------------------
540   // Window
541
542   NasalWindow::init("canvas.Window")
543     .bases<NasalElement>()
544     .bases<NasalLayoutItem>()
545     .member("_node_ghost", &elementGetNode<sc::Window>)
546     .method("_getCanvasDecoration", &sc::Window::getCanvasDecoration)
547     .method("setLayout", &sc::Window::setLayout);
548
549   canvas_module.set("_newWindowGhost", f_createWindow);
550   canvas_module.set("_getDesktopGhost", f_getDesktop);
551   canvas_module.set("setInputFocus", f_setInputFocus);
552
553   return naNil();
554 }