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