openMSX
Display.cc
Go to the documentation of this file.
1 #include "Display.hh"
2 #include "RendererFactory.hh"
3 #include "Layer.hh"
4 #include "VideoSystem.hh"
5 #include "VideoLayer.hh"
6 #include "EventDistributor.hh"
7 #include "FinishFrameEvent.hh"
8 #include "FileOperations.hh"
9 #include "FileContext.hh"
10 #include "InputEvents.hh"
11 #include "CliComm.hh"
12 #include "Timer.hh"
13 #include "BooleanSetting.hh"
14 #include "IntegerSetting.hh"
15 #include "EnumSetting.hh"
16 #include "Reactor.hh"
17 #include "MSXMotherBoard.hh"
18 #include "HardwareConfig.hh"
19 #include "XMLElement.hh"
21 #include "CommandException.hh"
22 #include "StringOp.hh"
23 #include "Version.hh"
24 #include "build-info.hh"
25 #include "checked_cast.hh"
26 #include "stl.hh"
27 #include "unreachable.hh"
28 #include <algorithm>
29 #include <cassert>
30 
31 using std::string;
32 using std::vector;
33 
34 namespace openmsx {
35 
37  : RTSchedulable(reactor_.getRTScheduler())
38  , screenShotCmd(reactor_.getCommandController(), *this)
39  , fpsInfo(reactor_.getOpenMSXInfoCommand(), *this)
40  , osdGui(reactor_.getCommandController(), *this)
41  , reactor(reactor_)
42  , renderSettings(reactor.getCommandController())
43  , commandConsole(reactor.getGlobalCommandController(),
44  reactor.getEventDistributor(), *this)
45  , currentRenderer(RenderSettings::UNINITIALIZED)
46  , switchInProgress(false)
47 {
48  frameDurationSum = 0;
49  for (unsigned i = 0; i < NUM_FRAME_DURATIONS; ++i) {
50  frameDurations.addFront(20);
51  frameDurationSum += 20;
52  }
53  prevTimeStamp = Timer::getTime();
54 
55  EventDistributor& eventDistributor = reactor.getEventDistributor();
57  *this);
59  *this);
61  *this);
63  *this);
64 #if PLATFORM_ANDROID
66  *this);
67 #endif
68  renderSettings.getRendererSetting().attach(*this);
69  renderSettings.getFullScreenSetting().attach(*this);
70  renderSettings.getScaleFactorSetting().attach(*this);
71  renderFrozen = false;
72 }
73 
75 {
76  renderSettings.getRendererSetting().detach(*this);
77  renderSettings.getFullScreenSetting().detach(*this);
78  renderSettings.getScaleFactorSetting().detach(*this);
79 
80  EventDistributor& eventDistributor = reactor.getEventDistributor();
81 #if PLATFORM_ANDROID
83  *this);
84 #endif
86  *this);
88  *this);
90  *this);
92  *this);
93 
94  resetVideoSystem();
95 
96  assert(listeners.empty());
97 }
98 
100 {
101  assert(!videoSystem);
102  assert(currentRenderer == RenderSettings::UNINITIALIZED);
103  assert(!switchInProgress);
104  currentRenderer = renderSettings.getRenderer();
105  switchInProgress = true;
106  doRendererSwitch();
107 }
108 
110 {
111  assert(videoSystem);
112  return *videoSystem;
113 }
114 
115 void Display::resetVideoSystem()
116 {
117  videoSystem.reset();
118  // At this point all layers expect for the Video9000 layer
119  // should be gone.
120  //assert(layers.empty());
121 }
122 
124 {
125  return reactor.getCliComm();
126 }
127 
129 {
130  assert(!contains(listeners, &listener));
131  listeners.push_back(&listener);
132 }
133 
135 {
136  listeners.erase(find_unguarded(listeners, &listener));
137 }
138 
140 {
141  for (auto& l : layers) {
142  if (l->getZ() == Layer::Z_MSX_ACTIVE) {
143  return l;
144  }
145  }
146  return nullptr;
147 }
148 
149 Display::Layers::iterator Display::baseLayer()
150 {
151  // Note: It is possible to cache this, but since the number of layers is
152  // low at the moment, it's not really worth it.
153  auto it = end(layers);
154  while (true) {
155  if (it == begin(layers)) {
156  // There should always be at least one opaque layer.
157  // TODO: This is not true for DummyVideoSystem.
158  // Anyway, a missing layer will probably stand out visually,
159  // so do we really have to assert on it?
160  //UNREACHABLE;
161  return it;
162  }
163  --it;
164  if ((*it)->getCoverage() == Layer::COVER_FULL) return it;
165  }
166 }
167 
168 void Display::executeRT()
169 {
170  repaint();
171 }
172 
173 int Display::signalEvent(const std::shared_ptr<const Event>& event)
174 {
175  if (event->getType() == OPENMSX_FINISH_FRAME_EVENT) {
176  auto& ffe = checked_cast<const FinishFrameEvent&>(*event);
177  if (ffe.needRender()) {
178  repaint();
180  std::make_shared<SimpleEvent>(
182  }
183  } else if (event->getType() == OPENMSX_SWITCH_RENDERER_EVENT) {
184  doRendererSwitch();
185  } else if (event->getType() == OPENMSX_MACHINE_LOADED_EVENT) {
186  setWindowTitle();
187  } else if (event->getType() == OPENMSX_EXPOSE_EVENT) {
188  // Don't render too often, and certainly not when the screen
189  // will anyway soon be rendered.
190  repaintDelayed(100 * 1000); // 10fps
191  } else if (PLATFORM_ANDROID && event->getType() == OPENMSX_FOCUS_EVENT) {
192  // On Android, the rendering must be frozen when the app is sent to
193  // the background, because Android takes away all graphics resources
194  // from the app. It simply destroys the entire graphics context.
195  // Though, a repaint() must happen within the focus-lost event
196  // so that the SDL Android port realises that the graphix context
197  // is gone and will re-build it again on the first flush to the
198  // surface after the focus has been regained.
199 
200  // Perform a repaint before updating the renderFrozen flag:
201  // -When loosing the focus, this repaint will flush a last
202  // time the SDL surface, making sure that the Android SDL
203  // port discovers that the graphics context is gone.
204  // -When gaining the focus, this repaint does nothing as
205  // the renderFrozen flag is still false
206  repaint();
207  auto& focusEvent = checked_cast<const FocusEvent&>(*event);
208  ad_printf("Setting renderFrozen to %d", !focusEvent.getGain());
209  renderFrozen = !focusEvent.getGain();
210  }
211  return 0;
212 }
213 
214 void Display::setWindowTitle()
215 {
216  string title = Version::full();
217  if (!Version::RELEASE) {
218  title += " [";
219  title += BUILD_FLAVOUR;
220  title += ']';
221  }
222  if (MSXMotherBoard* motherboard = reactor.getMotherBoard()) {
223  if (const HardwareConfig* machine = motherboard->getMachineConfig()) {
224  const XMLElement& config = machine->getConfig();
225  title += " - " +
226  config.getChild("info").getChildData("manufacturer") + ' ' +
227  config.getChild("info").getChildData("code");
228  }
229  }
230  videoSystem->setWindowTitle(title);
231 }
232 
233 void Display::update(const Setting& setting)
234 {
235  if (&setting == &renderSettings.getRendererSetting()) {
236  checkRendererSwitch();
237  } else if (&setting == &renderSettings.getFullScreenSetting()) {
238  checkRendererSwitch();
239  } else if (&setting == &renderSettings.getScaleFactorSetting()) {
240  checkRendererSwitch();
241  } else {
242  UNREACHABLE;
243  }
244 }
245 
246 void Display::checkRendererSwitch()
247 {
248  if (switchInProgress) {
249  // This method only queues a request to switch renderer (see
250  // comments below why). If there already is such a request
251  // queued we don't need to do it again.
252  return;
253  }
254  auto newRenderer = renderSettings.getRenderer();
255  if ((newRenderer != currentRenderer) ||
256  !getVideoSystem().checkSettings()) {
257  currentRenderer = newRenderer;
258  // don't do the actualing swithing in the Tcl callback
259  // it seems creating and destroying Settings (= Tcl vars)
260  // causes problems???
261  switchInProgress = true;
263  std::make_shared<SimpleEvent>(
265  }
266 }
267 
268 void Display::doRendererSwitch()
269 {
270  assert(switchInProgress);
271 
272  bool success = false;
273  while (!success) {
274  try {
275  doRendererSwitch2();
276  success = true;
277  } catch (MSXException& e) {
278  auto& rendererSetting = renderSettings.getRendererSetting();
279  string errorMsg = "Couldn't activate renderer " +
280  rendererSetting.getString() +
281  ": " + e.getMessage();
282  // now try some things that might work against this:
283  if (rendererSetting.getEnum() != RenderSettings::SDL) {
284  errorMsg += "\nTrying to switch to SDL renderer instead...";
285  rendererSetting.setEnum(RenderSettings::SDL);
286  currentRenderer = RenderSettings::SDL;
287  } else {
288  auto& scaleFactorSetting = renderSettings.getScaleFactorSetting();
289  unsigned curval = scaleFactorSetting.getInt();
290  if (curval == 1) throw MSXException(e.getMessage() + " (and I have no other ideas to try...)"); // give up and die... :(
291  errorMsg += "\nTrying to decrease scale_factor setting from " + StringOp::toString(curval) + " to " + StringOp::toString(curval - 1) + "...";
292  scaleFactorSetting.setInt(curval - 1);
293  }
294  getCliComm().printWarning(errorMsg);
295  }
296  }
297 
298  switchInProgress = false;
299 }
300 
301 void Display::doRendererSwitch2()
302 {
303  for (auto& l : listeners) {
304  l->preVideoSystemChange();
305  }
306 
307  resetVideoSystem();
308  videoSystem = RendererFactory::createVideoSystem(reactor);
309  setWindowTitle();
310 
311  for (auto& l : listeners) {
312  l->postVideoSystemChange();
313  }
314 }
315 
317 {
318  if (switchInProgress) {
319  // The checkRendererSwitch() method will queue a
320  // SWITCH_RENDERER_EVENT, but before that event is handled
321  // we shouldn't do any repaints (with inconsistent setting
322  // values and render objects). This can happen when this
323  // method gets called because of a DELAYED_REPAINT_EVENT
324  // (DELAYED_REPAINT_EVENT was already queued before
325  // SWITCH_RENDERER_EVENT is queued).
326  return;
327  }
328 
329  cancelRT(); // cancel delayed repaint
330 
331  if (!renderFrozen) {
332  assert(videoSystem);
333  if (OutputSurface* surface = videoSystem->getOutputSurface()) {
334  repaint(*surface);
335  videoSystem->flush();
336  }
337  }
338 
339  // update fps statistics
340  auto now = Timer::getTime();
341  auto duration = now - prevTimeStamp;
342  prevTimeStamp = now;
343  frameDurationSum += duration - frameDurations.removeBack();
344  frameDurations.addFront(duration);
345 }
346 
348 {
349  for (auto it = baseLayer(); it != end(layers); ++it) {
350  if ((*it)->getCoverage() != Layer::COVER_NONE) {
351  (*it)->paint(surface);
352  }
353  }
354 }
355 
356 void Display::repaintDelayed(uint64_t delta)
357 {
358  if (isPendingRT()) {
359  // already a pending repaint
360  return;
361  }
362  scheduleRT(unsigned(delta));
363 }
364 
366 {
367  int z = layer.getZ();
368  auto it = find_if(begin(layers), end(layers),
369  [&](Layer* l) { return l->getZ() > z; });
370  layers.insert(it, &layer);
371  layer.setDisplay(*this);
372 }
373 
375 {
376  layers.erase(find_unguarded(layers, &layer));
377 }
378 
379 void Display::updateZ(Layer& layer)
380 {
381  // Remove at old Z-index...
382  removeLayer(layer);
383  // ...and re-insert at new Z-index.
384  addLayer(layer);
385 }
386 
387 
388 // ScreenShotCmd
389 
390 Display::ScreenShotCmd::ScreenShotCmd(CommandController& commandController,
391  Display& display_)
392  : Command(commandController, "screenshot")
393  , display(display_)
394 {
395 }
396 
397 void Display::ScreenShotCmd::execute(array_ref<TclObject> tokens, TclObject& result)
398 {
399  bool rawShot = false;
400  bool withOsd = false;
401  bool doubleSize = false;
402  string_ref prefix = "openmsx";
403  vector<TclObject> arguments;
404  for (unsigned i = 1; i < tokens.size(); ++i) {
405  string_ref tok = tokens[i].getString();
406  if (StringOp::startsWith(tok, '-')) {
407  if (tok == "--") {
408  arguments.insert(end(arguments),
409  std::begin(tokens) + i + 1, std::end(tokens));
410  break;
411  }
412  if (tok == "-prefix") {
413  if (++i == tokens.size()) {
414  throw CommandException("Missing argument");
415  }
416  prefix = tokens[i].getString();
417  } else if (tok == "-raw") {
418  rawShot = true;
419  } else if (tok == "-msxonly") {
420  display.getCliComm().printWarning(
421  "The -msxonly option has been deprecated and will "
422  "be removed in a future release. Instead, use the "
423  "-raw option for the same effect.");
424  rawShot = true;
425  } else if (tok == "-doublesize") {
426  doubleSize = true;
427  } else if (tok == "-with-osd") {
428  withOsd = true;
429  } else {
430  throw CommandException("Invalid option: " + tok);
431  }
432  } else {
433  arguments.push_back(tokens[i]);
434  }
435  }
436  if (doubleSize && !rawShot) {
437  throw CommandException("-doublesize option can only be used in "
438  "combination with -raw");
439  }
440  if (rawShot && withOsd) {
441  throw CommandException("-with-osd cannot be used in "
442  "combination with -raw");
443  }
444 
445  string_ref fname;
446  switch (arguments.size()) {
447  case 0:
448  // nothing
449  break;
450  case 1:
451  fname = arguments[0].getString();
452  break;
453  default:
454  throw SyntaxError();
455  }
457  fname, "screenshots", prefix, ".png");
458 
459  if (!rawShot) {
460  // include all layers (OSD stuff, console)
461  try {
462  display.getVideoSystem().takeScreenShot(filename, withOsd);
463  } catch (MSXException& e) {
464  throw CommandException(
465  "Failed to take screenshot: " + e.getMessage());
466  }
467  } else {
468  auto videoLayer = dynamic_cast<VideoLayer*>(
469  display.findActiveLayer());
470  if (!videoLayer) {
471  throw CommandException(
472  "Current renderer doesn't support taking screenshots.");
473  }
474  unsigned height = doubleSize ? 480 : 240;
475  try {
476  videoLayer->takeRawScreenShot(height, filename);
477  } catch (MSXException& e) {
478  throw CommandException(
479  "Failed to take screenshot: " + e.getMessage());
480  }
481  }
482 
483  display.getCliComm().printInfo("Screen saved to " + filename);
484  result.setString(filename);
485 }
486 
487 string Display::ScreenShotCmd::help(const vector<string>& /*tokens*/) const
488 {
489  // Note: -no-sprites option is implemented in Tcl
490  return
491  "screenshot Write screenshot to file \"openmsxNNNN.png\"\n"
492  "screenshot <filename> Write screenshot to indicated file\n"
493  "screenshot -prefix foo Write screenshot to file \"fooNNNN.png\"\n"
494  "screenshot -raw 320x240 raw screenshot (of MSX screen only)\n"
495  "screenshot -raw -doublesize 640x480 raw screenshot (of MSX screen only)\n"
496  "screenshot -with-osd Include OSD elements in the screenshot\n"
497  "screenshot -no-sprites Don't include sprites in the screenshot\n";
498 }
499 
500 void Display::ScreenShotCmd::tabCompletion(vector<string>& tokens) const
501 {
502  static const char* const extra[] = {
503  "-prefix", "-raw", "-doublesize", "-with-osd", "-no-sprites",
504  };
505  completeFileName(tokens, UserFileContext(), extra);
506 }
507 
508 
509 // FpsInfoTopic
510 
511 Display::FpsInfoTopic::FpsInfoTopic(InfoCommand& openMSXInfoCommand,
512  Display& display_)
513  : InfoTopic(openMSXInfoCommand, "fps")
514  , display(display_)
515 {
516 }
517 
518 void Display::FpsInfoTopic::execute(array_ref<TclObject> /*tokens*/,
519  TclObject& result) const
520 {
521  double fps = 1000000.0 * Display::NUM_FRAME_DURATIONS / display.frameDurationSum;
522  result.setDouble(fps);
523 }
524 
525 string Display::FpsInfoTopic::help(const vector<string>& /*tokens*/) const
526 {
527  return "Returns the current rendering speed in frames per second.";
528 }
529 
530 } // namespace openmsx
void setDisplay(LayerListener &display_)
Store pointer to Display.
Definition: Layer.hh:59
Contains the main loop of openMSX.
Definition: Reactor.hh:62
Sent when a OPENMSX_FINISH_FRAME_EVENT caused a redraw of the screen.
Definition: Event.hh:37
void createVideoSystem()
Definition: Display.cc:99
string_ref::const_iterator end(const string_ref &x)
Definition: string_ref.hh:150
Layer is not visible, that is completely transparent.
Definition: Layer.hh:39
size_type size() const
Definition: array_ref.hh:61
Send when a (new) machine configuration is loaded.
Definition: Event.hh:52
ITER find_unguarded(ITER first, ITER last, const VAL &val)
Faster alternative to 'find' when it's guaranteed that the value will be found (if not the behavior i...
Definition: stl.hh:114
Layer * findActiveLayer() const
Definition: Display.cc:139
void registerEventListener(EventType type, EventListener &listener, Priority priority=OTHER)
Registers a given object to receive certain events.
void addLayer(Layer &layer)
Definition: Display.cc:365
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
string toString(long long a)
Definition: StringOp.cc:156
void printWarning(string_ref message)
Definition: CliComm.cc:28
Interface for display layers.
Definition: Layer.hh:11
CliComm & getCliComm() const
Definition: Display.cc:123
Display(Reactor &reactor)
Definition: Display.cc:36
Layer fully covers the screen: any underlying layers are invisible.
Definition: Layer.hh:32
bool contains(ITER first, ITER last, const VAL &val)
Check if a range contains a given value, using linear search.
Definition: stl.hh:95
void distributeEvent(const EventPtr &event)
Schedule the given event for delivery.
This class implements a subset of the proposal for std::string_ref (proposed for the next c++ standar...
Definition: string_ref.hh:18
A frame buffer where pixels can be written to.
unique_ptr< VideoSystem > createVideoSystem(Reactor &reactor)
Create the video system required by the current renderer setting.
#define PLATFORM_ANDROID
Definition: build-info.hh:18
static const bool RELEASE
Definition: Version.hh:12
EventDistributor & getEventDistributor()
Definition: Reactor.hh:78
VideoSystem & getVideoSystem()
Definition: Display.cc:109
void attach(Observer< T > &observer)
Definition: Subject.hh:52
void repaint()
Redraw the display.
Definition: Display.cc:316
Sent when VDP (V99x8 or V9990) reaches the end of a frame.
Definition: Event.hh:31
void removeLayer(Layer &layer)
Definition: Display.cc:374
bool startsWith(string_ref total, string_ref part)
Definition: StringOp.cc:242
This class implements a subset of the proposal for std::array_ref (proposed for the next c++ standard...
Definition: array_ref.hh:19
void detach(VideoSystemChangeListener &listener)
Definition: Display.cc:134
RendererSetting & getRendererSetting()
The current renderer.
MSXMotherBoard * getMotherBoard() const
Definition: Reactor.cc:331
string_ref getString() const
Definition: EnumSetting.hh:109
string parseCommandFileArgument(string_ref argument, string_ref directory, string_ref prefix, string_ref extension)
Helper function for parsing filename arguments in Tcl commands.
RendererID getRenderer() const
Video back-end system.
Definition: VideoSystem.hh:20
void repaintDelayed(uint64_t delta)
Definition: Display.cc:356
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
Send when (part of) the openMSX window gets exposed, and thus should be repainted.
Definition: Event.hh:61
ZIndex getZ() const
Query the Z-index of this layer.
Definition: Layer.hh:50
void scheduleRT(uint64_t delta)
void attach(VideoSystemChangeListener &listener)
Definition: Display.cc:128
bool isPendingRT() const
Class containing all settings for renderers.
void detach(Observer< T > &observer)
Definition: Subject.hh:58
static std::string full()
Definition: Version.cc:7
CliComm & getCliComm()
Definition: Reactor.cc:268
BooleanSetting & getFullScreenSetting()
Full screen [on, off].
uint64_t getTime()
Get current (real) time in us.
Definition: Timer.cc:24
void addFront(const T &element)
string_ref::const_iterator begin(const string_ref &x)
Definition: string_ref.hh:149
#define ad_printf(...)
Definition: openmsx.hh:10
IntegerSetting & getScaleFactorSetting()
The current scaling factor.
#define UNREACHABLE
Definition: unreachable.hh:35