]> git.mxchange.org Git - flightgear.git/blob - src/Canvas/gui_mgr.cxx
Canvas window: increase drag accuracy.
[flightgear.git] / src / Canvas / gui_mgr.cxx
1 // Canvas gui/dialog manager
2 //
3 // Copyright (C) 2012  Thomas Geymayer <tomgey@gmail.com>
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 #include "gui_mgr.hxx"
20 #include <Canvas/window.hxx>
21
22 #include <Main/fg_os.hxx>
23 #include <Main/fg_props.hxx>
24 #include <Main/globals.hxx>
25 #include <Viewer/CameraGroup.hxx>
26 #include <Viewer/renderer.hxx>
27
28 #include <simgear/canvas/Canvas.hxx>
29 #include <simgear/canvas/CanvasPlacement.hxx>
30 #include <simgear/scene/util/OsgMath.hxx>
31
32 #include <osg/BlendFunc>
33 #include <osgViewer/Viewer>
34 #include <osgGA/GUIEventHandler>
35
36 #include <boost/bind.hpp>
37 #include <boost/lexical_cast.hpp>
38
39 class DesktopGroup;
40 typedef boost::shared_ptr<DesktopGroup> DesktopPtr;
41 typedef boost::weak_ptr<DesktopGroup> DesktopWeakPtr;
42
43 /**
44  * Event handler
45  */
46 class GUIEventHandler:
47   public osgGA::GUIEventHandler
48 {
49   public:
50     GUIEventHandler(const DesktopWeakPtr& desktop_group);
51
52     bool handle( const osgGA::GUIEventAdapter& ea,
53                  osgGA::GUIActionAdapter&,
54                  osg::Object*,
55                  osg::NodeVisitor* );
56
57   protected:
58     DesktopWeakPtr _desktop;
59 };
60
61 /**
62  * Track a canvas placement on a window
63  */
64 class WindowPlacement:
65   public simgear::canvas::Placement
66 {
67   public:
68     WindowPlacement( SGPropertyNode* node,
69                      canvas::WindowPtr window,
70                      simgear::canvas::CanvasPtr canvas ):
71       Placement(node),
72       _window(window),
73       _canvas(canvas)
74     {}
75
76     /**
77      * Remove placement from window
78      */
79     virtual ~WindowPlacement()
80     {
81       canvas::WindowPtr window = _window.lock();
82       simgear::canvas::CanvasPtr canvas = _canvas.lock();
83
84       if( window && canvas && canvas == window->getCanvasContent().lock() )
85         window->setCanvasContent( simgear::canvas::CanvasPtr() );
86     }
87
88   private:
89     canvas::WindowWeakPtr _window;
90     simgear::canvas::CanvasWeakPtr _canvas;
91 };
92
93 /**
94  * Desktop root group
95  */
96 class DesktopGroup:
97   public simgear::canvas::Group
98 {
99   public:
100     DesktopGroup();
101     bool handleEvent(const osgGA::GUIEventAdapter& ea);
102
103   protected:
104
105     friend class GUIMgr;
106
107     SGPropertyChangeCallback<DesktopGroup> _cb_mouse_mode;
108     bool                                   _handle_events;
109
110     simgear::PropertyObject<int>        _width,
111                                         _height;
112
113     canvas::WindowWeakPtr _last_push,
114                           _last_mouse_over,
115                           _resize_window;
116     uint8_t _resize;
117     int     _last_cursor;
118
119     osg::Vec2 _drag_start;
120     float _last_x,
121           _last_y;
122     double _last_scroll_time;
123
124     bool handleMouse(const osgGA::GUIEventAdapter& ea);
125     void handleResize(int x, int y, int width, int height);
126     void handleMouseMode(SGPropertyNode* node);
127
128     /**
129      *
130      */
131     simgear::canvas::ElementFactory
132     getChildFactory(const std::string& type) const
133     {
134       if( type == "window" )
135         return &Element::create<canvas::Window>;
136
137       return Group::getChildFactory(type);
138     }
139
140     /**
141      *
142      */
143     simgear::canvas::Placements
144     addPlacement(SGPropertyNode* node, simgear::canvas::CanvasPtr canvas)
145     {
146       const std::string& id = node->getStringValue("id");
147
148       simgear::canvas::Placements placements;
149       canvas::WindowPtr window = getChild<canvas::Window>(id);
150       if( window )
151       {
152         window->setCanvasContent(canvas);
153         placements.push_back(
154           simgear::canvas::PlacementPtr(
155             new WindowPlacement(node, window, canvas)
156         ));
157       }
158       return placements;
159     }
160 };
161
162 //------------------------------------------------------------------------------
163 GUIEventHandler::GUIEventHandler(const DesktopWeakPtr& desktop_group):
164   _desktop( desktop_group )
165 {
166
167 }
168
169 //------------------------------------------------------------------------------
170 bool GUIEventHandler::handle( const osgGA::GUIEventAdapter& ea,
171                               osgGA::GUIActionAdapter&,
172                               osg::Object*,
173                               osg::NodeVisitor* )
174 {
175   if( ea.getHandled() )
176     return false;
177
178   DesktopPtr desktop = _desktop.lock();
179   return desktop && desktop->handleEvent(ea);
180 }
181
182 //------------------------------------------------------------------------------
183 DesktopGroup::DesktopGroup():
184   Group(simgear::canvas::CanvasPtr(), fgGetNode("/sim/gui/canvas", true)),
185   _cb_mouse_mode( this,
186                   &DesktopGroup::handleMouseMode,
187                   fgGetNode("/devices/status/mice/mouse[0]/mode") ),
188   _handle_events(true),
189   _width(_node, "size[0]"),
190   _height(_node, "size[1]"),
191   _resize(canvas::Window::NONE),
192   _last_cursor(MOUSE_CURSOR_NONE),
193   _last_x(-1),
194   _last_y(-1),
195   _last_scroll_time(0)
196 {
197   osg::Camera* camera =
198     flightgear::getGUICamera( flightgear::CameraGroup::getDefault() );
199   assert(camera);
200   camera->addChild( getMatrixTransform() );
201
202   simgear::canvas::Canvas::addPlacementFactory
203   (
204     "window",
205     boost::bind(&DesktopGroup::addPlacement, this, _1, _2)
206   );
207
208
209   osg::StateSet* stateSet = _transform->getOrCreateStateSet();
210   stateSet->setDataVariance(osg::Object::STATIC);
211   stateSet->setRenderBinDetails(1000, "RenderBin");
212
213   // speed optimization?
214   stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
215   stateSet->setAttribute(new osg::BlendFunc(
216     osg::BlendFunc::SRC_ALPHA,
217     osg::BlendFunc::ONE_MINUS_SRC_ALPHA)
218   );
219   stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
220   stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
221   stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
222   stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
223
224   _width = _height = -1;
225
226   // Do not change values on reinit
227   _width.node()->setAttribute(SGPropertyNode::PRESERVE, true);
228   _height.node()->setAttribute(SGPropertyNode::PRESERVE, true);
229 }
230
231 //------------------------------------------------------------------------------
232 bool DesktopGroup::handleEvent(const osgGA::GUIEventAdapter& ea)
233 {
234   switch( ea.getEventType() )
235   {
236     case osgGA::GUIEventAdapter::PUSH:
237     case osgGA::GUIEventAdapter::RELEASE:
238 //    case osgGA::GUIEventAdapter::DOUBLECLICK:
239 //    // DOUBLECLICK doesn't seem to be triggered...
240     case osgGA::GUIEventAdapter::DRAG:
241     case osgGA::GUIEventAdapter::MOVE:
242     case osgGA::GUIEventAdapter::SCROLL:
243       return handleMouse(ea);
244     case osgGA::GUIEventAdapter::RESIZE:
245       handleResize( ea.getWindowX(),
246                     ea.getWindowY(),
247                     ea.getWindowWidth(),
248                     ea.getWindowHeight() );
249       return false; // Let other event handlers also consume resize events
250     default:
251       return false;
252   }
253 }
254
255 /*
256 RESIZE AREAS
257 ============
258
259 |   || |      _ inside corner region (L-shaped part inside margin) both
260 |___||_|_ _ _/  directions can be resized (outside only one axis)
261 |   || |     |
262 |   || |
263 |   || |_____|__                  _
264 |   ||       |   } margin_neg      \
265 |    ========|== <-- window border  |_ area where resize
266 |            |   } margin_pos       |  can be initiated
267 |____________|__/                 _/
268 |<- corner ->|
269 */
270 const float resize_margin_pos = 12;
271 const float resize_margin_neg = 2;
272 const float resize_corner = 20;
273
274 //------------------------------------------------------------------------------
275 bool DesktopGroup::handleMouse(const osgGA::GUIEventAdapter& ea)
276 {
277   if( !_transform->getNumChildren() || !_handle_events )
278     return false;
279
280   namespace sc = simgear::canvas;
281   sc::MouseEventPtr event(new sc::MouseEvent(ea));
282
283   event->screen_pos.x() = 0.5 * (ea.getXnormalized() + 1) * _width + 0.5;
284   event->screen_pos.y() = 0.5 * (ea.getYnormalized() + 1) * _height + 0.5;
285   if(    ea.getMouseYOrientation()
286       != osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS )
287     event->screen_pos.y() = _height - event->screen_pos.y();
288
289   event->delta.x() = event->getScreenX() - _last_x;
290   event->delta.y() = event->getScreenY() - _last_y;
291
292   _last_x = event->getScreenX();
293   _last_y = event->getScreenY();
294
295   event->local_pos = event->client_pos = event->screen_pos;
296
297   if( !_resize_window.expired() )
298   {
299     switch( ea.getEventType() )
300     {
301       case osgGA::GUIEventAdapter::RELEASE:
302         _resize_window.lock()->handleResize(canvas::Window::NONE);
303         _resize_window.reset();
304         break;
305       case osgGA::GUIEventAdapter::DRAG:
306         _resize_window.lock()->handleResize( _resize,
307                                              event->screen_pos - _drag_start );
308         return true;
309       default:
310         return false;
311     }
312   }
313
314   canvas::WindowPtr window_at_cursor;
315   for( int i = _transform->getNumChildren() - 1; i >= 0; --i )
316   {
317     osg::Group *element = _transform->getChild(i)->asGroup();
318
319     assert(element);
320     assert(element->getUserData());
321
322     canvas::WindowPtr window =
323       boost::dynamic_pointer_cast<canvas::Window>
324       (
325         static_cast<sc::Element::OSGUserData*>(element->getUserData())->element
326       );
327
328     if( !window || !window->isCapturingEvents() || !window->isVisible() )
329       continue;
330
331     float margin = window->isResizable() ? resize_margin_pos : 0;
332     if( window->getScreenRegion().contains( event->getScreenX(),
333                                             event->getScreenY(),
334                                             margin ) )
335     {
336       window_at_cursor = window;
337       break;
338     }
339   }
340
341   if( window_at_cursor )
342   {
343     const SGRect<float>& reg = window_at_cursor->getScreenRegion();
344
345     if(     window_at_cursor->isResizable()
346         && (  ea.getEventType() == osgGA::GUIEventAdapter::MOVE
347            || ea.getEventType() == osgGA::GUIEventAdapter::PUSH
348            || ea.getEventType() == osgGA::GUIEventAdapter::RELEASE
349            )
350         && !reg.contains( event->getScreenX(),
351                           event->getScreenY(),
352                           -resize_margin_neg ) )
353     {
354       if( !_last_cursor )
355         _last_cursor = fgGetMouseCursor();
356
357       _resize = 0;
358
359       if( event->getScreenX() <= reg.l() + resize_corner )
360         _resize |= canvas::Window::LEFT;
361       else if( event->getScreenX() >= reg.r() - resize_corner )
362         _resize |= canvas::Window::RIGHT;
363
364       if( event->getScreenY() <= reg.t() + resize_corner )
365         _resize |= canvas::Window::TOP;
366       else if( event->getScreenY() >= reg.b() - resize_corner )
367         _resize |= canvas::Window::BOTTOM;
368
369       static const int cursor_mapping[] =
370       {
371         0, MOUSE_CURSOR_LEFTSIDE, MOUSE_CURSOR_RIGHTSIDE, 0,
372         MOUSE_CURSOR_TOPSIDE, MOUSE_CURSOR_TOPLEFT, MOUSE_CURSOR_TOPRIGHT, 0,
373         MOUSE_CURSOR_BOTTOMSIDE, MOUSE_CURSOR_BOTTOMLEFT, MOUSE_CURSOR_BOTTOMRIGHT,
374       };
375
376       if( !cursor_mapping[_resize] )
377         return false;
378
379       fgSetMouseCursor(cursor_mapping[_resize]);
380
381       if( ea.getEventType() == osgGA::GUIEventAdapter::PUSH )
382       {
383         _resize_window = window_at_cursor;
384         _drag_start = event->screen_pos;
385
386         window_at_cursor->raise();
387         window_at_cursor->handleResize(_resize | canvas::Window::INIT);
388       }
389
390       return true;
391     }
392   }
393
394   if( _last_cursor )
395   {
396     fgSetMouseCursor(_last_cursor);
397     _last_cursor = 0;
398     return true;
399   }
400
401   canvas::WindowPtr target_window = window_at_cursor;
402   switch( ea.getEventType() )
403   {
404     case osgGA::GUIEventAdapter::PUSH:
405       _last_push = window_at_cursor;
406       event->type = sc::Event::MOUSE_DOWN;
407       break;
408     case osgGA::GUIEventAdapter::SCROLL:
409       switch( ea.getScrollingMotion() )
410       {
411         case osgGA::GUIEventAdapter::SCROLL_UP:
412           event->delta.y() = 1;
413           break;
414         case osgGA::GUIEventAdapter::SCROLL_DOWN:
415           event->delta.y() = -1;
416           break;
417         default:
418           return false;
419       }
420
421       // osg sends two events for every scrolling motion. We don't need
422       // duplicate events, so lets ignore the second event with the same
423       // timestamp.
424       if( _last_scroll_time == ea.getTime() )
425         return window_at_cursor ? true : false;
426       _last_scroll_time = ea.getTime();
427
428       event->type = sc::Event::WHEEL;
429       break;
430     case osgGA::GUIEventAdapter::MOVE:
431     {
432       canvas::WindowPtr last_mouse_over = _last_mouse_over.lock();
433       if( last_mouse_over != window_at_cursor && last_mouse_over )
434       {
435         sc::MouseEventPtr move_event( new sc::MouseEvent(*event) );
436         move_event->type = sc::Event::MOUSE_LEAVE;
437         move_event->client_pos -= toOsg(last_mouse_over->getPosition());
438         move_event->local_pos = move_event->client_pos;
439
440         last_mouse_over->handleEvent(move_event);
441       }
442       _last_mouse_over = window_at_cursor;
443       event->type = sc::Event::MOUSE_MOVE;
444       break;
445     }
446     case osgGA::GUIEventAdapter::RELEASE:
447     {
448       event->type = sc::Event::MOUSE_UP;
449
450       canvas::WindowPtr last_push = _last_push.lock();
451       _last_push.reset();
452
453       if( last_push && last_push != target_window )
454       {
455         // Leave old window
456         sc::MouseEventPtr leave_event( new sc::MouseEvent(*event) );
457         leave_event->type = sc::Event::MOUSE_LEAVE;
458         leave_event->client_pos -= toOsg(last_push->getPosition());
459         leave_event->local_pos = leave_event->client_pos;
460
461         last_push->handleEvent(leave_event);
462       }
463       break;
464     }
465     case osgGA::GUIEventAdapter::DRAG:
466       target_window = _last_push.lock();
467       event->type = sc::Event::DRAG;
468       break;
469
470     default:
471       return false;
472   }
473
474   if( target_window )
475   {
476     event->client_pos -= toOsg(target_window->getPosition());
477     event->local_pos = event->client_pos;
478     return target_window->handleEvent(event);
479   }
480   else
481     return false;
482 }
483
484 //------------------------------------------------------------------------------
485 void DesktopGroup::handleResize(int x, int y, int width, int height)
486 {
487   if( _width == width && _height == height )
488     return;
489
490   _width = width;
491   _height = height;
492
493   // Origin should be at top left corner, therefore we need to mirror the y-axis
494   _transform->setMatrix(osg::Matrix(
495     1,  0, 0, 0,
496     0, -1, 0, 0,
497     0,  0, 1, 0,
498     0, _height, 0, 1
499   ));
500 }
501
502 //------------------------------------------------------------------------------
503 void DesktopGroup::handleMouseMode(SGPropertyNode* node)
504 {
505   // pass-through indicates events should pass through to the UI
506   _handle_events = fgGetNode("/input/mice/mouse[0]/mode", node->getIntValue())
507                      ->getBoolValue("pass-through");
508 }
509
510 //------------------------------------------------------------------------------
511 GUIMgr::GUIMgr():
512   _desktop( new DesktopGroup ),
513   _event_handler( new GUIEventHandler(
514     boost::static_pointer_cast<DesktopGroup>(_desktop)
515   ))
516 {
517   // We handle the property listener manually within ::init and ::shutdown.
518   _desktop->removeListener();
519 }
520
521 //------------------------------------------------------------------------------
522 canvas::WindowPtr GUIMgr::createWindow(const std::string& name)
523 {
524   canvas::WindowPtr window = _desktop->createChild<canvas::Window>(name);
525   if( name.empty() )
526     window->set<std::string>
527     (
528       "id",
529       boost::lexical_cast<std::string>(window->getProps()->getIndex())
530     );
531   return window;
532 }
533
534 //------------------------------------------------------------------------------
535 void GUIMgr::init()
536 {
537   boost::static_pointer_cast<DesktopGroup>(_desktop)->handleResize
538   (
539     0,
540     0,
541     fgGetInt("/sim/startup/xsize"),
542     fgGetInt("/sim/startup/ysize")
543   );
544
545   globals->get_renderer()
546          ->getViewer()
547          ->getEventHandlers()
548          // GUI is on top of everything so lets install as first event handler
549          .push_front( _event_handler );
550
551   _desktop->getProps()->addChangeListener(_desktop.get());
552   _desktop->getProps()->fireCreatedRecursive();
553 }
554
555 //------------------------------------------------------------------------------
556 void GUIMgr::shutdown()
557 {
558   _desktop->getProps()->removeChangeListener(_desktop.get());
559
560   globals->get_renderer()
561          ->getViewer()
562          ->removeEventHandler( _event_handler );
563 }
564
565 //------------------------------------------------------------------------------
566 void GUIMgr::update(double dt)
567 {
568   _desktop->update(dt);
569 }
570
571 //------------------------------------------------------------------------------
572 simgear::canvas::GroupPtr GUIMgr::getDesktop()
573 {
574   return _desktop;
575 }