]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalCanvas.cxx
Interim windows build fix
[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 naRef f_grabPointer(const nasal::CallContext& ctx)
190 {
191   return ctx.to_nasal(
192     requireGUIMgr(ctx.c).grabPointer(ctx.requireArg<sc::WindowPtr>(0))
193   );
194 }
195
196 naRef f_ungrabPointer(const nasal::CallContext& ctx)
197 {
198   requireGUIMgr(ctx.c).ungrabPointer(ctx.requireArg<sc::WindowPtr>(0));
199   return naNil();
200 }
201
202 static naRef f_groupCreateChild(sc::Group& group, const nasal::CallContext& ctx)
203 {
204   return ctx.to_nasal( group.createChild( ctx.requireArg<std::string>(0),
205                                           ctx.getArg<std::string>(1) ) );
206 }
207
208 static sc::ElementPtr f_groupGetChild(sc::Group& group, SGPropertyNode* node)
209 {
210   return group.getChild(node);
211 }
212
213 static void propElementSetData( simgear::PropertyBasedElement& el,
214                                 const std::string& name,
215                                 naContext c,
216                                 naRef ref )
217 {
218   if( naIsNil(ref) )
219     return el.removeDataProp(name);
220
221   std::string val = nasal::from_nasal<std::string>(c, ref);
222
223   char* end = NULL;
224
225   long val_long = strtol(val.c_str(), &end, 10);
226   if( !*end )
227     return el.setDataProp(name, val_long);
228
229   double val_double = strtod(val.c_str(), &end);
230   if( !*end )
231     return el.setDataProp(name, val_double);
232
233   el.setDataProp(name, val);
234 }
235
236 /**
237  * Accessor for HTML5 data properties.
238  *
239  * # set single property:
240  * el.data("myKey", 5);
241  *
242  * # set multiple properties
243  * el.data({myProp1: 12, myProp2: "test"});
244  *
245  * # get value of properties
246  * el.data("myKey");   # 5
247  * el.data("myProp2"); # "test"
248  *
249  * # remove a single property
250  * el.data("myKey", nil);
251  *
252  * # remove multiple properties
253  * el.data({myProp1: nil, myProp2: nil});
254  *
255  * # set and remove multiple properties
256  * el.data({newProp: "some text...", removeProp: nil});
257  *
258  *
259  * @see http://api.jquery.com/data/
260  */
261 static naRef f_propElementData( simgear::PropertyBasedElement& el,
262                                 const nasal::CallContext& ctx )
263 {
264   if( ctx.isHash(0) )
265   {
266     // Add/delete properties given as hash
267     nasal::Hash obj = ctx.requireArg<nasal::Hash>(0);
268     for(nasal::Hash::iterator it = obj.begin(); it != obj.end(); ++it)
269       propElementSetData(el, it->getKey(), ctx.c, it->getValue<naRef>());
270
271     return ctx.to_nasal(&el);
272   }
273
274   std::string name = ctx.getArg<std::string>(0);
275   if( !name.empty() )
276   {
277     if( ctx.argc == 1 )
278     {
279       // name + additional argument -> add/delete property
280       SGPropertyNode* node = el.getDataProp<SGPropertyNode*>(name);
281       if( !node )
282         return naNil();
283
284       return ctx.to_nasal( node->getStringValue() );
285     }
286     else
287     {
288       // only name -> get property
289       propElementSetData(el, name, ctx.c, ctx.requireArg<naRef>(1));
290       return ctx.to_nasal(&el);
291     }
292   }
293
294   return naNil();
295 }
296
297 static naRef f_createCustomEvent(const nasal::CallContext& ctx)
298 {
299   std::string const& type = ctx.requireArg<std::string>(0);
300   if( type.empty() )
301     return naNil();
302
303   bool bubbles = false;
304   simgear::StringMap detail;
305   if( ctx.isHash(1) )
306   {
307     nasal::Hash const& cfg = ctx.requireArg<nasal::Hash>(1);
308     naRef na_detail = cfg.get("detail");
309     if( naIsHash(na_detail) )
310       detail = ctx.from_nasal<simgear::StringMap>(na_detail);
311     bubbles = cfg.get<bool>("bubbles");
312   }
313
314   return ctx.to_nasal(
315     sc::CustomEventPtr(new sc::CustomEvent(type, bubbles, detail))
316   );
317 }
318
319 struct CustomEventDetailWrapper:
320   public SGReferenced
321 {
322   sc::CustomEventPtr _event;
323
324   CustomEventDetailWrapper(const sc::CustomEventPtr& event):
325     _event(event)
326   {
327
328   }
329
330   bool _get( const std::string& key,
331              std::string& value_out ) const
332   {
333     if( !_event )
334       return false;
335
336     simgear::StringMap::const_iterator it = _event->detail.find(key);
337     if( it == _event->detail.end() )
338       return false;
339
340     value_out = it->second;
341     return true;
342   }
343
344   bool _set( const std::string& key,
345              const std::string& value )
346   {
347     if( !_event )
348       return false;
349
350     _event->detail[ key ] = value;
351     return true;
352   }
353 };
354
355 static naRef f_customEventGetDetail( sc::CustomEvent& event,
356                                      naContext c )
357 {
358   return nasal::to_nasal(
359     c,
360     CustomEventDetailPtr(new CustomEventDetailWrapper(&event))
361   );
362 }
363
364 static naRef f_boxLayoutAddItem( sc::BoxLayout& box,
365                                  const nasal::CallContext& ctx )
366 {
367   box.addItem( ctx.requireArg<sc::LayoutItemRef>(0),
368                ctx.getArg<int>(1),
369                ctx.getArg<int>(2, sc::AlignFill) );
370   return naNil();
371 }
372 static naRef f_boxLayoutInsertItem( sc::BoxLayout& box,
373                                     const nasal::CallContext& ctx )
374 {
375   box.insertItem( ctx.requireArg<int>(0),
376                   ctx.requireArg<sc::LayoutItemRef>(1),
377                   ctx.getArg<int>(2),
378                   ctx.getArg<int>(3, sc::AlignFill) );
379   return naNil();
380 }
381
382 static naRef f_boxLayoutAddStretch( sc::BoxLayout& box,
383                                     const nasal::CallContext& ctx )
384 {
385   box.addStretch( ctx.getArg<int>(0) );
386   return naNil();
387 }
388 static naRef f_boxLayoutInsertStretch( sc::BoxLayout& box,
389                                        const nasal::CallContext& ctx )
390 {
391   box.insertStretch( ctx.requireArg<int>(0),
392                      ctx.getArg<int>(1) );
393   return naNil();
394 }
395
396 template<class Type, class Base>
397 static naRef f_newAsBase(const nasal::CallContext& ctx)
398 {
399   return ctx.to_nasal<Base*>(new Type());
400 }
401
402 naRef initNasalCanvas(naRef globals, naContext c)
403 {
404   nasal::Hash globals_module(globals, c),
405               canvas_module = globals_module.createHash("canvas");
406
407   nasal::Object::setupGhost();
408
409   //----------------------------------------------------------------------------
410   // Events
411
412   using osgGA::GUIEventAdapter;
413   NasalEvent::init("canvas.Event")
414     .member("type", &sc::Event::getTypeString)
415     .member("target", &sc::Event::getTarget)
416     .member("currentTarget", &sc::Event::getCurrentTarget)
417     .member("defaultPrevented", &sc::Event::defaultPrevented)
418     .method("stopPropagation", &sc::Event::stopPropagation)
419     .method("preventDefault", &sc::Event::preventDefault);
420
421   NasalCustomEvent::init("canvas.CustomEvent")
422     .bases<NasalEvent>()
423     .member("detail", &f_customEventGetDetail, &sc::CustomEvent::setDetail);
424   NasalCustomEventDetail::init("canvas.CustomEventDetail")
425     ._get(&CustomEventDetailWrapper::_get)
426     ._set(&CustomEventDetailWrapper::_set);
427
428   canvas_module.createHash("CustomEvent")
429                .set("new", &f_createCustomEvent);
430
431   NasalDeviceEvent::init("canvas.DeviceEvent")
432     .bases<NasalEvent>()
433     .member("modifiers", &sc::DeviceEvent::getModifiers)
434     .member("ctrlKey", &sc::DeviceEvent::ctrlKey)
435     .member("shiftKey", &sc::DeviceEvent::shiftKey)
436     .member("altKey",  &sc::DeviceEvent::altKey)
437     .member("metaKey",  &sc::DeviceEvent::metaKey);
438
439   NasalKeyboardEvent::init("canvas.KeyboardEvent")
440     .bases<NasalDeviceEvent>()
441     .member("key", &sc::KeyboardEvent::key)
442     .member("location", &sc::KeyboardEvent::location)
443     .member("repeat", &sc::KeyboardEvent::repeat)
444     .member("charCode", &sc::KeyboardEvent::charCode)
445     .member("keyCode", &sc::KeyboardEvent::keyCode);
446
447   NasalMouseEvent::init("canvas.MouseEvent")
448     .bases<NasalDeviceEvent>()
449     .member("screenX", &sc::MouseEvent::getScreenX)
450     .member("screenY", &sc::MouseEvent::getScreenY)
451     .member("clientX", &sc::MouseEvent::getClientX)
452     .member("clientY", &sc::MouseEvent::getClientY)
453     .member("localX", &sc::MouseEvent::getLocalX)
454     .member("localY", &sc::MouseEvent::getLocalY)
455     .member("deltaX", &sc::MouseEvent::getDeltaX)
456     .member("deltaY", &sc::MouseEvent::getDeltaY)
457     .member("button", &sc::MouseEvent::getButton)
458     .member("buttons", &sc::MouseEvent::getButtonMask)
459     .member("click_count", &sc::MouseEvent::getCurrentClickCount);
460
461   //----------------------------------------------------------------------------
462   // Canvas & elements
463
464   NasalPropertyBasedElement::init("PropertyBasedElement")
465     .method("data", &f_propElementData);
466   NasalCanvas::init("Canvas")
467     .bases<NasalPropertyBasedElement>()
468     .bases<nasal::ObjectRef>()
469     .member("_node_ghost", &elementGetNode<sc::Canvas>)
470     .member("size_x", &sc::Canvas::getSizeX)
471     .member("size_y", &sc::Canvas::getSizeY)
472     .method("_createGroup", &f_canvasCreateGroup)
473     .method("_getGroup", &sc::Canvas::getGroup)
474     .method( "addEventListener",
475              static_cast<bool (sc::Canvas::*)( const std::string&,
476                                                const sc::EventListener& )>
477              (&sc::Canvas::addEventListener) )
478     .method("dispatchEvent", &sc::Canvas::dispatchEvent)
479     .method("setLayout", &sc::Canvas::setLayout)
480     .method("setFocusElement", &sc::Canvas::setFocusElement)
481     .method("clearFocusElement", &sc::Canvas::clearFocusElement);
482
483   canvas_module.set("_newCanvasGhost", f_createCanvas);
484   canvas_module.set("_getCanvasGhost", f_getCanvas);
485
486   NasalElement::init("canvas.Element")
487     .bases<NasalPropertyBasedElement>()
488     .member("_node_ghost", &elementGetNode<sc::Element>)
489     .method("_getParent", &sc::Element::getParent)
490     .method("_getCanvas", &sc::Element::getCanvas)
491     .method("addEventListener", &sc::Element::addEventListener)
492     .method("setFocus", &sc::Element::setFocus)
493     .method("dispatchEvent", &sc::Element::dispatchEvent)
494     .method("getBoundingBox", &sc::Element::getBoundingBox)
495     .method("getTightBoundingBox", &sc::Element::getTightBoundingBox);
496
497   NasalGroup::init("canvas.Group")
498     .bases<NasalElement>()
499     .method("_createChild", &f_groupCreateChild)
500     .method( "_getChild", &f_groupGetChild)
501     .method("_getElementById", &sc::Group::getElementById);
502   NasalText::init("canvas.Text")
503     .bases<NasalElement>()
504     .method("heightForWidth", &sc::Text::heightForWidth)
505     .method("maxWidth", &sc::Text::maxWidth)
506     .method("lineCount", &sc::Text::lineCount)
507     .method("lineLength", &sc::Text::lineLength)
508     .method("getNearestCursor", &sc::Text::getNearestCursor)
509     .method("getCursorPos", &sc::Text::getCursorPos);
510
511   //----------------------------------------------------------------------------
512   // Layouting
513
514 #define ALIGN_ENUM_MAPPING(key, val, comment) canvas_module.set(#key, sc::key);
515 #  include <simgear/canvas/layout/AlignFlag_values.hxx>
516 #undef ALIGN_ENUM_MAPPING
517
518   void (sc::LayoutItem::*f_layoutItemSetContentsMargins)(int, int, int, int)
519     = &sc::LayoutItem::setContentsMargins;
520
521   NasalLayoutItem::init("canvas.LayoutItem")
522     .method("getCanvas", &sc::LayoutItem::getCanvas)
523     .method("setCanvas", &sc::LayoutItem::setCanvas)
524     .method("getParent", &sc::LayoutItem::getParent)
525     .method("setParent", &sc::LayoutItem::setParent)
526     .method("setContentsMargins", f_layoutItemSetContentsMargins)
527     .method("setContentsMargin", &sc::LayoutItem::setContentsMargin)
528     .method("sizeHint", &sc::LayoutItem::sizeHint)
529     .method("minimumSize", &sc::LayoutItem::minimumSize)
530     .method("maximumSize", &sc::LayoutItem::maximumSize)
531     .method("hasHeightForWidth", &sc::LayoutItem::hasHeightForWidth)
532     .method("heightForWidth", &sc::LayoutItem::heightForWidth)
533     .method("minimumHeightForWidth", &sc::LayoutItem::minimumHeightForWidth)
534     .method("setAlignment", &sc::LayoutItem::setAlignment)
535     .method("alignment", &sc::LayoutItem::alignment)
536     .method("setVisible", &sc::LayoutItem::setVisible)
537     .method("isVisible", &sc::LayoutItem::isVisible)
538     .method("isExplicitlyHidden", &sc::LayoutItem::isExplicitlyHidden)
539     .method("show", &sc::LayoutItem::show)
540     .method("hide", &sc::LayoutItem::hide)
541     .method("setGeometry", &sc::LayoutItem::setGeometry)
542     .method("geometry", &sc::LayoutItem::geometry);
543   sc::NasalWidget::setupGhost(canvas_module);
544
545   NasalLayout::init("canvas.Layout")
546     .bases<NasalLayoutItem>()
547     .method("addItem", &sc::Layout::addItem)
548     .method("setSpacing", &sc::Layout::setSpacing)
549     .method("spacing", &sc::Layout::spacing)
550     .method("count", &sc::Layout::count)
551     .method("itemAt", &sc::Layout::itemAt)
552     .method("takeAt", &sc::Layout::takeAt)
553     .method("removeItem", &sc::Layout::removeItem)
554     .method("clear", &sc::Layout::clear);
555
556   NasalBoxLayout::init("canvas.BoxLayout")
557     .bases<NasalLayout>()
558     .method("addItem", &f_boxLayoutAddItem)
559     .method("addSpacing", &sc::BoxLayout::addSpacing)
560     .method("addStretch", &f_boxLayoutAddStretch)
561     .method("insertItem", &f_boxLayoutInsertItem)
562     .method("insertSpacing", &sc::BoxLayout::insertSpacing)
563     .method("insertStretch", &f_boxLayoutInsertStretch)
564     .method("setStretch", &sc::BoxLayout::setStretch)
565     .method("setStretchFactor", &sc::BoxLayout::setStretchFactor)
566     .method("stretch", &sc::BoxLayout::stretch);
567
568   canvas_module.createHash("HBoxLayout")
569                .set("new", &f_newAsBase<sc::HBoxLayout, sc::BoxLayout>);
570   canvas_module.createHash("VBoxLayout")
571                .set("new", &f_newAsBase<sc::VBoxLayout, sc::BoxLayout>);
572
573   //----------------------------------------------------------------------------
574   // Window
575
576   NasalWindow::init("canvas.Window")
577     .bases<NasalElement>()
578     .bases<NasalLayoutItem>()
579     .member("_node_ghost", &elementGetNode<sc::Window>)
580     .method("_getCanvasDecoration", &sc::Window::getCanvasDecoration)
581     .method("setLayout", &sc::Window::setLayout);
582
583   canvas_module.set("_newWindowGhost", f_createWindow);
584   canvas_module.set("_getDesktopGhost", f_getDesktop);
585   canvas_module.set("setInputFocus", f_setInputFocus);
586   canvas_module.set("grabPointer", f_grabPointer);
587   canvas_module.set("ungrabPointer", f_ungrabPointer);
588
589   return naNil();
590 }