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