1 // NasalCanvas.cxx -- expose Canvas classes to Nasal
3 // Written by James Turner, started 2012.
5 // Copyright (C) 2012 James Turner
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.
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.
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.
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>
31 #include <osgGA/GUIEventAdapter>
33 #include <simgear/sg_inlines.h>
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>
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>
50 extern naRef propNodeGhostCreate(naContext c, SGPropertyNode* n);
52 namespace sc = simgear::canvas;
54 template<class Element>
55 naRef elementGetNode(Element& element, naContext c)
57 return propNodeGhostCreate(c, element.getProps());
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;
66 struct CustomEventDetailWrapper;
67 typedef SGSharedPtr<CustomEventDetailWrapper> CustomEventDetailPtr;
68 typedef nasal::Ghost<CustomEventDetailPtr> NasalCustomEventDetail;
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;
76 typedef nasal::Ghost<sc::LayoutItemRef> NasalLayoutItem;
77 typedef nasal::Ghost<sc::LayoutRef> NasalLayout;
78 typedef nasal::Ghost<sc::BoxLayoutRef> NasalBoxLayout;
80 typedef nasal::Ghost<sc::WindowPtr> NasalWindow;
82 naRef to_nasal_helper(naContext c, const osg::BoundingBox& bb)
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();
90 return nasal::to_nasal(c, bb_vec);
93 SGPropertyNode* from_nasal_helper(naContext c, naRef ref, SGPropertyNode**)
95 SGPropertyNode* props = ghostToPropNode(ref);
97 naRuntimeError(c, "Not a SGPropertyNode ghost.");
102 CanvasMgr& requireCanvasMgr(naContext c)
104 CanvasMgr* canvas_mgr =
105 static_cast<CanvasMgr*>(globals->get_subsystem("Canvas"));
107 naRuntimeError(c, "Failed to get Canvas subsystem");
112 GUIMgr& requireGUIMgr(naContext c)
115 static_cast<GUIMgr*>(globals->get_subsystem("CanvasGUI"));
117 naRuntimeError(c, "Failed to get CanvasGUI subsystem");
123 * Create new Canvas and get ghost for it.
125 static naRef f_createCanvas(const nasal::CallContext& ctx)
127 return ctx.to_nasal(requireCanvasMgr(ctx.c).createCanvas());
131 * Create new Window and get ghost for it.
133 static naRef f_createWindow(const nasal::CallContext& ctx)
135 return nasal::to_nasal<sc::WindowWeakPtr>
138 requireGUIMgr(ctx.c).createWindow( ctx.getArg<std::string>(0) )
143 * Get ghost for existing Canvas.
145 static naRef f_getCanvas(const nasal::CallContext& ctx)
147 SGPropertyNode& props = *ctx.requireArg<SGPropertyNode*>(0);
148 CanvasMgr& canvas_mgr = requireCanvasMgr(ctx.c);
150 sc::CanvasPtr canvas;
151 if( canvas_mgr.getPropertyRoot() == props.getParent() )
153 // get a canvas specified by its root node
154 canvas = canvas_mgr.getCanvas( props.getIndex() );
155 if( !canvas || canvas->getProps() != &props )
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") );
167 return ctx.to_nasal(canvas);
170 naRef f_canvasCreateGroup(sc::Canvas& canvas, const nasal::CallContext& ctx)
172 return ctx.to_nasal( canvas.createGroup(ctx.getArg<std::string>(0)) );
176 * Get group containing all gui windows
178 naRef f_getDesktop(naContext c, naRef me, int argc, naRef* args)
180 return nasal::to_nasal(c, requireGUIMgr(c).getDesktop());
183 naRef f_setInputFocus(const nasal::CallContext& ctx)
185 requireGUIMgr(ctx.c).setInputFocus(ctx.requireArg<sc::WindowPtr>(0));
189 static naRef f_groupCreateChild(sc::Group& group, const nasal::CallContext& ctx)
191 return ctx.to_nasal( group.createChild( ctx.requireArg<std::string>(0),
192 ctx.getArg<std::string>(1) ) );
195 static sc::ElementPtr f_groupGetChild(sc::Group& group, SGPropertyNode* node)
197 return group.getChild(node);
200 static void propElementSetData( simgear::PropertyBasedElement& el,
201 const std::string& name,
206 return el.removeDataProp(name);
208 std::string val = nasal::from_nasal<std::string>(c, ref);
212 long val_long = strtol(val.c_str(), &end, 10);
214 return el.setDataProp(name, val_long);
216 double val_double = strtod(val.c_str(), &end);
218 return el.setDataProp(name, val_double);
220 el.setDataProp(name, val);
224 * Accessor for HTML5 data properties.
226 * # set single property:
227 * el.data("myKey", 5);
229 * # set multiple properties
230 * el.data({myProp1: 12, myProp2: "test"});
232 * # get value of properties
233 * el.data("myKey"); # 5
234 * el.data("myProp2"); # "test"
236 * # remove a single property
237 * el.data("myKey", nil);
239 * # remove multiple properties
240 * el.data({myProp1: nil, myProp2: nil});
242 * # set and remove multiple properties
243 * el.data({newProp: "some text...", removeProp: nil});
246 * @see http://api.jquery.com/data/
248 static naRef f_propElementData( simgear::PropertyBasedElement& el,
249 const nasal::CallContext& ctx )
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>());
258 return ctx.to_nasal(&el);
261 std::string name = ctx.getArg<std::string>(0);
266 // name + additional argument -> add/delete property
267 SGPropertyNode* node = el.getDataProp<SGPropertyNode*>(name);
271 return ctx.to_nasal( node->getStringValue() );
275 // only name -> get property
276 propElementSetData(el, name, ctx.c, ctx.requireArg<naRef>(1));
277 return ctx.to_nasal(&el);
284 static naRef f_createCustomEvent(const nasal::CallContext& ctx)
286 std::string const& type = ctx.requireArg<std::string>(0);
290 bool bubbles = false;
291 simgear::StringMap detail;
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");
302 sc::CustomEventPtr(new sc::CustomEvent(type, bubbles, detail))
306 struct CustomEventDetailWrapper:
309 sc::CustomEventPtr _event;
311 CustomEventDetailWrapper(const sc::CustomEventPtr& event):
317 bool _get( const std::string& key,
318 std::string& value_out ) const
323 simgear::StringMap::const_iterator it = _event->detail.find(key);
324 if( it == _event->detail.end() )
327 value_out = it->second;
331 bool _set( const std::string& key,
332 const std::string& value )
337 _event->detail[ key ] = value;
342 static naRef f_customEventGetDetail( sc::CustomEvent& event,
345 return nasal::to_nasal(
347 CustomEventDetailPtr(new CustomEventDetailWrapper(&event))
351 static naRef f_boxLayoutAddItem( sc::BoxLayout& box,
352 const nasal::CallContext& ctx )
354 box.addItem( ctx.requireArg<sc::LayoutItemRef>(0),
356 ctx.getArg<int>(2, sc::AlignFill) );
359 static naRef f_boxLayoutInsertItem( sc::BoxLayout& box,
360 const nasal::CallContext& ctx )
362 box.insertItem( ctx.requireArg<int>(0),
363 ctx.requireArg<sc::LayoutItemRef>(1),
365 ctx.getArg<int>(3, sc::AlignFill) );
369 static naRef f_boxLayoutAddStretch( sc::BoxLayout& box,
370 const nasal::CallContext& ctx )
372 box.addStretch( ctx.getArg<int>(0) );
375 static naRef f_boxLayoutInsertStretch( sc::BoxLayout& box,
376 const nasal::CallContext& ctx )
378 box.insertStretch( ctx.requireArg<int>(0),
379 ctx.getArg<int>(1) );
383 template<class Type, class Base>
384 static naRef f_newAsBase(const nasal::CallContext& ctx)
386 return ctx.to_nasal<Base*>(new Type());
389 naRef initNasalCanvas(naRef globals, naContext c)
391 nasal::Hash globals_module(globals, c),
392 canvas_module = globals_module.createHash("canvas");
394 nasal::Object::setupGhost();
396 //----------------------------------------------------------------------------
399 using osgGA::GUIEventAdapter;
400 NasalEvent::init("canvas.Event")
401 .member("type", &sc::Event::getTypeString)
402 .member("target", &sc::Event::getTarget)
403 .member("currentTarget", &sc::Event::getCurrentTarget)
404 .member("defaultPrevented", &sc::Event::defaultPrevented)
405 .method("stopPropagation", &sc::Event::stopPropagation)
406 .method("preventDefault", &sc::Event::preventDefault);
408 NasalCustomEvent::init("canvas.CustomEvent")
410 .member("detail", &f_customEventGetDetail, &sc::CustomEvent::setDetail);
411 NasalCustomEventDetail::init("canvas.CustomEventDetail")
412 ._get(&CustomEventDetailWrapper::_get)
413 ._set(&CustomEventDetailWrapper::_set);
415 canvas_module.createHash("CustomEvent")
416 .set("new", &f_createCustomEvent);
418 NasalDeviceEvent::init("canvas.DeviceEvent")
420 .member("modifiers", &sc::DeviceEvent::getModifiers)
421 .member("ctrlKey", &sc::DeviceEvent::ctrlKey)
422 .member("shiftKey", &sc::DeviceEvent::shiftKey)
423 .member("altKey", &sc::DeviceEvent::altKey)
424 .member("metaKey", &sc::DeviceEvent::metaKey);
426 NasalKeyboardEvent::init("canvas.KeyboardEvent")
427 .bases<NasalDeviceEvent>()
428 .member("key", &sc::KeyboardEvent::key)
429 .member("location", &sc::KeyboardEvent::location)
430 .member("repeat", &sc::KeyboardEvent::repeat)
431 .member("charCode", &sc::KeyboardEvent::charCode)
432 .member("keyCode", &sc::KeyboardEvent::keyCode);
434 NasalMouseEvent::init("canvas.MouseEvent")
435 .bases<NasalDeviceEvent>()
436 .member("screenX", &sc::MouseEvent::getScreenX)
437 .member("screenY", &sc::MouseEvent::getScreenY)
438 .member("clientX", &sc::MouseEvent::getClientX)
439 .member("clientY", &sc::MouseEvent::getClientY)
440 .member("localX", &sc::MouseEvent::getLocalX)
441 .member("localY", &sc::MouseEvent::getLocalY)
442 .member("deltaX", &sc::MouseEvent::getDeltaX)
443 .member("deltaY", &sc::MouseEvent::getDeltaY)
444 .member("button", &sc::MouseEvent::getButton)
445 .member("buttons", &sc::MouseEvent::getButtonMask)
446 .member("click_count", &sc::MouseEvent::getCurrentClickCount);
448 //----------------------------------------------------------------------------
451 NasalPropertyBasedElement::init("PropertyBasedElement")
452 .method("data", &f_propElementData);
453 NasalCanvas::init("Canvas")
454 .bases<NasalPropertyBasedElement>()
455 .bases<nasal::ObjectRef>()
456 .member("_node_ghost", &elementGetNode<sc::Canvas>)
457 .member("size_x", &sc::Canvas::getSizeX)
458 .member("size_y", &sc::Canvas::getSizeY)
459 .method("_createGroup", &f_canvasCreateGroup)
460 .method("_getGroup", &sc::Canvas::getGroup)
461 .method( "addEventListener",
462 static_cast<bool (sc::Canvas::*)( const std::string&,
463 const sc::EventListener& )>
464 (&sc::Canvas::addEventListener) )
465 .method("dispatchEvent", &sc::Canvas::dispatchEvent)
466 .method("setLayout", &sc::Canvas::setLayout);
468 canvas_module.set("_newCanvasGhost", f_createCanvas);
469 canvas_module.set("_getCanvasGhost", f_getCanvas);
471 NasalElement::init("canvas.Element")
472 .bases<NasalPropertyBasedElement>()
473 .member("_node_ghost", &elementGetNode<sc::Element>)
474 .method("_getParent", &sc::Element::getParent)
475 .method("_getCanvas", &sc::Element::getCanvas)
476 .method("addEventListener", &sc::Element::addEventListener)
477 .method("dispatchEvent", &sc::Element::dispatchEvent)
478 .method("getBoundingBox", &sc::Element::getBoundingBox)
479 .method("getTightBoundingBox", &sc::Element::getTightBoundingBox);
481 NasalGroup::init("canvas.Group")
482 .bases<NasalElement>()
483 .method("_createChild", &f_groupCreateChild)
484 .method( "_getChild", &f_groupGetChild)
485 .method("_getElementById", &sc::Group::getElementById);
486 NasalText::init("canvas.Text")
487 .bases<NasalElement>()
488 .method("heightForWidth", &sc::Text::heightForWidth)
489 .method("maxWidth", &sc::Text::maxWidth)
490 .method("getNearestCursor", &sc::Text::getNearestCursor);
492 //----------------------------------------------------------------------------
495 #define ALIGN_ENUM_MAPPING(key, val, comment) canvas_module.set(#key, sc::key);
496 # include <simgear/canvas/layout/AlignFlag_values.hxx>
497 #undef ALIGN_ENUM_MAPPING
499 void (sc::LayoutItem::*f_layoutItemSetContentsMargins)(int, int, int, int)
500 = &sc::LayoutItem::setContentsMargins;
502 NasalLayoutItem::init("canvas.LayoutItem")
503 .method("getCanvas", &sc::LayoutItem::getCanvas)
504 .method("setCanvas", &sc::LayoutItem::setCanvas)
505 .method("getParent", &sc::LayoutItem::getParent)
506 .method("setParent", &sc::LayoutItem::setParent)
507 .method("setContentsMargins", f_layoutItemSetContentsMargins)
508 .method("setContentsMargin", &sc::LayoutItem::setContentsMargin)
509 .method("sizeHint", &sc::LayoutItem::sizeHint)
510 .method("minimumSize", &sc::LayoutItem::minimumSize)
511 .method("maximumSize", &sc::LayoutItem::maximumSize)
512 .method("hasHeightForWidth", &sc::LayoutItem::hasHeightForWidth)
513 .method("heightForWidth", &sc::LayoutItem::heightForWidth)
514 .method("minimumHeightForWidth", &sc::LayoutItem::minimumHeightForWidth)
515 .method("setAlignment", &sc::LayoutItem::setAlignment)
516 .method("alignment", &sc::LayoutItem::alignment)
517 .method("setVisible", &sc::LayoutItem::setVisible)
518 .method("isVisible", &sc::LayoutItem::isVisible)
519 .method("isExplicitlyHidden", &sc::LayoutItem::isExplicitlyHidden)
520 .method("show", &sc::LayoutItem::show)
521 .method("hide", &sc::LayoutItem::hide)
522 .method("setGeometry", &sc::LayoutItem::setGeometry)
523 .method("geometry", &sc::LayoutItem::geometry);
524 sc::NasalWidget::setupGhost(canvas_module);
526 NasalLayout::init("canvas.Layout")
527 .bases<NasalLayoutItem>()
528 .method("addItem", &sc::Layout::addItem)
529 .method("setSpacing", &sc::Layout::setSpacing)
530 .method("spacing", &sc::Layout::spacing)
531 .method("count", &sc::Layout::count)
532 .method("itemAt", &sc::Layout::itemAt)
533 .method("takeAt", &sc::Layout::takeAt)
534 .method("removeItem", &sc::Layout::removeItem)
535 .method("clear", &sc::Layout::clear);
537 NasalBoxLayout::init("canvas.BoxLayout")
538 .bases<NasalLayout>()
539 .method("addItem", &f_boxLayoutAddItem)
540 .method("addSpacing", &sc::BoxLayout::addSpacing)
541 .method("addStretch", &f_boxLayoutAddStretch)
542 .method("insertItem", &f_boxLayoutInsertItem)
543 .method("insertSpacing", &sc::BoxLayout::insertSpacing)
544 .method("insertStretch", &f_boxLayoutInsertStretch)
545 .method("setStretch", &sc::BoxLayout::setStretch)
546 .method("setStretchFactor", &sc::BoxLayout::setStretchFactor)
547 .method("stretch", &sc::BoxLayout::stretch);
549 canvas_module.createHash("HBoxLayout")
550 .set("new", &f_newAsBase<sc::HBoxLayout, sc::BoxLayout>);
551 canvas_module.createHash("VBoxLayout")
552 .set("new", &f_newAsBase<sc::VBoxLayout, sc::BoxLayout>);
554 //----------------------------------------------------------------------------
557 NasalWindow::init("canvas.Window")
558 .bases<NasalElement>()
559 .bases<NasalLayoutItem>()
560 .member("_node_ghost", &elementGetNode<sc::Window>)
561 .method("_getCanvasDecoration", &sc::Window::getCanvasDecoration)
562 .method("setLayout", &sc::Window::setLayout);
564 canvas_module.set("_newWindowGhost", f_createWindow);
565 canvas_module.set("_getDesktopGhost", f_getDesktop);
566 canvas_module.set("setInputFocus", f_setInputFocus);