]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalCanvas.cxx
Canvas: expose layouting to Nasal.
[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/MouseEvent.hxx>
43
44 #include <simgear/nasal/cppbind/from_nasal.hxx>
45 #include <simgear/nasal/cppbind/to_nasal.hxx>
46 #include <simgear/nasal/cppbind/NasalHash.hxx>
47 #include <simgear/nasal/cppbind/Ghost.hxx>
48
49 extern naRef propNodeGhostCreate(naContext c, SGPropertyNode* n);
50
51 namespace sc = simgear::canvas;
52
53 template<class Element>
54 naRef elementGetNode(Element& element, naContext c)
55 {
56   return propNodeGhostCreate(c, element.getProps());
57 }
58
59 typedef nasal::Ghost<sc::EventPtr> NasalEvent;
60 typedef nasal::Ghost<sc::CustomEventPtr> NasalCustomEvent;
61 typedef nasal::Ghost<sc::MouseEventPtr> NasalMouseEvent;
62
63 struct CustomEventDetailWrapper;
64 typedef SGSharedPtr<CustomEventDetailWrapper> CustomEventDetailPtr;
65 typedef nasal::Ghost<CustomEventDetailPtr> NasalCustomEventDetail;
66
67 typedef nasal::Ghost<simgear::PropertyBasedElementPtr> NasalPropertyBasedElement;
68 typedef nasal::Ghost<sc::CanvasPtr> NasalCanvas;
69 typedef nasal::Ghost<sc::ElementPtr> NasalElement;
70 typedef nasal::Ghost<sc::GroupPtr> NasalGroup;
71 typedef nasal::Ghost<sc::TextPtr> NasalText;
72
73 typedef nasal::Ghost<sc::LayoutItemRef> NasalLayoutItem;
74 typedef nasal::Ghost<sc::LayoutRef> NasalLayout;
75
76 typedef nasal::Ghost<sc::WindowWeakPtr> NasalWindow;
77
78 naRef to_nasal_helper(naContext c, const osg::BoundingBox& bb)
79 {
80   std::vector<float> bb_vec(4);
81   bb_vec[0] = bb._min.x();
82   bb_vec[1] = bb._min.y();
83   bb_vec[2] = bb._max.x();
84   bb_vec[3] = bb._max.y();
85
86   return nasal::to_nasal(c, bb_vec);
87 }
88
89 SGPropertyNode* from_nasal_helper(naContext c, naRef ref, SGPropertyNode**)
90 {
91   SGPropertyNode* props = ghostToPropNode(ref);
92   if( !props )
93     naRuntimeError(c, "Not a SGPropertyNode ghost.");
94
95   return props;
96 }
97
98 sc::CanvasWeakPtr from_nasal_helper(naContext c, naRef ref, sc::CanvasWeakPtr const*)
99 {
100   return nasal::from_nasal<sc::CanvasPtr>(c, ref);
101 }
102
103 CanvasMgr& requireCanvasMgr(naContext c)
104 {
105   CanvasMgr* canvas_mgr =
106     static_cast<CanvasMgr*>(globals->get_subsystem("Canvas"));
107   if( !canvas_mgr )
108     naRuntimeError(c, "Failed to get Canvas subsystem");
109
110   return *canvas_mgr;
111 }
112
113 GUIMgr& requireGUIMgr(naContext c)
114 {
115   GUIMgr* mgr =
116     static_cast<GUIMgr*>(globals->get_subsystem("CanvasGUI"));
117   if( !mgr )
118     naRuntimeError(c, "Failed to get CanvasGUI subsystem");
119
120   return *mgr;
121 }
122
123 /**
124  * Create new Canvas and get ghost for it.
125  */
126 static naRef f_createCanvas(const nasal::CallContext& ctx)
127 {
128   return NasalCanvas::create(ctx.c, requireCanvasMgr(ctx.c).createCanvas());
129 }
130
131 /**
132  * Create new Window and get ghost for it.
133  */
134 static naRef f_createWindow(const nasal::CallContext& ctx)
135 {
136   return NasalWindow::create
137   (
138     ctx.c,
139     requireGUIMgr(ctx.c).createWindow( ctx.getArg<std::string>(0) )
140   );
141 }
142
143 /**
144  * Get ghost for existing Canvas.
145  */
146 static naRef f_getCanvas(naContext c, naRef me, int argc, naRef* args)
147 {
148   nasal::CallContext ctx(c, argc, args);
149   SGPropertyNode& props = *ctx.requireArg<SGPropertyNode*>(0);
150   CanvasMgr& canvas_mgr = requireCanvasMgr(c);
151
152   sc::CanvasPtr canvas;
153   if( canvas_mgr.getPropertyRoot() == props.getParent() )
154   {
155     // get a canvas specified by its root node
156     canvas = canvas_mgr.getCanvas( props.getIndex() );
157     if( !canvas || canvas->getProps() != &props )
158       return naNil();
159   }
160   else
161   {
162     // get a canvas by name
163     if( props.hasValue("name") )
164       canvas = canvas_mgr.getCanvas( props.getStringValue("name") );
165     else if( props.hasValue("index") )
166       canvas = canvas_mgr.getCanvas( props.getIntValue("index") );
167   }
168
169   return NasalCanvas::create(c, canvas);
170 }
171
172 naRef f_canvasCreateGroup(sc::Canvas& canvas, const nasal::CallContext& ctx)
173 {
174   return NasalGroup::create
175   (
176     ctx.c,
177     canvas.createGroup( ctx.getArg<std::string>(0) )
178   );
179 }
180
181 /**
182  * Get group containing all gui windows
183  */
184 naRef f_getDesktop(naContext c, naRef me, int argc, naRef* args)
185 {
186   return NasalGroup::create(c, requireGUIMgr(c).getDesktop());
187 }
188
189 naRef f_groupCreateChild(sc::Group& group, const nasal::CallContext& ctx)
190 {
191   return NasalElement::create
192   (
193     ctx.c,
194     group.createChild( ctx.requireArg<std::string>(0),
195                        ctx.getArg<std::string>(1) )
196   );
197 }
198
199 naRef f_groupGetChild(sc::Group& group, const nasal::CallContext& ctx)
200 {
201   return NasalElement::create
202   (
203     ctx.c,
204     group.getChild( ctx.requireArg<SGPropertyNode*>(0) )
205   );
206 }
207
208 naRef f_groupGetElementById(sc::Group& group, const nasal::CallContext& ctx)
209 {
210   return NasalElement::create
211   (
212     ctx.c,
213     group.getElementById( ctx.requireArg<std::string>(0) )
214   );
215 }
216
217 static void propElementSetData( simgear::PropertyBasedElement& el,
218                                 const std::string& name,
219                                 naContext c,
220                                 naRef ref )
221 {
222   if( naIsNil(ref) )
223     return el.removeDataProp(name);
224
225   std::string val = nasal::from_nasal<std::string>(c, ref);
226
227   char* end = NULL;
228
229   long val_long = strtol(val.c_str(), &end, 10);
230   if( !*end )
231     return el.setDataProp(name, val_long);
232
233   double val_double = strtod(val.c_str(), &end);
234   if( !*end )
235     return el.setDataProp(name, val_double);
236
237   el.setDataProp(name, val);
238 }
239
240 /**
241  * Accessor for HTML5 data properties.
242  *
243  * # set single property:
244  * el.data("myKey", 5);
245  *
246  * # set multiple properties
247  * el.data({myProp1: 12, myProp2: "test"});
248  *
249  * # get value of properties
250  * el.data("myKey");   # 5
251  * el.data("myProp2"); # "test"
252  *
253  * # remove a single property
254  * el.data("myKey", nil);
255  *
256  * # remove multiple properties
257  * el.data({myProp1: nil, myProp2: nil});
258  *
259  * # set and remove multiple properties
260  * el.data({newProp: "some text...", removeProp: nil});
261  *
262  *
263  * @see http://api.jquery.com/data/
264  */
265 static naRef f_propElementData( simgear::PropertyBasedElement& el,
266                                 const nasal::CallContext& ctx )
267 {
268   if( ctx.isHash(0) )
269   {
270     // Add/delete properties given as hash
271     nasal::Hash obj = ctx.requireArg<nasal::Hash>(0);
272     for(nasal::Hash::iterator it = obj.begin(); it != obj.end(); ++it)
273       propElementSetData(el, it->getKey(), ctx.c, it->getValue<naRef>());
274
275     return ctx.to_nasal(&el);
276   }
277
278   std::string name = ctx.getArg<std::string>(0);
279   if( !name.empty() )
280   {
281     if( ctx.argc == 1 )
282     {
283       // name + additional argument -> add/delete property
284       SGPropertyNode* node = el.getDataProp<SGPropertyNode*>(name);
285       if( !node )
286         return naNil();
287
288       return ctx.to_nasal( node->getStringValue() );
289     }
290     else
291     {
292       // only name -> get property
293       propElementSetData(el, name, ctx.c, ctx.requireArg<naRef>(1));
294       return ctx.to_nasal(&el);
295     }
296   }
297
298   return naNil();
299 }
300
301 template<int Mask>
302 naRef f_eventGetModifier(sc::MouseEvent& event, naContext)
303 {
304   return naNum((event.getModifiers() & Mask) != 0);
305 }
306
307 static naRef f_createCustomEvent(const nasal::CallContext& ctx)
308 {
309   std::string const& type = ctx.requireArg<std::string>(0);
310   if( type.empty() )
311     return naNil();
312
313   simgear::StringMap detail;
314   if( ctx.isHash(1) )
315   {
316     nasal::Hash const& cfg = ctx.requireArg<nasal::Hash>(1);
317     naRef na_detail = cfg.get("detail");
318     if( naIsHash(na_detail) )
319       detail = ctx.from_nasal<simgear::StringMap>(na_detail);
320   }
321
322   return NasalCustomEvent::create(
323     ctx.c,
324     sc::CustomEventPtr(new sc::CustomEvent(type, detail))
325   );
326 }
327
328 struct CustomEventDetailWrapper:
329   public SGReferenced
330 {
331   sc::CustomEventPtr _event;
332
333   CustomEventDetailWrapper(const sc::CustomEventPtr& event):
334     _event(event)
335   {
336
337   }
338
339   bool _get( const std::string& key,
340              std::string& value_out ) const
341   {
342     if( !_event )
343       return false;
344
345     simgear::StringMap::const_iterator it = _event->detail.find(key);
346     if( it == _event->detail.end() )
347       return false;
348
349     value_out = it->second;
350     return true;
351   }
352
353   bool _set( const std::string& key,
354              const std::string& value )
355   {
356     if( !_event )
357       return false;
358
359     _event->detail[ key ] = value;
360     return true;
361   }
362 };
363
364 static naRef f_customEventGetDetail( sc::CustomEvent& event,
365                                      naContext c )
366 {
367   return nasal::to_nasal(
368     c,
369     CustomEventDetailPtr(new CustomEventDetailWrapper(&event))
370   );
371 }
372
373 naRef to_nasal_helper(naContext c, const sc::ElementWeakPtr& el)
374 {
375   return NasalElement::create(c, el.lock());
376 }
377
378 naRef to_nasal_helper(naContext c, const sc::CanvasWeakPtr& canvas)
379 {
380   return NasalCanvas::create(c, canvas.lock());
381 }
382
383 template<class Type, class Base>
384 static naRef f_newAsBase(const nasal::CallContext& ctx)
385 {
386   return ctx.to_nasal<Base*>(new Type());
387 }
388
389 naRef initNasalCanvas(naRef globals, naContext c)
390 {
391   nasal::Hash globals_module(globals, c),
392               canvas_module = globals_module.createHash("canvas");
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   NasalMouseEvent::init("canvas.MouseEvent")
415     .bases<NasalEvent>()
416     .member("screenX", &sc::MouseEvent::getScreenX)
417     .member("screenY", &sc::MouseEvent::getScreenY)
418     .member("clientX", &sc::MouseEvent::getClientX)
419     .member("clientY", &sc::MouseEvent::getClientY)
420     .member("localX", &sc::MouseEvent::getLocalX)
421     .member("localY", &sc::MouseEvent::getLocalY)
422     .member("deltaX", &sc::MouseEvent::getDeltaX)
423     .member("deltaY", &sc::MouseEvent::getDeltaY)
424     .member("button", &sc::MouseEvent::getButton)
425     .member("buttons", &sc::MouseEvent::getButtonMask)
426     .member("modifiers", &sc::MouseEvent::getModifiers)
427     .member("ctrlKey", &f_eventGetModifier<GUIEventAdapter::MODKEY_CTRL>)
428     .member("shiftKey", &f_eventGetModifier<GUIEventAdapter::MODKEY_SHIFT>)
429     .member("altKey", &f_eventGetModifier<GUIEventAdapter::MODKEY_ALT>)
430     .member("metaKey", &f_eventGetModifier<GUIEventAdapter::MODKEY_META>)
431     .member("click_count", &sc::MouseEvent::getCurrentClickCount);
432
433   //----------------------------------------------------------------------------
434   // Canvas & elements
435
436   NasalPropertyBasedElement::init("PropertyBasedElement")
437     .method("data", &f_propElementData);
438   NasalCanvas::init("Canvas")
439     .bases<NasalPropertyBasedElement>()
440     .member("_node_ghost", &elementGetNode<sc::Canvas>)
441     .member("size_x", &sc::Canvas::getSizeX)
442     .member("size_y", &sc::Canvas::getSizeY)
443     .method("_createGroup", &f_canvasCreateGroup)
444     .method("_getGroup", &sc::Canvas::getGroup)
445     .method("addEventListener", &sc::Canvas::addEventListener)
446     .method("dispatchEvent", &sc::Canvas::dispatchEvent);
447
448   canvas_module.set("_newCanvasGhost", f_createCanvas);
449   canvas_module.set("_getCanvasGhost", f_getCanvas);
450
451   NasalElement::init("canvas.Element")
452     .bases<NasalPropertyBasedElement>()
453     .member("_node_ghost", &elementGetNode<sc::Element>)
454     .method("_getParent", &sc::Element::getParent)
455     .method("_getCanvas", &sc::Element::getCanvas)
456     .method("addEventListener", &sc::Element::addEventListener)
457     .method("dispatchEvent", &sc::Element::dispatchEvent)
458     .method("getBoundingBox", &sc::Element::getBoundingBox)
459     .method("getTightBoundingBox", &sc::Element::getTightBoundingBox);
460   NasalGroup::init("canvas.Group")
461     .bases<NasalElement>()
462     .method("_createChild", &f_groupCreateChild)
463     .method("_getChild", &f_groupGetChild)
464     .method("_getElementById", &f_groupGetElementById);
465   NasalText::init("canvas.Text")
466     .bases<NasalElement>()
467     .method("getNearestCursor", &sc::Text::getNearestCursor);
468
469   //----------------------------------------------------------------------------
470   // Layouting
471
472   NasalLayoutItem::init("canvas.LayoutItem")
473     .method("setCanvas", &sc::LayoutItem::setCanvas);
474   sc::NasalWidget::setupGhost(canvas_module);
475
476   NasalLayout::init("canvas.Layout")
477     .bases<NasalLayoutItem>()
478     .method("addItem", &sc::Layout::addItem);
479
480   canvas_module.createHash("HBoxLayout")
481                .set("new", &f_newAsBase<sc::HBoxLayout, sc::Layout>);
482
483   //----------------------------------------------------------------------------
484   // Window
485
486   NasalWindow::init("canvas.Window")
487     .bases<NasalElement>()
488     .member("_node_ghost", &elementGetNode<sc::Window>)
489     .method("_getCanvasDecoration", &sc::Window::getCanvasDecoration)
490     .method("setLayout", &sc::Window::setLayout);
491
492   canvas_module.set("_newWindowGhost", f_createWindow);
493   canvas_module.set("_getDesktopGhost", f_getDesktop);
494
495   return naNil();
496 }