Add brackets around control flow constructs to make more readable
[gnash.git] / gui / gui.cpp
blobcc8b8f49ab4a1ce2859df54af36a23e3fb1c5a0d
1 // gui.cpp: Top level GUI for SWF player, for Gnash.
2 //
3 // Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Free Software
4 // Foundation, Inc
5 //
6 // This program is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 #ifdef HAVE_CONFIG_H
22 #include "gnashconfig.h"
23 #endif
25 #include "gui.h"
27 #include <vector>
28 #include <algorithm>
30 #include "MovieClip.h"
31 #include "Renderer.h"
32 #include "sound_handler.h"
33 #include "movie_root.h"
34 #include "VM.h"
35 #include "DisplayObject.h"
36 #include "GnashEnums.h"
37 #include "RunResources.h"
38 #include "StreamProvider.h"
39 #include "ScreenShotter.h"
41 #ifdef GNASH_FPS_DEBUG
42 #include "ClockTime.h"
43 #include <boost/format.hpp>
44 #endif
46 /// Define this to make sure each frame is fully rendered from ground up
47 /// even if no motion has been detected in the movie.
48 //#define FORCE_REDRAW 1
50 /// Define this if you want to debug the *detection* of region updates only.
51 /// This will disable region updates for the backend (GUI+renderer) completely
52 /// so that only the last region (red frame) will be visible. However, this
53 /// slows down rendering as each frame is fully re-rendered. If you want to
54 /// debug the GUI part, however (see if blitting the region works), then you
55 /// probably won't define this.
56 #ifndef DISABLE_REGION_UPDATES_DEBUGGING
57 //#define REGION_UPDATES_DEBUGGING_FULL_REDRAW 1
58 #endif
60 #ifndef DISABLE_REGION_UPDATES_DEBUGGING
61 // a runtime check would make the { x; } block conditionally executed
62 #define IF_DEBUG_REGION_UPDATES(x) { if (_showUpdatedRegions) { x } }
63 #else
64 #define IF_DEBUG_REGION_UPDATES(x)
65 #endif
67 // Define this to have gnash print the mouse pointer coordinates
68 // as the mouse moves. See also ENABLE_KEYBOARD_MOUSE_MOVEMENTS
69 // to have more control over mouse pointer.
71 //#define DEBUG_MOUSE_COORDINATES 1
73 // Define the following macro if you want to skip rendering
74 // when late on FPS time.
75 // This is an experimental feature, so it's off by default
76 //#define SKIP_RENDERING_IF_LATE 1
79 namespace gnash {
81 Gui::Gui(RunResources& r) :
82 _loop(true),
83 _xid(0),
84 _width(1),
85 _height(1),
86 _runResources(r),
87 _interval(0),
88 _redraw_flag(true),
89 _fullscreen(false),
90 _mouseShown(true),
91 _maxAdvances(0),
92 _advances(0),
93 _xscale(1.0f),
94 _yscale(1.0f),
95 _xoffset(0),
96 _yoffset(0)
97 #ifdef GNASH_FPS_DEBUG
98 ,fps_counter(0)
99 ,fps_counter_total(0)
100 ,fps_timer(0)
101 ,fps_timer_interval(0.0)
102 ,frames_dropped(0)
103 #endif
104 ,_movieDef(0)
105 ,_stage(0)
106 ,_stopped(false)
107 ,_started(false)
108 ,_showUpdatedRegions(false)
110 // NOTE: it's important that _systemClock is constructed
111 // before and destroyed after _virtualClock !
112 ,_systemClock()
113 ,_virtualClock(_systemClock)
114 #ifdef ENABLE_KEYBOARD_MOUSE_MOVEMENTS
115 ,_xpointer(0)
116 ,_ypointer(0)
117 ,_keyboardMouseMovements(true) // TODO: base default on gnashrc or always false and provide menu item to toggle
118 ,_keyboardMouseMovementsStep(1)
119 #endif
124 Gui::Gui(unsigned long xid, float scale, bool loop, RunResources& r)
126 _loop(loop),
127 _xid(xid),
128 _width(1),
129 _height(1),
130 _runResources(r),
131 _interval(0),
132 _redraw_flag(true),
133 _fullscreen(false),
134 _mouseShown(true),
135 _maxAdvances(0),
136 _advances(0),
137 _xscale(scale),
138 _yscale(scale),
139 _xoffset(0), // TODO: x and y offset will need update !
140 _yoffset(0)
141 #ifdef GNASH_FPS_DEBUG
142 ,fps_counter(0)
143 ,fps_counter_total(0)
144 ,fps_timer(0)
145 ,fps_timer_interval(0.0)
146 ,frames_dropped(0)
147 #endif
148 ,_movieDef(0)
149 ,_stage(0)
150 ,_stopped(false)
151 ,_started(false)
152 ,_showUpdatedRegions(false)
154 // NOTE: it's important that _systemClock is constructed
155 // before and destroyed after _virtualClock !
156 ,_systemClock()
157 ,_virtualClock(_systemClock)
158 #ifdef ENABLE_KEYBOARD_MOUSE_MOVEMENTS
159 ,_xpointer(0)
160 ,_ypointer(0)
161 ,_keyboardMouseMovements(true) // TODO: base default on gnashrc or always false and provide menu item to toggle
162 ,_keyboardMouseMovementsStep(1)
163 #endif
167 Gui::~Gui()
169 if ( _movieDef.get() ) log_debug("~Gui - _movieDef refcount: %d", _movieDef->get_ref_count());
171 #ifdef GNASH_FPS_DEBUG
172 if ( fps_timer_interval ) {
173 std::cerr << "Total frame advances/drops: "
174 << fps_counter_total << "/" << frames_dropped << std::endl;
176 #endif
179 void
180 Gui::setClipboard(const std::string&)
182 LOG_ONCE(log_unimpl(_("Clipboard not yet supported in this GUI")));
185 void
186 Gui::setFullscreen()
188 log_unimpl(_("Fullscreen not yet supported in this GUI"));
191 void
192 Gui::resizeWindow(int /*width*/, int /*height*/)
194 log_unimpl(_("Window resize not yet supported in this GUI"));
197 void
198 Gui::unsetFullscreen()
200 log_unimpl(_("Fullscreen not yet supported in this GUI"));
203 void
204 Gui::quit()
206 // Take a screenshot of the last frame if required.
207 if (_screenShotter.get() && _renderer.get()) {
208 _screenShotter->last(*_renderer);
211 quitUI();
214 void
215 Gui::hideMenu()
217 log_unimpl(_("Menu hiding not yet supported in this GUI"));
220 bool
221 Gui::showMouse(bool /* show */)
223 LOG_ONCE(log_unimpl(_("Mouse show/hide not yet supported in this GUI")));
224 return true;
227 void
228 Gui::showMenu(bool /* show */)
230 LOG_ONCE(log_unimpl(_("menushow not yet supported in this GUI")));
233 void
234 Gui::allowScale(bool allow)
236 if (!_stage) {
237 log_error("Gui::allowScale called before a movie_root was available");
238 return;
241 if (allow) _stage->setStageScaleMode(movie_root::SCALEMODE_SHOWALL);
242 else _stage->setStageScaleMode(movie_root::SCALEMODE_NOSCALE);
245 void
246 Gui::toggleFullscreen()
248 /// Sends request to Gnash core to change display state.
249 if (_fullscreen) {
250 _stage->setStageDisplayState(movie_root::DISPLAYSTATE_NORMAL);
252 else {
253 _stage->setStageDisplayState(movie_root::DISPLAYSTATE_FULLSCREEN);
257 void
258 Gui::restart()
260 _stage->reset();
261 _started = false;
262 start();
265 void
266 Gui::updateStageMatrix()
268 if (!_stage) {
269 // When VM initializes, we'll get a call to resize_view, which
270 // would call us again.
271 //log_debug("Can't update stage matrix till VM is initialized");
272 return;
275 assert(_stage); // when VM is initialized this should hold
277 float swfwidth = _movieDef->get_width_pixels();
278 float swfheight = _movieDef->get_height_pixels();
280 // Fetch scale mode
281 movie_root::ScaleMode scaleMode = _stage->getStageScaleMode();
283 switch (scaleMode) {
284 case movie_root::SCALEMODE_NOSCALE:
285 _xscale = _yscale = 1.0f;
286 break;
288 case movie_root::SCALEMODE_SHOWALL:
289 // set new scale value ( user-pixel / pseudo-pixel ). Do
290 // not divide by zero, or we end up with an invalid
291 // stage matrix that returns nan values.
292 _xscale = (swfwidth == 0.0f) ? 1.0f : _width / swfwidth;
293 _yscale = (swfheight == 0.0f) ? 1.0f : _height / swfheight;
295 // Scale proportionally, using smallest scale
296 if (_xscale < _yscale) {
297 _yscale = _xscale;
299 else if (_yscale < _xscale) {
300 _xscale = _yscale;
302 break;
304 case movie_root::SCALEMODE_NOBORDER:
305 // set new scale value ( user-pixel / pseudo-pixel )
306 _xscale = (swfwidth == 0.0f) ? 1.0f : _width / swfwidth;
307 _yscale = (swfheight == 0.0f) ? 1.0f : _height / swfheight;
309 // Scale proportionally, using biggest scale
310 if (_xscale > _yscale) {
311 _yscale = _xscale;
313 else if (_yscale > _xscale) {
314 _xscale = _yscale;
316 break;
318 case movie_root::SCALEMODE_EXACTFIT:
319 // NOTE: changing aspect ratio is valid!
320 _xscale = (swfwidth == 0.0f) ? 1.0f : _width / swfwidth;
321 _yscale = (swfheight == 0.0f) ? 1.0f : _height / swfheight;
322 break;
324 default:
325 log_error("Invalid scaleMode %d", scaleMode);
326 break;
329 _xoffset=0;
330 _yoffset=0;
332 // Fetch align mode
333 movie_root::StageAlign align = _stage->getStageAlignment();
334 movie_root::StageHorizontalAlign halign = align.first;
335 movie_root::StageVerticalAlign valign = align.second;
337 // Handle horizontal alignment
338 switch ( halign ) {
339 case movie_root::STAGE_H_ALIGN_L:
341 // _xoffset=0 is fine
342 break;
345 case movie_root::STAGE_H_ALIGN_R:
347 // Offsets in pixels
348 float defWidth = swfwidth *= _xscale;
349 float diffWidth = _width-defWidth;
350 _xoffset = diffWidth;
351 break;
354 case movie_root::STAGE_V_ALIGN_C:
356 // Offsets in pixels
357 float defWidth = swfwidth *= _xscale;
358 float diffWidth = _width-defWidth;
359 _xoffset = diffWidth/2.0;
360 break;
363 default:
365 log_error("Invalid horizontal align %d", valign);
366 break;
370 // Handle vertical alignment
371 switch ( valign ) {
372 case movie_root::STAGE_V_ALIGN_T:
374 // _yoffset=0 is fine
375 break;
378 case movie_root::STAGE_V_ALIGN_B:
380 float defHeight = swfheight *= _yscale;
381 float diffHeight = _height-defHeight;
382 _yoffset = diffHeight;
383 break;
386 case movie_root::STAGE_V_ALIGN_C:
388 float defHeight = swfheight *= _yscale;
389 float diffHeight = _height-defHeight;
390 _yoffset = diffHeight/2.0;
391 break;
394 default:
396 log_error("Invalid vertical align %d", valign);
397 break;
401 //log_debug("updateStageMatrix: scaleMode:%d, valign:%d, halign:%d",
402 //scaleMode, valign, halign);
404 // TODO: have a generic set_matrix ?
405 if (_renderer.get()) {
406 _renderer->set_scale(_xscale, _yscale);
407 _renderer->set_translation(_xoffset, _yoffset);
408 } else {
409 //log_debug("updateStageMatrix: could not signal updated stage
410 //matrix to renderer (no renderer registered)");
413 // trigger redraw
414 //_redraw_flag |= (_width!=width) || (_height!=height);
415 _redraw_flag = true; // this fixes bug #21971
419 void
420 Gui::resize_view(int width, int height)
423 assert(width>0);
424 assert(height>0);
426 if (_stage && _started) {
427 _stage->setDimensions(width, height);
430 _width = width;
431 _height = height;
432 _validbounds.setTo(0, 0, _width, _height);
434 updateStageMatrix();
436 if ( _stage && _started ) display(_stage);
440 void
441 Gui::toggleSound()
443 assert (_stage);
444 // @todo since we registered the sound handler, shouldn't we know
445 // already what it is ?!
446 sound::sound_handler* s = _stage->runResources().soundHandler();
448 if (!s) return;
450 if (s->is_muted()) s->unmute();
451 else s->mute();
455 void
456 Gui::notifyMouseMove(int ux, int uy)
458 movie_root* m = _stage;
460 if ( ! _started ) return;
462 if ( _stopped ) return;
464 // A stage pseudopixel is user pixel / _xscale wide
465 boost::int32_t x = (ux-_xoffset) / _xscale;
467 // A stage pseudopixel is user pixel / _xscale high
468 boost::int32_t y = (uy-_yoffset) / _yscale;
470 #ifdef DEBUG_MOUSE_COORDINATES
471 log_debug(_("mouse @ %d,%d"), x, y);
472 #endif
474 if ( m->mouseMoved(x, y) )
476 // any action triggered by the
477 // event required screen refresh
478 display(m);
481 DisplayObject* activeEntity = m->getActiveEntityUnderPointer();
482 if ( activeEntity )
484 if ( activeEntity->isSelectableTextField() )
486 setCursor(CURSOR_INPUT);
488 else if ( activeEntity->allowHandCursor() )
490 setCursor(CURSOR_HAND);
492 else
494 setCursor(CURSOR_NORMAL);
497 else
499 setCursor(CURSOR_NORMAL);
502 #ifdef ENABLE_KEYBOARD_MOUSE_MOVEMENTS
503 _xpointer = ux;
504 _ypointer = uy;
505 #endif
510 void
511 Gui::notifyMouseWheel(int delta)
513 movie_root* m = _stage;
514 assert(m);
516 if (!_started) return;
517 if (_stopped) return;
519 if (m->mouseWheel(delta)) {
520 // any action triggered by the
521 // event required screen refresh
522 display(m);
526 void
527 Gui::notifyMouseClick(bool mouse_pressed)
529 movie_root* m = _stage;
530 assert(m);
532 if (!_started) return;
533 if (_stopped) return;
535 if (m->mouseClick(mouse_pressed)) {
536 // any action triggered by the
537 // event required screen refresh
538 display(m);
542 void
543 Gui::refreshView()
545 movie_root* m = _stage;
547 if ( ! _started ) return;
549 assert(m);
550 _redraw_flag=true;
551 display(m);
555 void
556 Gui::notify_key_event(gnash::key::code k, int modifier, bool pressed)
559 /* Handle GUI shortcuts */
560 if (pressed) {
561 if (k == gnash::key::ESCAPE) {
562 if (isFullscreen()) {
563 _stage->setStageDisplayState(movie_root::DISPLAYSTATE_NORMAL);
567 if (modifier & gnash::key::GNASH_MOD_CONTROL) {
568 switch (k) {
569 case gnash::key::o:
570 case gnash::key::O:
571 takeScreenShot();
572 break;
573 case gnash::key::r:
574 case gnash::key::R:
575 restart();
576 break;
577 case gnash::key::p:
578 case gnash::key::P:
579 pause();
580 break;
581 case gnash::key::l:
582 case gnash::key::L:
583 refreshView();
584 break;
585 case gnash::key::q:
586 case gnash::key::Q:
587 case gnash::key::w:
588 case gnash::key::W:
589 quit();
590 break;
591 case gnash::key::f:
592 case gnash::key::F:
593 toggleFullscreen();
594 break;
595 case gnash::key::h:
596 case gnash::key::H:
597 showUpdatedRegions(!showUpdatedRegions());
598 break;
599 case gnash::key::MINUS:
601 // Max interval allowed: 1 second (1FPS)
602 const size_t ni = std::min<size_t>(_interval + 2, 1000u);
603 setInterval(ni);
604 break;
606 case gnash::key::PLUS:
608 // Min interval allowed: 1/100 second (100FPS)
609 const size_t ni = std::max<size_t>(_interval - 2, 10u);
610 setInterval(ni);
611 break;
613 case gnash::key::EQUALS:
615 if (_stage) {
616 const float fps = _stage->frameRate();
617 // Min interval allowed: 1/100 second (100FPS)
618 const size_t ni = 1000.0/fps;
619 setInterval(ni);
621 break;
623 default:
624 break;
627 #ifdef ENABLE_KEYBOARD_MOUSE_MOVEMENTS
628 if ( _keyboardMouseMovements ) {
629 int step = _keyboardMouseMovementsStep;
630 // x5 if SHIFT is pressed
631 if (modifier & gnash::key::GNASH_MOD_SHIFT) step *= 5;
632 switch (k) {
633 case gnash::key::UP:
635 int newx = _xpointer;
636 int newy = _ypointer-step;
637 if ( newy < 0 ) newy=0;
638 notifyMouseMove(newx, newy);
639 break;
641 case gnash::key::DOWN:
643 int newx = _xpointer;
644 int newy = _ypointer+step;
645 if ( newy >= _height ) newy = _height-1;
646 notifyMouseMove(newx, newy);
647 break;
649 case gnash::key::LEFT:
651 int newx = _xpointer-step;
652 int newy = _ypointer;
653 if ( newx < 0 ) newx = 0;
654 notifyMouseMove(newx, newy);
655 break;
657 case gnash::key::RIGHT:
659 const int newy = _ypointer;
660 int newx = _xpointer + step;
661 if ( newx >= _width ) newx = _width-1;
662 notifyMouseMove(newx, newy);
663 break;
665 default:
666 break;
669 #endif // ENABLE_KEYBOARD_MOUSE_MOVEMENTS
673 if (!_started) return;
675 if (_stopped) return;
677 if (_stage->keyEvent(k, pressed)) {
678 // any action triggered by the
679 // event required screen refresh
680 display(_stage);
685 bool
686 Gui::display(movie_root* m)
688 assert(m == _stage); // why taking this arg ??
690 assert(_started);
692 InvalidatedRanges changed_ranges;
693 bool redraw_flag;
695 // Should the frame be rendered completely, even if it did not change?
696 #ifdef FORCE_REDRAW
697 redraw_flag = true;
698 #else
699 redraw_flag = _redraw_flag || want_redraw();
700 #endif
702 // reset class member if we do a redraw now
703 if (redraw_flag) _redraw_flag=false;
705 // Find out the surrounding frame of all characters which
706 // have been updated. This just checks what region of the stage has changed
707 // due to ActionScript code, the timeline or user events. The GUI can still
708 // choose to render a different part of the stage.
710 if (!redraw_flag) {
712 // choose snapping ranges factor
713 changed_ranges.setSnapFactor(1.3f);
715 // Use multi ranges only when GUI/Renderer supports it
716 // (Useless CPU overhead, otherwise)
717 changed_ranges.setSingleMode(!want_multiple_regions());
719 // scan through all sprites to compute invalidated bounds
720 m->add_invalidated_bounds(changed_ranges, false);
722 // grow ranges by a 2 pixels to avoid anti-aliasing issues
723 changed_ranges.growBy(40.0f / _xscale);
725 // optimize ranges
726 changed_ranges.combineRanges();
730 // TODO: Remove this and want_redraw to avoid confusion!?
731 if (redraw_flag) {
732 changed_ranges.setWorld();
735 // DEBUG ONLY:
736 // This is a good place to inspect the invalidated bounds state. Enable
737 // the following block (and parts of it) if you need to.
738 #if 0
740 // This may print a huge amount of information, but is useful to analyze
741 // the (visible) object structure of the movie and the flags of the
742 // characters. For example, a characters should have set the
743 // m_child_invalidated flag if at least one of it's childs has the
744 // invalidated flag set.
745 log_debug("DUMPING CHARACTER TREE");
747 InfoTree tr;
748 InfoTree::iterator top = tr.begin();
749 _stage->getMovieInfo(tr, top);
751 for (InfoTree::iterator i = tr.begin(), e = tr.end();
752 i != e; ++i) {
753 std::cout << std::string(tr.depth(i) * 2, ' ') << i->first << ": " <<
754 i->second << std::endl;
758 // less verbose, and often necessary: see the exact coordinates of the
759 // invalidated bounds (mainly to see if it's NULL or something else).
760 std::cout << "Calculated changed ranges: " << changed_ranges << "\n";
762 #endif
764 // Avoid drawing of stopped movies
765 if ( ! changed_ranges.isNull() ) // use 'else'?
767 // Tell the GUI(!) that we only need to update this
768 // region. Note the GUI can do whatever it wants with
769 // this information. It may simply ignore the bounds
770 // (which will normally lead into a complete redraw),
771 // or it may extend or shrink the bounds as it likes. So,
772 // by calling set_invalidated_bounds we have no guarantee
773 // that only this part of the stage is rendered again.
774 #ifdef REGION_UPDATES_DEBUGGING_FULL_REDRAW
775 // redraw the full screen so that only the
776 // *new* invalidated region is visible
777 // (helps debugging)
778 InvalidatedRanges world_ranges;
779 world_ranges.setWorld();
780 setInvalidatedRegions(world_ranges);
781 #else
782 setInvalidatedRegions(changed_ranges);
783 #endif
785 // TODO: should this be called even if we're late ?
786 beforeRendering();
788 // Render the frame, if not late.
789 // It's up to the GUI/renderer combination
790 // to do any clipping, if desired.
791 m->display();
793 // show invalidated region using a red rectangle
794 // (Flash debug style)
795 IF_DEBUG_REGION_UPDATES (
796 if (_renderer.get() && !changed_ranges.isWorld())
799 for (size_t rno = 0; rno < changed_ranges.size(); rno++) {
801 const geometry::Range2d<int>& bounds =
802 changed_ranges.getRange(rno);
804 point corners[4];
805 float xmin = bounds.getMinX();
806 float xmax = bounds.getMaxX();
807 float ymin = bounds.getMinY();
808 float ymax = bounds.getMaxY();
810 corners[0].x = xmin;
811 corners[0].y = ymin;
812 corners[1].x = xmax;
813 corners[1].y = ymin;
814 corners[2].x = xmax;
815 corners[2].y = ymax;
816 corners[3].x = xmin;
817 corners[3].y = ymax;
818 SWFMatrix no_transform;
819 _renderer->draw_poly(corners, 4,
820 rgba(0,0,0,0), rgba(255,0,0,255), no_transform, false);
826 // show frame on screen
827 renderBuffer();
831 return true;
834 void
835 Gui::play()
837 if ( ! _stopped ) return;
839 _stopped = false;
840 if ( ! _started ) start();
841 else
843 assert (_stage);
844 // @todo since we registered the sound handler, shouldn't we know
845 // already what it is ?!
846 sound::sound_handler* s = _stage->runResources().soundHandler();
847 if ( s ) s->unpause();
849 log_debug("Starting virtual clock");
850 _virtualClock.resume();
853 playHook ();
856 void
857 Gui::stop()
859 // _stage must be registered before this is called.
860 assert(_stage);
862 if ( _stopped ) return;
863 if ( isFullscreen() ) unsetFullscreen();
865 _stopped = true;
867 // @todo since we registered the sound handler, shouldn't we know
868 // already what it is ?!
869 sound::sound_handler* s = _stage->runResources().soundHandler();
870 if ( s ) s->pause();
872 log_debug("Pausing virtual clock");
873 _virtualClock.pause();
875 stopHook();
878 void
879 Gui::pause()
881 if (_stopped) {
882 play();
883 return;
886 // TODO: call stop() instead ?
887 // The only thing I see is that ::stop exits full-screen,
888 // but I'm not sure that's intended behaviour
890 // @todo since we registered the sound handler, shouldn't we know
891 // already what it is ?!
892 sound::sound_handler* s = _stage->runResources().soundHandler();
893 if (s) s->pause();
894 _stopped = true;
896 log_debug("Pausing virtual clock");
897 _virtualClock.pause();
899 stopHook();
902 void
903 Gui::start()
905 assert ( ! _started );
906 if (_stopped) {
907 log_debug("Gui is in stop mode, won't start application");
908 return;
911 // Initializes the stage with a Movie and the passed flash vars.
912 _stage->init(_movieDef.get(), _flashVars);
914 bool background = true; // ??
915 _stage->set_background_alpha(background ? 1.0f : 0.05f);
917 // to properly update stageMatrix if scaling is given
918 resize_view(_width, _height);
920 // @todo since we registered the sound handler, shouldn't we know
921 // already what it is ?!
922 sound::sound_handler* s = _stage->runResources().soundHandler();
923 if ( s ) {
924 if ( ! _audioDump.empty() ) {
925 s->setAudioDump(_audioDump);
927 s->unpause();
929 _started = true;
932 log_debug("Starting virtual clock");
933 _virtualClock.resume();
937 bool
938 Gui::advanceMovie()
941 if (isStopped()) {
942 return false;
945 if (!_started) {
946 start();
949 gnash::movie_root* m = _stage;
951 // Define REVIEW_ALL_FRAMES to have *all* frames
952 // consequentially displayed. Useful for debugging.
953 //#define REVIEW_ALL_FRAMES 1
955 #ifndef REVIEW_ALL_FRAMES
956 // Advance movie by one frame
957 const bool advanced = m->advance();
958 #else
959 const size_t cur_frame = m->getRootMovie()->get_current_frame();
960 const size_t tot_frames = m->getRootMovie()->get_frame_count();
961 const bool advanced = m->advance();
963 m->getRootMovie().ensureFrameLoaded(tot_frames);
964 m->goto_frame(cur_frame + 1);
965 m->getRootMovie().setPlayState(gnash::MovieClip::PLAYSTATE_PLAY);
966 log_debug(_("Frame %d"), m->get_current_frame());
967 #endif
969 #ifdef GNASH_FPS_DEBUG
970 // will be a no-op if fps_timer_interval is zero
971 if (advanced) {
972 fpsCounterTick();
974 #endif
977 // TODO: ask stage about doDisplay ?
978 // - if it didn't advance might need to check updateAfterEvent
979 bool doDisplay = true;
981 #ifdef SKIP_RENDERING_IF_LATE
982 // We want to skip rendering IFF it's time to advance again.
983 // We'll ask the stage about it
984 if (_stage->timeToNextFrame() <= 0) {
986 // or should it be if advanced ?
987 if (doDisplay) {
988 // TODO: take note of a frame drop (count them)
989 //log_debug("Frame rendering dropped due to being late");
990 #ifdef GNASH_FPS_DEBUG
991 ++frames_dropped;
992 #endif
994 doDisplay = false;
996 #endif // ndef SKIP_RENDERING_IF_LATE
998 if (doDisplay) display(m);
1000 if (!loops()) {
1001 size_t curframe = m->get_current_frame(); // can be 0 on malformed SWF
1002 const gnash::MovieClip& si = m->getRootMovie();
1003 if (curframe + 1 >= si.get_frame_count()) {
1004 quit();
1008 if (_screenShotter.get() && _renderer.get()) {
1009 _screenShotter->screenShot(*_renderer, _advances);
1012 // Only increment advances and check for exit condition when we've
1013 // really changed frame.
1014 if (advanced) {
1015 /// Quit if we've reached the frame advance limit.
1016 if (_maxAdvances && (_advances > _maxAdvances)) {
1017 quit();
1019 ++_advances;
1022 return advanced;
1025 void
1026 Gui::setScreenShotter(std::auto_ptr<ScreenShotter> ss)
1028 _screenShotter.reset(ss.release());
1031 void
1032 Gui::takeScreenShot()
1034 if (!_screenShotter.get()) {
1035 // If no ScreenShotter exists, none was requested at startup.
1036 // We use a default filename pattern.
1037 URL url(_runResources.streamProvider().baseURL());
1038 std::string::size_type p = url.path().rfind('/');
1039 const std::string& name = (p == std::string::npos) ? url.path() :
1040 url.path().substr(p + 1);
1041 const std::string& filename = "screenshot-" + name + "-%f";
1042 _screenShotter.reset(new ScreenShotter(filename, GNASH_FILETYPE_PNG));
1044 assert (_screenShotter.get());
1045 _screenShotter->now();
1048 void
1049 Gui::setCursor(gnash_cursor_type /*newcursor*/)
1051 /* do nothing */
1054 bool
1055 Gui::want_redraw()
1057 return false;
1060 void
1061 Gui::setInvalidatedRegion(const SWFRect& /*bounds*/)
1063 /* do nothing */
1066 void
1067 Gui::setInvalidatedRegions(const InvalidatedRanges& ranges)
1069 // fallback to single regions
1070 geometry::Range2d<int> full = ranges.getFullArea();
1072 SWFRect bounds;
1074 if (full.isFinite()) {
1075 bounds = SWFRect(full.getMinX(), full.getMinY(),
1076 full.getMaxX(), full.getMaxY());
1078 else if (full.isWorld()) {
1079 bounds.set_world();
1082 setInvalidatedRegion(bounds);
1085 #ifdef USE_SWFTREE
1087 std::auto_ptr<movie_root::InfoTree>
1088 Gui::getMovieInfo() const
1090 std::auto_ptr<movie_root::InfoTree> tr;
1092 if (!_stage) {
1093 return tr;
1096 tr.reset(new movie_root::InfoTree());
1098 // Top nodes for the tree:
1099 // 1. VM information
1100 // 2. "Stage" information
1101 // 3. ...
1103 movie_root::InfoTree::iterator topIter = tr->begin();
1104 movie_root::InfoTree::iterator firstLevelIter;
1106 VM& vm = _stage->getVM();
1108 std::ostringstream os;
1111 /// VM top level
1113 os << "SWF " << vm.getSWFVersion();
1114 topIter = tr->insert(topIter, std::make_pair("VM version", os.str()));
1116 // This short-cut is to avoid a bug in movie_root's getMovieInfo,
1117 // which relies on the availability of a _rootMovie for doing
1118 // it's work, while we don't set it if we didn't start..
1120 if (! _started) {
1121 topIter = tr->insert(topIter, std::make_pair("Stage properties",
1122 "not constructed yet"));
1123 return tr;
1126 movie_root& stage = vm.getRoot();
1127 stage.getMovieInfo(*tr, topIter);
1130 /// Mouse entities
1132 topIter = tr->insert(topIter, std::make_pair("Mouse Entities", ""));
1134 const DisplayObject* ch;
1135 ch = stage.getActiveEntityUnderPointer();
1136 if (ch) {
1137 std::stringstream ss;
1138 ss << ch->getTarget() << " (" + typeName(*ch)
1139 << " - depth:" << ch->get_depth()
1140 << " - useHandCursor:" << ch->allowHandCursor()
1141 << ")";
1142 firstLevelIter = tr->append_child(topIter,
1143 std::make_pair("Active entity under mouse pointer", ss.str()));
1146 ch = stage.getEntityUnderPointer();
1147 if (ch) {
1148 std::stringstream ss;
1149 ss << ch->getTarget() << " (" + typeName(*ch)
1150 << " - depth:" << ch->get_depth()
1151 << ")";
1152 firstLevelIter = tr->append_child(topIter,
1153 std::make_pair("Topmost entity under mouse pointer", ss.str()));
1156 ch = stage.getDraggingCharacter();
1157 if (ch) {
1158 std::stringstream ss;
1159 ss << ch->getTarget() << " (" + typeName(*ch)
1160 << " - depth:" << ch->get_depth() << ")";
1161 firstLevelIter = tr->append_child(topIter,
1162 std::make_pair("Dragging character: ", ss.str()));
1166 /// GC row
1168 topIter = tr->insert(topIter, std::make_pair("GC Statistics", ""));
1169 GC::CollectablesCount cc;
1170 _stage->gc().countCollectables(cc);
1172 const std::string lbl = "GC managed ";
1173 for (GC::CollectablesCount::iterator i=cc.begin(), e=cc.end(); i!=e; ++i) {
1174 const std::string& typ = i->first;
1175 std::ostringstream ss;
1176 ss << i->second;
1177 firstLevelIter = tr->append_child(topIter,
1178 std::make_pair(lbl + typ, ss.str()));
1181 tr->sort(firstLevelIter.begin(), firstLevelIter.end());
1183 return tr;
1186 #endif
1188 #ifdef GNASH_FPS_DEBUG
1189 void
1190 Gui::fpsCounterTick()
1193 // increment this *before* the early return so that
1194 // frame count on exit is still valid
1195 ++fps_counter_total;
1197 if (! fps_timer_interval) {
1198 return;
1201 boost::uint64_t current_timer = clocktime::getTicks();
1203 // TODO: keep fps_timer_interval in milliseconds to avoid the multiplication
1204 // at each fpsCounterTick call...
1205 boost::uint64_t interval_ms = (boost::uint64_t)(fps_timer_interval * 1000.0);
1207 if (fps_counter_total==1) {
1208 fps_timer = current_timer;
1209 fps_start_timer = current_timer;
1212 ++fps_counter;
1214 if (current_timer - fps_timer >= interval_ms) {
1216 float secs = (current_timer - fps_timer) / 1000.0;
1217 float secs_total = (current_timer - fps_start_timer)/1000.0;
1219 float rate = fps_counter/secs;
1221 if (secs > 10000000) {
1222 // the timers are unsigned, so when the clock runs "backwards" it leads
1223 // to a very high difference value. In theory, this should never happen
1224 // with ticks, but it does on my machine (which may have a hw problem?).
1225 std::cerr << "Time glitch detected, need to restart FPS counters, sorry..." << std::endl;
1227 fps_timer = current_timer;
1228 fps_start_timer = current_timer;
1229 fps_counter_total = 0;
1230 fps_counter = 0;
1231 return;
1234 // first FPS message?
1235 if (fps_timer == fps_start_timer) { // they're ints, so we can compare
1236 fps_rate_min = rate;
1237 fps_rate_max = rate;
1238 } else {
1239 fps_rate_min = std::min<float>(fps_rate_min, rate);
1240 fps_rate_max = std::max<float>(fps_rate_max, rate);
1243 float avg = fps_counter_total / secs_total;
1245 //log_debug("Effective frame rate: %0.2f fps", (float)(fps_counter/secs));
1246 std::cerr << boost::format("Effective frame rate: %0.2f fps "
1247 "(min %0.2f, avg %0.2f, max %0.2f, "
1248 "%u frames in %0.1f secs total, "
1249 "dropped %u)") % rate %
1250 fps_rate_min % avg % fps_rate_max %
1251 fps_counter_total % secs_total %
1252 frames_dropped << std::endl;
1254 fps_counter = 0;
1255 fps_timer = current_timer;
1260 #endif
1262 void
1263 Gui::addFlashVars(Gui::VariableMap& from)
1265 for (VariableMap::iterator i=from.begin(), ie=from.end(); i!=ie; ++i) {
1266 _flashVars[i->first] = i->second;
1270 void
1271 Gui::setMovieDefinition(movie_definition* md)
1273 assert(!_movieDef);
1274 _movieDef = md;
1277 void
1278 Gui::setStage(movie_root* stage)
1280 assert(stage);
1281 assert(!_stage);
1282 _stage = stage;
1285 bool
1286 Gui::yesno(const std::string& question)
1288 log_error("This gui didn't override 'yesno', assuming 'yes' answer to "
1289 "question: %s", question);
1290 return true;
1293 void
1294 Gui::setQuality(Quality q)
1296 if (!_stage) {
1297 log_error("Gui::setQuality called before a movie_root was available");
1298 return;
1300 _stage->setQuality(q);
1303 Quality
1304 Gui::getQuality() const
1306 if (!_stage) {
1307 log_error("Gui::getQuality called before a movie_root was available");
1308 // just a guess..
1309 return QUALITY_HIGH;
1311 return _stage->getQuality();
1314 void
1315 Gui::setFDCallback(int fd, boost::function<void ()> callback)
1317 log_debug("Setting callback for fd #%d", fd);
1319 _fd_callbacks[fd] = callback;
1321 watchFD(fd);
1325 void
1326 Gui::callCallback(int fd)
1328 std::map<int, boost::function<void ()> >::iterator it = _fd_callbacks.find(fd);
1330 if (it == _fd_callbacks.end()) {
1331 log_error("Attempted to call a callback for an unregistered fd.");
1332 return;
1335 boost::function<void()>& f = it->second;
1337 f();
1339 // end of namespace
1342 // local Variables:
1343 // mode: C++
1344 // indent-tabs-mode: nil
1345 // End: