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 naRef f_grabPointer(const nasal::CallContext& ctx)
192 requireGUIMgr(ctx.c).grabPointer(ctx.requireArg<sc::WindowPtr>(0))
196 naRef f_ungrabPointer(const nasal::CallContext& ctx)
198 requireGUIMgr(ctx.c).ungrabPointer(ctx.requireArg<sc::WindowPtr>(0));
202 static naRef f_groupCreateChild(sc::Group& group, const nasal::CallContext& ctx)
204 return ctx.to_nasal( group.createChild( ctx.requireArg<std::string>(0),
205 ctx.getArg<std::string>(1) ) );
208 static sc::ElementPtr f_groupGetChild(sc::Group& group, SGPropertyNode* node)
210 return group.getChild(node);
213 static void propElementSetData( simgear::PropertyBasedElement& el,
214 const std::string& name,
219 return el.removeDataProp(name);
221 std::string val = nasal::from_nasal<std::string>(c, ref);
225 long val_long = strtol(val.c_str(), &end, 10);
227 return el.setDataProp(name, val_long);
229 double val_double = strtod(val.c_str(), &end);
231 return el.setDataProp(name, val_double);
233 el.setDataProp(name, val);
237 * Accessor for HTML5 data properties.
239 * # set single property:
240 * el.data("myKey", 5);
242 * # set multiple properties
243 * el.data({myProp1: 12, myProp2: "test"});
245 * # get value of properties
246 * el.data("myKey"); # 5
247 * el.data("myProp2"); # "test"
249 * # remove a single property
250 * el.data("myKey", nil);
252 * # remove multiple properties
253 * el.data({myProp1: nil, myProp2: nil});
255 * # set and remove multiple properties
256 * el.data({newProp: "some text...", removeProp: nil});
259 * @see http://api.jquery.com/data/
261 static naRef f_propElementData( simgear::PropertyBasedElement& el,
262 const nasal::CallContext& ctx )
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>());
271 return ctx.to_nasal(&el);
274 std::string name = ctx.getArg<std::string>(0);
279 // name + additional argument -> add/delete property
280 SGPropertyNode* node = el.getDataProp<SGPropertyNode*>(name);
284 return ctx.to_nasal( node->getStringValue() );
288 // only name -> get property
289 propElementSetData(el, name, ctx.c, ctx.requireArg<naRef>(1));
290 return ctx.to_nasal(&el);
297 static naRef f_createCustomEvent(const nasal::CallContext& ctx)
299 std::string const& type = ctx.requireArg<std::string>(0);
303 bool bubbles = false;
304 simgear::StringMap detail;
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");
315 sc::CustomEventPtr(new sc::CustomEvent(type, bubbles, detail))
319 struct CustomEventDetailWrapper:
322 sc::CustomEventPtr _event;
324 CustomEventDetailWrapper(const sc::CustomEventPtr& event):
330 bool _get( const std::string& key,
331 std::string& value_out ) const
336 simgear::StringMap::const_iterator it = _event->detail.find(key);
337 if( it == _event->detail.end() )
340 value_out = it->second;
344 bool _set( const std::string& key,
345 const std::string& value )
350 _event->detail[ key ] = value;
355 static naRef f_customEventGetDetail( sc::CustomEvent& event,
358 return nasal::to_nasal(
360 CustomEventDetailPtr(new CustomEventDetailWrapper(&event))
364 static naRef f_boxLayoutAddItem( sc::BoxLayout& box,
365 const nasal::CallContext& ctx )
367 box.addItem( ctx.requireArg<sc::LayoutItemRef>(0),
369 ctx.getArg<int>(2, sc::AlignFill) );
372 static naRef f_boxLayoutInsertItem( sc::BoxLayout& box,
373 const nasal::CallContext& ctx )
375 box.insertItem( ctx.requireArg<int>(0),
376 ctx.requireArg<sc::LayoutItemRef>(1),
378 ctx.getArg<int>(3, sc::AlignFill) );
382 static naRef f_boxLayoutAddStretch( sc::BoxLayout& box,
383 const nasal::CallContext& ctx )
385 box.addStretch( ctx.getArg<int>(0) );
388 static naRef f_boxLayoutInsertStretch( sc::BoxLayout& box,
389 const nasal::CallContext& ctx )
391 box.insertStretch( ctx.requireArg<int>(0),
392 ctx.getArg<int>(1) );
396 template<class Type, class Base>
397 static naRef f_newAsBase(const nasal::CallContext& ctx)
399 return ctx.to_nasal<Base*>(new Type());
402 naRef initNasalCanvas(naRef globals, naContext c)
404 nasal::Hash globals_module(globals, c),
405 canvas_module = globals_module.createHash("canvas");
407 nasal::Object::setupGhost();
409 //----------------------------------------------------------------------------
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);
421 NasalCustomEvent::init("canvas.CustomEvent")
423 .member("detail", &f_customEventGetDetail, &sc::CustomEvent::setDetail);
424 NasalCustomEventDetail::init("canvas.CustomEventDetail")
425 ._get(&CustomEventDetailWrapper::_get)
426 ._set(&CustomEventDetailWrapper::_set);
428 canvas_module.createHash("CustomEvent")
429 .set("new", &f_createCustomEvent);
431 NasalDeviceEvent::init("canvas.DeviceEvent")
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);
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);
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);
461 //----------------------------------------------------------------------------
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);
483 canvas_module.set("_newCanvasGhost", f_createCanvas);
484 canvas_module.set("_getCanvasGhost", f_getCanvas);
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);
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);
511 //----------------------------------------------------------------------------
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
518 void (sc::LayoutItem::*f_layoutItemSetContentsMargins)(int, int, int, int)
519 = &sc::LayoutItem::setContentsMargins;
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);
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);
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);
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>);
573 //----------------------------------------------------------------------------
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);
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);