root/OpenSceneGraph/trunk/src/osgWidget/WindowManager.cpp @ 13376

Revision 13376, 17.5 kB (checked in by robert, 26 hours ago)

Moved widgets from VolumeEditorWidget? to TransferFunctionWidget?, and widget utilities into WidgetUtils?.

  • Property svn:eol-style set to native
Line 
1// -*-c++-*- osgWidget - Code by: Jeremy Moles (cubicool) 2007-2008
2// $Id: WindowManager.cpp 66 2008-07-14 21:54:09Z cubicool $
3
4#include <iostream>
5#include <algorithm>
6#include <osg/io_utils>
7#include <osgWidget/Types>
8#include <osgWidget/Util>
9#include <osgWidget/WindowManager>
10#include <osgWidget/Lua>
11#include <osgWidget/Python>
12#include <osgWidget/Box>
13#include <osgWidget/Label>
14
15namespace osgWidget {
16
17WindowManager::WindowManager(
18    osgViewer::View* view,
19    point_type       width,
20    point_type       height,
21    unsigned int     nodeMask,
22    unsigned int     flags
23):
24_width          (width),
25_height         (height),
26_windowWidth    (width),
27_windowHeight   (height),
28_flags          (flags),
29_nodeMask       (nodeMask),
30_view           (view),
31_lastX          (0.0f),
32_lastY          (0.0f),
33_lastEvent      (0),
34_lastPush       (0),
35_lastVertical   (PD_NONE),
36_lastHorizontal (PD_NONE),
37_focusMode      (PFM_FOCUS),
38_leftDown       (false),
39_middleDown     (false),
40_rightDown      (false),
41_scrolling      (osgGA::GUIEventAdapter::SCROLL_NONE),
42_styleManager   (new StyleManager()) {
43    _name = generateRandomName("WindowManager");
44
45    if(_flags & WM_USE_LUA) {
46        _lua = new LuaEngine(this);
47
48        if(!_lua->initialize()) warn() << "Error creating LuaEngine." << std::endl;
49    }
50
51    if(_flags & WM_USE_PYTHON) {
52        _python = new PythonEngine(this);
53
54        if(!_python->initialize()) warn() << "Error creating PythonEngine." << std::endl;
55    }
56
57    if(_flags & WM_USE_RENDERBINS) getOrCreateStateSet()->setMode(GL_DEPTH_TEST, false);
58
59    // Setup our picking debug (is debug the right word here?) Window...
60    if(_flags & WM_PICK_DEBUG) {
61        _pickWindow = new Box("PickWindow", Box::VERTICAL);
62
63        Label* label = new Label("PickLabel");
64
65        label->setFontSize(13);
66        label->setFontColor(1.0f, 1.0f, 1.0f, 1.0f);
67        label->setFont("fonts/VeraMono.ttf");
68        label->setPadding(5.0f);
69        label->setCanFill(true);
70
71        _pickWindow->getBackground()->setColor(0.0f, 0.0f, 0.0f, 0.85f);
72        _pickWindow->addWidget(label);
73        _pickWindow->setNodeMask(~_nodeMask);
74        _pickWindow->removeEventMask(EVENT_MASK_FOCUS);
75        _pickWindow->setStrata(Window::STRATA_FOREGROUND);
76
77        addChild(_pickWindow.get());
78
79        _updatePickWindow(0, 0, 0);
80    }
81
82    getOrCreateStateSet()->setMode(
83        GL_BLEND,
84        osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE
85    );
86    getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
87}
88
89WindowManager::WindowManager(const WindowManager& wm, const osg::CopyOp& co):
90    osg::Switch(wm, co),
91    _width          (wm._width),
92    _height         (wm._height),
93    _windowWidth    (wm._width),
94    _windowHeight   (wm._height),
95    _flags          (wm._flags),
96    _nodeMask       (wm._nodeMask),
97    _view           (wm._view),
98    _lastX          (0.0f),
99    _lastY          (0.0f),
100    _lastEvent      (0),
101    _lastPush       (0),
102    _lastVertical   (PD_NONE),
103    _lastHorizontal (PD_NONE),
104    _focusMode      (PFM_FOCUS),
105    _leftDown       (false),
106    _middleDown     (false),
107    _rightDown      (false),
108    _scrolling      (osgGA::GUIEventAdapter::SCROLL_NONE),
109    _styleManager   (new StyleManager())
110{
111}
112
113WindowManager::~WindowManager()
114{
115    if(_flags & WM_USE_LUA) _lua->close();
116
117    if(_flags & WM_USE_PYTHON) _python->close();
118}
119
120void WindowManager::setEventFromInterface(Event& ev, EventInterface* ei) {
121    Widget* widget = dynamic_cast<Widget*>(ei);
122    Window* window = dynamic_cast<Window*>(ei);
123
124    if(widget) {
125        ev._window = widget->getParent();
126        ev._widget = widget;
127    }
128
129    else if(window) ev._window = window;
130}
131
132bool WindowManager::_handleMousePushed(float x, float y, bool& down) {
133    down = true;
134
135    Event ev(this, EVENT_MOUSE_PUSH);
136
137    WidgetList widgetList;
138
139    if(!pickAtXY(x, y, widgetList)) return false;
140
141    ev.makeMouse(x, y);
142
143    _lastPush = getFirstEventInterface(widgetList, ev);
144
145    if(!_lastPush) return false;
146
147    // TODO: This is the old way; it didn't allow Event handler code to call grabFocus().
148    // bool handled = _lastPush->callMethodAndCallbacks(ev);
149
150    if(_focusMode != PFM_SLOPPY) {
151        if(ev._window) {
152            Window* topmostWindow = ev._window->getTopmostParent();
153
154            setFocused(topmostWindow);
155
156            if(ev._widget) topmostWindow->setFocused(ev._widget);
157        }
158
159        // If the user wants to be able to "unfocus" the last Window.
160        else if(_focusMode == PFM_UNFOCUS) setFocused(0);
161    }
162
163    return _lastPush->callMethodAndCallbacks(ev);
164}
165
166bool WindowManager::_handleMouseReleased(float x, float y, bool& down) {
167    down = false;
168
169    // If were were in a drag state, reset our boolean flag.
170    // if(_lastDrag) _lastDrag = 0;
171
172    if(!_lastPush) return false;
173
174    // By design, we can only release an EventInterface we previously pressed.
175    // Whether or not we're ON the EventInterface when the release occurs isn't important.
176    Event ev(this, EVENT_MOUSE_RELEASE);
177
178    setEventFromInterface(ev, _lastPush);
179
180    bool handled = _lastPush->callMethodAndCallbacks(ev);
181
182    _lastPush = 0;
183
184    return handled;
185}
186
187void WindowManager::_getPointerXYDiff(float& x, float& y) {
188    x -= _lastX;
189    y -= _lastY;
190}
191
192void WindowManager::_updatePickWindow(const WidgetList* wl, point_type x, point_type y) {
193    Label* label = dynamic_cast<Label*>(_pickWindow->getByName("PickLabel"));
194
195    if(!wl) {
196        setValue(0, false);
197
198        return;
199    }
200
201    setValue(0, true);
202
203    std::stringstream ss;
204
205    point_type xdiff = x;
206    point_type ydiff = y;
207
208    _getPointerXYDiff(xdiff, ydiff);
209
210    ss
211        << "At XY Coords: " << x << ", " << y
212        << " ( diff " << xdiff << ", " << ydiff << " )"
213        << std::endl
214    ;
215
216    const Window* parent = wl->back()->getParent();
217
218    ss
219        << "Window: " << parent->getName()
220        << " ( xyz " << parent->getPosition() << " )"
221        << " { zRange " << parent->getZRange() << " }"
222        << " < size " << parent->getSize() << " >"
223        << " EventMask: " << std::hex << parent->getEventMask()
224        << std::endl
225    ;
226
227    for(WidgetList::const_iterator i = wl->begin(); i != wl->end(); i++) {
228        Widget* widget = i->get();
229
230        ss
231            << "   - " << widget->getName()
232            << " ( xyz " << widget->getPosition() << " )"
233            << " [ XYZ " << widget->getPosition() * parent->getMatrix()
234            << " ] < size " << widget->getSize() << " >"
235            << " EventMask: " << std::hex << widget->getEventMask()
236            << std::endl
237        ;
238    }
239
240    label->setLabel(ss.str());
241
242    XYCoord size = label->getTextSize();
243
244    _pickWindow->resize(size.x() + 10.0f, size.y() + 10.0f);
245    _pickWindow->setOrigin(5.0f, _height - _pickWindow->getHeight() - 5.0f);
246    _pickWindow->update();
247}
248
249void WindowManager::childInserted(unsigned int i) {
250    Window* window = dynamic_cast<Window*>(getChild(i));
251
252    if(!window) return;
253
254    // Update Window's index
255    for(Iterator w = begin(); w != end(); w++) {
256        if(w->get()->_index >= i) w->get()->_index++;
257    }
258
259    _objects.push_back(window);
260
261    window->_index = i;
262
263    setFocused(window);
264
265    window->setNodeMask(_nodeMask);
266    window->managed(this);
267
268    for(Window::Iterator w = window->begin(); w != window->end(); w++) if(w->valid()) {
269        _styleManager->applyStyles(w->get());
270    }
271
272    _styleManager->applyStyles(window);
273}
274
275void WindowManager::childRemoved(unsigned int start, unsigned int numChildren) {
276    for (unsigned int i = start; i < start+numChildren; i++)
277    {
278        Window* window = getByIndex(i);
279
280        if(!window) continue;
281
282        if(_remove(window)) {
283
284            window->_index = 0;
285            window->unmanaged(this);
286        }
287    }
288
289    // Update Window's index
290    for(Iterator w = begin(); w != end(); w++) {
291        if(w->get()->_index >= start) w->get()->_index -= numChildren;
292    }
293
294}
295
296// This method performs intersection testing at the given XY coords, and returns true if
297// any intersections were found. It will break after processing the first pickable Window
298// it finds.
299bool WindowManager::pickAtXY(float x, float y, WidgetList& wl)
300{
301    Intersections intr;
302
303   
304    osg::Camera* camera = _view->getCamera();
305    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(camera->getGraphicsContext());
306    if (gw)
307    {
308        _view->computeIntersections(camera, osgUtil::Intersector::WINDOW, x, y, intr, _nodeMask);
309    }
310       
311    if (!intr.empty())
312    {
313        // Get the first Window at the XY coordinates; if you want a Window to be
314        // non-pickable, set the NodeMask to something else.
315        Window* activeWin = 0;
316
317        // Iterate over every picked result and create a list of Widgets that belong
318        // to that Window.
319        for(Intersections::iterator i = intr.begin(); i != intr.end(); i++) {
320            Window* win = dynamic_cast<Window*>(i->nodePath.back()->getParent(0));
321
322            // Make sure that our window is valid, and that our pick is within the
323            // "visible area" of the Window.
324            if(
325                !win ||
326                (win->getVisibilityMode() == Window::VM_PARTIAL && !win->isPointerXYWithinVisible(x, y))
327            ) {
328                continue;
329            }
330
331            // Set our activeWin, so that we know when we've got all the Widgets
332            // that belong to it.
333            if(!activeWin) activeWin = win;
334
335            // If we've found a new Widnow, break out!
336            else if(activeWin != win) break;
337
338            Widget* widget = dynamic_cast<Widget*>(i->drawable.get());
339
340            if(!widget) continue;
341
342            // We need to return a list of every Widget that was picked, so
343            // that the handler can operate on it accordingly.
344            else wl.push_back(widget);
345        }
346
347        if(wl.size()) {
348            // Potentially VERY expensive; only to be used for debugging. :)
349            if(_flags & WM_PICK_DEBUG) _updatePickWindow(&wl, x, y);
350
351            return true;
352        }
353    }
354
355    if(_flags & WM_PICK_DEBUG) _updatePickWindow(0, x, y);
356
357    return false;
358}
359
360
361bool WindowManager::setFocused(Window* window) {
362    Event ev(this);
363
364    ev._window = window;
365
366    // Inform the previously focused Window that it is going to be unfocused.
367    if(_focused.valid()) _focused->callMethodAndCallbacks(ev.makeType(EVENT_UNFOCUS));
368
369    _focused = window;
370
371    if(!window || !window->canFocus()) return false;
372
373    // Build a vector of every Window that is focusable, in the foreground, and in the
374    // background. All these Windows are handled differently.
375    Vector focusable;
376    Vector bg;
377    Vector fg;
378
379    for(ConstIterator it = begin(); it != end(); it++) if(it->valid()) {
380        Window* w = it->get();
381
382        if(w->getStrata() == Window::STRATA_FOREGROUND) fg.push_back(w);
383
384        else if(w->getStrata() == Window::STRATA_BACKGROUND) bg.push_back(w);
385
386        else focusable.push_back(w);
387    }
388
389    // After this call to sort, the internal objects will be arranged such that the
390    // previously focused window is the first, followed by all other Windows in
391    // descending order.
392    std::sort(focusable.begin(), focusable.end(), WindowZCompare());
393
394    // This is the depth range for each Window. Each Window object must be informed of
395    // the Z space allocated to it so that it can properly arrange it's children. We
396    // add 2 additional Windows here for anything that should appear in the background
397    // and foreground areas.
398    matrix_type zRange = 1.0f / (focusable.size() + 2.0f);
399
400    // Our offset for the following for() loop.
401    unsigned int i = 3;
402
403    // Handle all of our focusable Windows.
404    for(Iterator w = focusable.begin(); w != focusable.end(); w++) {
405        Window* win = w->get();
406
407        // Set our newly focused Window as the topmost element.
408        if(*w == window) win->_z = -zRange * 2.0f;
409
410        // Set the current Z of the remaining Windows and set their zRange so that
411        // they can update their own children.
412        else {
413            win->_z = -zRange * i;
414
415            i++;
416        }
417    }
418
419    // Handled our special BACKGROUND Windows.
420    for(Iterator w = bg.begin(); w != bg.end(); w++) w->get()->_z = -zRange * i;
421
422    // Handle our special FOREGOUND Windows.
423    for(Iterator w = fg.begin(); w != fg.end(); w++) w->get()->_z = -zRange;
424
425    // Update every window, regardless.
426    for(Iterator w = begin(); w != end(); w++) {
427        Window* win = w->get();
428
429        win->_zRange = zRange;
430
431        win->update();
432    }
433
434    _focused->callMethodAndCallbacks(ev.makeType(EVENT_FOCUS));
435
436    return true;
437}
438
439void WindowManager::setPointerXY(float x, float y) {
440    float xdiff = x;
441    float ydiff = y;
442
443    _getPointerXYDiff(xdiff, ydiff);
444
445    // If ydiff isn't NEAR 0 (floating point booleans aren't 100% reliable, but that
446    // doesn't matter in our case), assume we have either up or down movement.
447    if(ydiff != 0.0f) _lastVertical = ydiff > 0.0f ? PD_UP : PD_DOWN;
448
449    else _lastVertical = PD_NONE;
450
451    // If xdiff isn't 0, assume we have either left or right movement.
452    if(xdiff != 0.0f) _lastHorizontal = xdiff > 0.0f ? PD_RIGHT : PD_LEFT;
453
454    else _lastHorizontal = PD_NONE;
455
456    _lastX = x;
457    _lastY = y;
458}
459
460void WindowManager::setStyleManager(StyleManager* sm) {
461    _styleManager = sm;
462
463    for(Iterator i = begin(); i != end(); i++) if(i->valid()) {
464        Window* window = i->get();
465
466        for(Window::Iterator w = window->begin(); w != window->end(); w++) {
467            if(!w->valid()) continue;
468
469            _styleManager->applyStyles(w->get());
470        }
471
472        _styleManager->applyStyles(window);
473    }
474}
475
476void WindowManager::resizeAllWindows(bool visible) {
477    for(Iterator i = begin(); i != end(); i++) if(i->valid()) {
478        if(visible && !getValue(i->get()->_index)) continue;
479
480        i->get()->resize();
481    }
482}
483
484// Returns the application window coordinates of the WindowManager XY position.
485XYCoord WindowManager::windowXY(double x, double y) const {
486    return XYCoord((_windowWidth / _width) * x, (_windowHeight / _height) * y);
487}
488
489// Returns the WindowManager coordinates of the application window XY position.
490XYCoord WindowManager::localXY(double x, double y) const {
491    return XYCoord((_width / _windowWidth) * x, (_height / _windowHeight) * y);
492}
493
494// This is called by a ViewerEventHandler/MouseHandler (or whatever) as the pointer moves
495// around and intersects with objects. It also resets our state data (_widget, _leftDown,
496// etc.) The return value of this method is mostly useless.
497bool WindowManager::pointerMove(float x, float y) {
498    WidgetList wl;
499    Event      ev(this);
500
501    if(!pickAtXY(x, y, wl)) {
502        if(_lastEvent) {
503            setEventFromInterface(ev.makeMouse(x, y, EVENT_MOUSE_LEAVE), _lastEvent);
504
505            _lastEvent->callMethodAndCallbacks(ev);
506        }
507
508        if(_focusMode == PFM_SLOPPY) setFocused(0);
509
510        _lastEvent  = 0;
511        _leftDown   = 0;
512        _middleDown = 0;
513        _rightDown  = 0;
514
515        return false;
516    }
517
518    EventInterface* ei = getFirstEventInterface(wl, ev.makeMouse(x, y, EVENT_MOUSE_OVER));
519
520    if(!ei) return false;
521
522    if(_lastEvent != ei) {
523        if(_lastEvent) {
524            Event evLeave(this);
525
526            evLeave.makeMouse(x, y, EVENT_MOUSE_LEAVE);
527
528            setEventFromInterface(evLeave, _lastEvent);
529
530            _lastEvent->callMethodAndCallbacks(evLeave);
531        }
532
533        _lastEvent = ei;
534
535        if(_focusMode == PFM_SLOPPY && ev._window) setFocused(ev._window);
536
537        _lastEvent->callMethodAndCallbacks(ev.makeMouse(x, y, EVENT_MOUSE_ENTER));
538    }
539
540    ei->callMethodAndCallbacks(ev.makeMouse(x, y, EVENT_MOUSE_OVER));
541
542    return true;
543}
544
545bool WindowManager::pointerDrag(float x, float y) {
546    WidgetList widgetList;
547    Event      ev(this);
548
549    float xdiff = x;
550    float ydiff = y;
551
552    _getPointerXYDiff(xdiff, ydiff);
553
554    ev.makeMouse(xdiff, ydiff, EVENT_MOUSE_DRAG);
555
556    // If we're still in the drag state...
557    if(_lastPush) {
558        setEventFromInterface(ev, _lastPush);
559
560        return _lastPush->callMethodAndCallbacks(ev);
561    }
562
563    return false;
564}
565
566bool WindowManager::mouseScroll(float x, float y) {
567    WidgetList wl;
568
569    if(!pickAtXY(x, y, wl)) return false;
570
571    Event ev(this, EVENT_MOUSE_SCROLL);
572
573    EventInterface* ei = getFirstEventInterface(wl, ev);
574
575    if(!ei) return false;
576
577    return ei->callMethodAndCallbacks(ev);
578}
579
580// Keypresses only go the focused Window.
581bool WindowManager::keyDown(int key, int mask) {
582    if(_focused.valid()) {
583        Event ev(this, EVENT_KEY_DOWN);
584
585        ev.makeKey(key, mask);
586
587        Widget* focusedWidget = _focused->getFocused();
588
589        ev._window = _focused.get();
590        ev._widget = focusedWidget;
591
592        bool handled = false;
593
594        if(focusedWidget) handled = focusedWidget->callMethodAndCallbacks(ev);
595
596        if(!handled) return _focused->callMethodAndCallbacks(ev);
597
598        else return true;
599    }
600
601    return false;
602}
603
604bool WindowManager::keyUp(int key, int mask) {
605    if(_focused.valid()) {
606        Event ev(this, EVENT_KEY_UP);
607
608        ev.makeKey(key, mask);
609
610        Widget* focusedWidget = _focused->getFocused();
611
612        ev._window = _focused.get();
613        ev._widget = focusedWidget;
614
615        bool handled = false;
616
617        if(focusedWidget) handled = focusedWidget->callMethodAndCallbacks(ev);
618
619        if(!handled) return _focused->callMethodAndCallbacks(ev);
620
621        else return true;
622    }
623
624    return false;
625}
626
627// A convenience wrapper for creating a proper orthographic camera using the current
628// width and height.
629osg::Camera* WindowManager::createParentOrthoCamera() {
630    osg::Camera* camera = createOrthoCamera(_width, _height);
631
632    camera->addChild(this);
633
634    return camera;
635}
636
637}
Note: See TracBrowser for help on using the browser.