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