openMSX
MSXMotherBoard.cc
Go to the documentation of this file.
1 #include "MSXMotherBoard.hh"
2 #include "Reactor.hh"
3 #include "MSXDevice.hh"
4 #include "ReverseManager.hh"
5 #include "HardwareConfig.hh"
6 #include "ConfigException.hh"
7 #include "XMLElement.hh"
8 #include "MSXCliComm.hh"
9 #include "GlobalCliComm.hh"
10 #include "MSXCommandController.hh"
11 #include "Scheduler.hh"
12 #include "Schedulable.hh"
13 #include "CartridgeSlotManager.hh"
14 #include "EventDistributor.hh"
15 #include "Debugger.hh"
16 #include "SimpleDebuggable.hh"
17 #include "MSXMixer.hh"
18 #include "PluggingController.hh"
19 #include "MSXCPUInterface.hh"
20 #include "MSXCPU.hh"
21 #include "PanasonicMemory.hh"
22 #include "MSXDeviceSwitch.hh"
23 #include "MSXMapperIO.hh"
24 #include "CassettePort.hh"
25 #include "JoystickPort.hh"
26 #include "RenShaTurbo.hh"
27 #include "LedStatus.hh"
28 #include "MSXEventDistributor.hh"
30 #include "EventDelay.hh"
31 #include "RealTime.hh"
32 #include "DeviceFactory.hh"
33 #include "BooleanSetting.hh"
34 #include "GlobalSettings.hh"
35 #include "Command.hh"
36 #include "CommandException.hh"
37 #include "InfoTopic.hh"
38 #include "FileException.hh"
39 #include "TclObject.hh"
40 #include "Observer.hh"
41 #include "serialize.hh"
42 #include "serialize_stl.hh"
43 #include "ScopedAssign.hh"
44 #include "one_of.hh"
45 #include "ranges.hh"
46 #include "stl.hh"
47 #include "unreachable.hh"
48 #include "view.hh"
49 #include <cassert>
50 #include <functional>
51 #include <iostream>
52 #include <memory>
53 
54 using std::make_unique;
55 using std::string;
56 using std::unique_ptr;
57 using std::vector;
58 
59 namespace openmsx {
60 
62 {
63 public:
64  explicit AddRemoveUpdate(MSXMotherBoard& motherBoard);
66  AddRemoveUpdate(const AddRemoveUpdate&) = delete;
68 private:
69  MSXMotherBoard& motherBoard;
70 };
71 
72 class ResetCmd final : public RecordedCommand
73 {
74 public:
75  explicit ResetCmd(MSXMotherBoard& motherBoard);
76  void execute(span<const TclObject> tokens, TclObject& result,
77  EmuTime::param time) override;
78  [[nodiscard]] string help(const vector<string>& tokens) const override;
79 private:
80  MSXMotherBoard& motherBoard;
81 };
82 
83 class LoadMachineCmd final : public Command
84 {
85 public:
86  explicit LoadMachineCmd(MSXMotherBoard& motherBoard);
87  void execute(span<const TclObject> tokens, TclObject& result) override;
88  [[nodiscard]] string help(const vector<string>& tokens) const override;
89  void tabCompletion(vector<string>& tokens) const override;
90 private:
91  MSXMotherBoard& motherBoard;
92 };
93 
94 class ListExtCmd final : public Command
95 {
96 public:
97  explicit ListExtCmd(MSXMotherBoard& motherBoard);
98  void execute(span<const TclObject> tokens, TclObject& result) override;
99  [[nodiscard]] string help(const vector<string>& tokens) const override;
100 private:
101  MSXMotherBoard& motherBoard;
102 };
103 
104 class RemoveExtCmd final : public RecordedCommand
105 {
106 public:
107  explicit RemoveExtCmd(MSXMotherBoard& motherBoard);
108  void execute(span<const TclObject> tokens, TclObject& result,
109  EmuTime::param time) override;
110  [[nodiscard]] string help(const vector<string>& tokens) const override;
111  void tabCompletion(vector<string>& tokens) const override;
112 private:
113  MSXMotherBoard& motherBoard;
114 };
115 
116 class MachineNameInfo final : public InfoTopic
117 {
118 public:
119  explicit MachineNameInfo(MSXMotherBoard& motherBoard);
120  void execute(span<const TclObject> tokens,
121  TclObject& result) const override;
122  [[nodiscard]] string help(const vector<string>& tokens) const override;
123 private:
124  MSXMotherBoard& motherBoard;
125 };
126 
127 class MachineTypeInfo final : public InfoTopic
128 {
129 public:
130  explicit MachineTypeInfo(MSXMotherBoard& motherBoard);
131  void execute(span<const TclObject> tokens,
132  TclObject& result) const override;
133  [[nodiscard]] string help(const vector<string>& tokens) const override;
134 private:
135  MSXMotherBoard& motherBoard;
136 };
137 
138 class MachineExtensionInfo final : public InfoTopic
139 {
140 public:
141  explicit MachineExtensionInfo(MSXMotherBoard& motherBoard);
142  void execute(span<const TclObject> tokens,
143  TclObject& result) const override;
144  [[nodiscard]] string help(const vector<string>& tokens) const override;
145  void tabCompletion(vector<string>& tokens) const override;
146 private:
147  MSXMotherBoard& motherBoard;
148 };
149 
150 class DeviceInfo final : public InfoTopic
151 {
152 public:
153  explicit DeviceInfo(MSXMotherBoard& motherBoard);
154  void execute(span<const TclObject> tokens,
155  TclObject& result) const override;
156  [[nodiscard]] string help(const vector<string>& tokens) const override;
157  void tabCompletion(vector<string>& tokens) const override;
158 private:
159  MSXMotherBoard& motherBoard;
160 };
161 
162 class FastForwardHelper final : private Schedulable
163 {
164 public:
165  explicit FastForwardHelper(MSXMotherBoard& motherBoard);
166  void setTarget(EmuTime::param targetTime);
167 private:
168  void executeUntil(EmuTime::param time) override;
169  MSXMotherBoard& motherBoard;
170 };
171 
173 {
174 public:
175  explicit JoyPortDebuggable(MSXMotherBoard& motherBoard);
176  [[nodiscard]] byte read(unsigned address, EmuTime::param time) override;
177  void write(unsigned address, byte value) override;
178 };
179 
180 class SettingObserver final : public Observer<Setting>
181 {
182 public:
183  explicit SettingObserver(MSXMotherBoard& motherBoard);
184  void update(const Setting& setting) noexcept override;
185 private:
186  MSXMotherBoard& motherBoard;
187 };
188 
189 
190 static unsigned machineIDCounter = 0;
191 
193  : reactor(reactor_)
194  , machineID(strCat("machine", ++machineIDCounter))
195  , mapperIOCounter(0)
196  , machineConfig(nullptr)
197  , msxCliComm(make_unique<MSXCliComm>(*this, reactor.getGlobalCliComm()))
198  , msxEventDistributor(make_unique<MSXEventDistributor>())
199  , stateChangeDistributor(make_unique<StateChangeDistributor>())
200  , msxCommandController(make_unique<MSXCommandController>(
201  reactor.getGlobalCommandController(), reactor,
202  *this, *msxEventDistributor, machineID))
203  , scheduler(make_unique<Scheduler>())
204  , msxMixer(make_unique<MSXMixer>(
205  reactor.getMixer(), *this,
206  reactor.getGlobalSettings()))
207  , videoSourceSetting(*msxCommandController)
208  , fastForwardHelper(make_unique<FastForwardHelper>(*this))
209  , settingObserver(make_unique<SettingObserver>(*this))
210  , powerSetting(reactor.getGlobalSettings().getPowerSetting())
211  , powered(false)
212  , active(false)
213  , fastForwarding(false)
214 {
215  slotManager = make_unique<CartridgeSlotManager>(*this);
216  reverseManager = make_unique<ReverseManager>(*this);
217  resetCommand = make_unique<ResetCmd>(*this);
218  loadMachineCommand = make_unique<LoadMachineCmd>(*this);
219  listExtCommand = make_unique<ListExtCmd>(*this);
220  extCommand = make_unique<ExtCmd>(*this, "ext");
221  removeExtCommand = make_unique<RemoveExtCmd>(*this);
222  machineNameInfo = make_unique<MachineNameInfo>(*this);
223  machineTypeInfo = make_unique<MachineTypeInfo>(*this);
224  machineExtensionInfo = make_unique<MachineExtensionInfo>(*this);
225  deviceInfo = make_unique<DeviceInfo>(*this);
226  debugger = make_unique<Debugger>(*this);
227 
228  msxMixer->mute(); // powered down
229 
230  // Do this before machine-specific settings are created, otherwise
231  // a setting-info clicomm message is send with a machine id that hasn't
232  // been announced yet over clicomm.
233  addRemoveUpdate = make_unique<AddRemoveUpdate>(*this);
234 
235  // TODO: Initialization of this field cannot be done much earlier because
236  // EventDelay creates a setting, calling getMSXCliComm()
237  // on MSXMotherBoard, so "pimpl" has to be set up already.
238  eventDelay = make_unique<EventDelay>(
239  *scheduler, *msxCommandController,
240  reactor.getEventDistributor(), *msxEventDistributor,
241  *reverseManager);
242  realTime = make_unique<RealTime>(
243  *this, reactor.getGlobalSettings(), *eventDelay);
244 
245  powerSetting.attach(*settingObserver);
246 }
247 
249 {
250  powerSetting.detach(*settingObserver);
251  deleteMachine();
252 
253  assert(mapperIOCounter == 0);
254  assert(availableDevices.empty());
255  assert(extensions.empty());
256  assert(!machineConfig2);
257  assert(!getMachineConfig());
258 }
259 
260 void MSXMotherBoard::deleteMachine()
261 {
262  while (!extensions.empty()) {
263  try {
264  removeExtension(*extensions.back());
265  } catch (MSXException& e) {
266  std::cerr << "Internal error: failed to remove "
267  "extension while deleting a machine: "
268  << e.getMessage() << '\n';
269  UNREACHABLE;
270  }
271  }
272 
273  machineConfig2.reset();
274  machineConfig = nullptr;
275 }
276 
278 {
279  assert(!getMachineConfig());
280  machineConfig = machineConfig_;
281 
282  // make sure the CPU gets instantiated from the main thread
283  assert(!msxCpu);
284  msxCpu = make_unique<MSXCPU>(*this);
285  msxCpuInterface = make_unique<MSXCPUInterface>(*this);
286 }
287 
289 {
290  if (const HardwareConfig* machine = getMachineConfig()) {
291  return machine->getConfig().getChild("info").getChildData("type");
292  } else {
293  return "";
294  }
295 }
296 
298 {
299  const HardwareConfig* config = getMachineConfig();
300  assert(config);
301  return config->getConfig().getChild("devices").findChild("S1990") != nullptr;
302 }
303 
304 string MSXMotherBoard::loadMachine(const string& machine)
305 {
306  assert(machineName.empty());
307  assert(extensions.empty());
308  assert(!machineConfig2);
309  assert(!getMachineConfig());
310 
311  try {
312  machineConfig2 = HardwareConfig::createMachineConfig(*this, machine);
313  setMachineConfig(machineConfig2.get());
314  } catch (FileException& e) {
315  throw MSXException("Machine \"", machine, "\" not found: ",
316  e.getMessage());
317  } catch (MSXException& e) {
318  throw MSXException("Error in \"", machine, "\" machine: ",
319  e.getMessage());
320  }
321  try {
322  machineConfig->parseSlots();
323  machineConfig->createDevices();
324  } catch (MSXException& e) {
325  throw MSXException("Error in \"", machine, "\" machine: ",
326  e.getMessage());
327  }
328  if (powerSetting.getBoolean()) {
329  powerUp();
330  }
331  machineName = machine;
332  return machineName;
333 }
334 
335 string MSXMotherBoard::loadExtension(std::string_view name, std::string_view slotname)
336 {
337  unique_ptr<HardwareConfig> extension;
338  try {
340  *this, string(name), slotname);
341  } catch (FileException& e) {
342  throw MSXException(
343  "Extension \"", name, "\" not found: ", e.getMessage());
344  } catch (MSXException& e) {
345  throw MSXException(
346  "Error in \"", name, "\" extension: ", e.getMessage());
347  }
348  return insertExtension(name, std::move(extension));
349 }
350 
352  std::string_view name, unique_ptr<HardwareConfig> extension)
353 {
354  try {
355  extension->parseSlots();
356  extension->createDevices();
357  } catch (MSXException& e) {
358  throw MSXException(
359  "Error in \"", name, "\" extension: ", e.getMessage());
360  }
361  string result = extension->getName();
362  extensions.push_back(std::move(extension));
363  getMSXCliComm().update(CliComm::EXTENSION, result, "add");
364  return result;
365 }
366 
367 HardwareConfig* MSXMotherBoard::findExtension(std::string_view extensionName)
368 {
369  auto it = ranges::find_if(extensions, [&](auto& v) {
370  return v->getName() == extensionName;
371  });
372  return (it != end(extensions)) ? it->get() : nullptr;
373 }
374 
376 {
377  extension.testRemove();
378  getMSXCliComm().update(CliComm::EXTENSION, extension.getName(), "remove");
379  auto it = rfind_if_unguarded(extensions,
380  [&](auto& e) { return e.get() == &extension; });
381  extensions.erase(it);
382 }
383 
385 {
386  return *msxCliComm;
387 }
388 
390 {
391  assert(getMachineConfig()); // needed for PluggableFactory::createAll()
392  if (!pluggingController) {
393  pluggingController = make_unique<PluggingController>(*this);
394  }
395  return *pluggingController;
396 }
397 
399 {
400  assert(getMachineConfig()); // because CPU needs to know if we're
401  // emulating turbor or not
402  return *msxCpu;
403 }
404 
406 {
407  assert(getMachineConfig());
408  return *msxCpuInterface;
409 }
410 
412 {
413  if (!panasonicMemory) {
414  panasonicMemory = make_unique<PanasonicMemory>(*this);
415  }
416  return *panasonicMemory;
417 }
418 
420 {
421  if (!deviceSwitch) {
423  }
424  return *deviceSwitch;
425 }
426 
428 {
429  if (!cassettePort) {
430  assert(getMachineConfig());
431  if (getMachineConfig()->getConfig().findChild("CassettePort")) {
432  cassettePort = make_unique<CassettePort>(*getMachineConfig());
433  } else {
434  cassettePort = make_unique<DummyCassettePort>();
435  }
436  }
437  return *cassettePort;
438 }
439 
441 {
442  assert(port < 2);
443  if (!joystickPort[0]) {
444  assert(getMachineConfig());
445  // some MSX machines only have 1 instead of 2 joystick ports
446  std::string_view ports = getMachineConfig()->getConfig().getChildData(
447  "JoystickPorts", "AB");
448  if (ports != one_of("AB", "", "A", "B")) {
449  throw ConfigException(
450  "Invalid JoystickPorts specification, "
451  "should be one of '', 'A', 'B' or 'AB'.");
452  }
454  if (ports == one_of("AB", "A")) {
455  joystickPort[0] = make_unique<JoystickPort>(
456  ctrl, "joyporta", "MSX Joystick port A");
457  } else {
458  joystickPort[0] = make_unique<DummyJoystickPort>();
459  }
460  if (ports == one_of("AB", "B")) {
461  joystickPort[1] = make_unique<JoystickPort>(
462  ctrl, "joyportb", "MSX Joystick port B");
463  } else {
464  joystickPort[1] = make_unique<DummyJoystickPort>();
465  }
466  joyPortDebuggable = make_unique<JoyPortDebuggable>(*this);
467  }
468  return *joystickPort[port];
469 }
470 
472 {
473  if (!renShaTurbo) {
474  assert(getMachineConfig());
475  renShaTurbo = make_unique<RenShaTurbo>(
476  *msxCommandController,
477  getMachineConfig()->getConfig());
478  }
479  return *renShaTurbo;
480 }
481 
483 {
484  if (!ledStatus) {
485  (void)getMSXCliComm(); // force init, to be on the safe side
486  ledStatus = make_unique<LedStatus>(
487  reactor.getRTScheduler(),
488  *msxCommandController,
489  *msxCliComm);
490  }
491  return *ledStatus;
492 }
493 
495 {
496  return *msxCommandController;
497 }
498 
500 {
501  return msxCommandController->getMachineInfoCommand();
502 }
503 
505 {
506  return scheduler->getCurrentTime();
507 }
508 
510 {
511  if (!powered) {
512  return false;
513  }
514  assert(getMachineConfig()); // otherwise powered cannot be true
515 
516  getCPU().execute(false);
517  return true;
518 }
519 
520 void MSXMotherBoard::fastForward(EmuTime::param time, bool fast)
521 {
522  assert(powered);
523  assert(getMachineConfig());
524 
525  if (time <= getCurrentTime()) return;
526 
527  ScopedAssign sa(fastForwarding, fast);
528  realTime->disable();
529  msxMixer->mute();
530  fastForwardHelper->setTarget(time);
531  while (time > getCurrentTime()) {
532  // note: this can run (slightly) past the requested time
533  getCPU().execute(true); // fast-forward mode
534  }
535  realTime->enable();
536  msxMixer->unmute();
537 }
538 
540 {
541  if (getMachineConfig()) {
542  getCPU().setPaused(true);
543  }
544  msxMixer->mute();
545 }
546 
548 {
549  if (getMachineConfig()) {
550  getCPU().setPaused(false);
551  }
552  msxMixer->unmute();
553 }
554 
556 {
557  availableDevices.push_back(&device);
558 }
559 
561 {
562  move_pop_back(availableDevices, rfind_unguarded(availableDevices, &device));
563 }
564 
566 {
567  if (!powered) return;
568  assert(getMachineConfig());
569 
570  EmuTime::param time = getCurrentTime();
572  for (auto& d : availableDevices) {
573  d->reset(time);
574  }
575  getCPU().doReset(time);
576  // let everyone know we're booting, note that the fact that this is
577  // done after the reset call to the devices is arbitrary here
579  std::make_shared<SimpleEvent>(OPENMSX_BOOT_EVENT));
580 }
581 
583 {
584  byte result = 0xff;
585  for (auto& d : availableDevices) {
586  result &= d->readIRQVector();
587  }
588  return result;
589 }
590 
592 {
593  if (powered) return;
594  if (!getMachineConfig()) return;
595 
596  powered = true;
597  // TODO: If our "powered" field is always equal to the power setting,
598  // there is not really a point in keeping it.
599  // TODO: assert disabled see note in Reactor::run() where this method
600  // is called
601  //assert(powerSetting.getBoolean() == powered);
602  powerSetting.setBoolean(true);
603  // TODO: We could make the power LED a device, so we don't have to handle
604  // it separately here.
606 
607  EmuTime::param time = getCurrentTime();
609  for (auto& d : availableDevices) {
610  d->powerUp(time);
611  }
612  getCPU().doReset(time);
613  msxMixer->unmute();
614  // let everyone know we're booting, note that the fact that this is
615  // done after the reset call to the devices is arbitrary here
617  std::make_shared<SimpleEvent>(OPENMSX_BOOT_EVENT));
618 }
619 
620 void MSXMotherBoard::powerDown()
621 {
622  if (!powered) return;
623 
624  powered = false;
625  // TODO: This assertion fails in 1 case: when quitting with a running MSX.
626  // How do we want the Reactor to shutdown: immediately or after
627  // handling all pending commands/events/updates?
628  //assert(powerSetting.getBoolean() == powered);
629  powerSetting.setBoolean(false);
631 
632  msxMixer->mute();
633 
634  EmuTime::param time = getCurrentTime();
635  for (auto& d : availableDevices) {
636  d->powerDown(time);
637  }
638 }
639 
640 void MSXMotherBoard::activate(bool active_)
641 {
642  active = active_;
643  auto event = std::make_shared<SimpleEvent>(
645  msxEventDistributor->distributeEvent(event, scheduler->getCurrentTime());
646  if (active) {
647  realTime->resync();
648  }
649 }
650 
652 {
653  if (getMachineConfig()) {
655  }
656 }
657 
659 {
661 }
662 
663 MSXDevice* MSXMotherBoard::findDevice(std::string_view name)
664 {
665  auto it = ranges::find_if(availableDevices,
666  [&](auto* d) { return d->getName() == name; });
667  return (it != end(availableDevices)) ? *it : nullptr;
668 }
669 
671 {
672  if (mapperIOCounter == 0) {
674 
675  MSXCPUInterface& cpuInterface = getCPUInterface();
676  cpuInterface.register_IO_Out(0xFC, mapperIO.get());
677  cpuInterface.register_IO_Out(0xFD, mapperIO.get());
678  cpuInterface.register_IO_Out(0xFE, mapperIO.get());
679  cpuInterface.register_IO_Out(0xFF, mapperIO.get());
680  cpuInterface.register_IO_In (0xFC, mapperIO.get());
681  cpuInterface.register_IO_In (0xFD, mapperIO.get());
682  cpuInterface.register_IO_In (0xFE, mapperIO.get());
683  cpuInterface.register_IO_In (0xFF, mapperIO.get());
684  }
685  ++mapperIOCounter;
686  return *mapperIO;
687 }
688 
690 {
691  assert(mapperIO);
692  assert(mapperIOCounter);
693  --mapperIOCounter;
694  if (mapperIOCounter == 0) {
695  MSXCPUInterface& cpuInterface = getCPUInterface();
696  cpuInterface.unregister_IO_Out(0xFC, mapperIO.get());
697  cpuInterface.unregister_IO_Out(0xFD, mapperIO.get());
698  cpuInterface.unregister_IO_Out(0xFE, mapperIO.get());
699  cpuInterface.unregister_IO_Out(0xFF, mapperIO.get());
700  cpuInterface.unregister_IO_In (0xFC, mapperIO.get());
701  cpuInterface.unregister_IO_In (0xFD, mapperIO.get());
702  cpuInterface.unregister_IO_In (0xFE, mapperIO.get());
703  cpuInterface.unregister_IO_In (0xFF, mapperIO.get());
704 
705  mapperIO.reset();
706  }
707 }
708 
709 string MSXMotherBoard::getUserName(const string& hwName)
710 {
711  auto& s = userNames[hwName];
712  unsigned n = 0;
713  string userName;
714  do {
715  userName = strCat("untitled", ++n);
716  } while (contains(s, userName));
717  s.push_back(userName);
718  return userName;
719 }
720 
721 void MSXMotherBoard::freeUserName(const string& hwName, const string& userName)
722 {
723  auto& s = userNames[hwName];
724  move_pop_back(s, rfind_unguarded(s, userName));
725 }
726 
727 // AddRemoveUpdate
728 
730  : motherBoard(motherBoard_)
731 {
732  motherBoard.getReactor().getGlobalCliComm().update(
733  CliComm::HARDWARE, motherBoard.getMachineID(), "add");
734 }
735 
737 {
738  motherBoard.getReactor().getGlobalCliComm().update(
739  CliComm::HARDWARE, motherBoard.getMachineID(), "remove");
740 }
741 
742 
743 // ResetCmd
745  : RecordedCommand(motherBoard_.getCommandController(),
746  motherBoard_.getStateChangeDistributor(),
747  motherBoard_.getScheduler(),
748  "reset")
749  , motherBoard(motherBoard_)
750 {
751 }
752 
753 void ResetCmd::execute(span<const TclObject> /*tokens*/, TclObject& /*result*/,
754  EmuTime::param /*time*/)
755 {
756  motherBoard.doReset();
757 }
758 
759 string ResetCmd::help(const vector<string>& /*tokens*/) const
760 {
761  return "Resets the MSX.";
762 }
763 
764 
765 // LoadMachineCmd
767  : Command(motherBoard_.getCommandController(), "load_machine")
768  , motherBoard(motherBoard_)
769 {
770  // The load_machine command should always directly follow a
771  // create_machine command:
772  // - It's not allowed to use load_machine on a machine that has
773  // already a machine configuration loaded earlier.
774  // - We also disallow executing most machine-specifc commands on an
775  // 'empty machine' (an 'empty machine', is a machine returned by
776  // create_machine before the load_machine command is executed, so a
777  // machine without a machine configuration). The only exception is
778  // this load_machine command and machine_info.
779  //
780  // So if the only allowed command on an empty machine is
781  // 'load_machine', (and an empty machine by itself isn't very useful),
782  // then why isn't create_machine and load_machine merged into a single
783  // command? The only reason for this is that load_machine sends out
784  // events (machine specific) and maybe you already want to know the ID
785  // of the new machine (this is returned by create_machine) before those
786  // events will be send.
787  //
788  // Why not allow all commands on an empty machine? In the past we did
789  // allow this, though it often was the source of bugs. We could in each
790  // command (when needed) check for an empty machine and then return
791  // some dummy/empty result or some error. But because I can't think of
792  // any really useful command for an empty machine, it seemed easier to
793  // just disallow most commands.
795 }
796 
798 {
799  checkNumArgs(tokens, 2, "machine");
800  if (motherBoard.getMachineConfig()) {
801  throw CommandException("Already loaded a config in this machine.");
802  }
803  result = motherBoard.loadMachine(string(tokens[1].getString()));
804 }
805 
806 string LoadMachineCmd::help(const vector<string>& /*tokens*/) const
807 {
808  return "Load a msx machine configuration into an empty machine.";
809 }
810 
811 void LoadMachineCmd::tabCompletion(vector<string>& tokens) const
812 {
813  completeString(tokens, Reactor::getHwConfigs("machines"));
814 }
815 
816 
817 // ListExtCmd
819  : Command(motherBoard_.getCommandController(), "list_extensions")
820  , motherBoard(motherBoard_)
821 {
822 }
823 
825 {
826  result.addListElements(
827  view::transform(motherBoard.getExtensions(),
828  [&](auto& e) { return e->getName(); }));
829 }
830 
831 string ListExtCmd::help(const vector<string>& /*tokens*/) const
832 {
833  return "Return a list of all inserted extensions.";
834 }
835 
836 
837 // ExtCmd
838 ExtCmd::ExtCmd(MSXMotherBoard& motherBoard_, std::string commandName_)
839  : RecordedCommand(motherBoard_.getCommandController(),
840  motherBoard_.getStateChangeDistributor(),
841  motherBoard_.getScheduler(),
842  commandName_)
843  , motherBoard(motherBoard_)
844  , commandName(std::move(commandName_))
845 {
846 }
847 
849  EmuTime::param /*time*/)
850 {
851  checkNumArgs(tokens, 2, "extension");
852  try {
853  auto slotname = (commandName.size() == 4)
854  ? std::string_view(&commandName[3], 1)
855  : "any";
856  result = motherBoard.loadExtension(
857  tokens[1].getString(), slotname);
858  } catch (MSXException& e) {
859  throw CommandException(std::move(e).getMessage());
860  }
861 }
862 
863 string ExtCmd::help(const vector<string>& /*tokens*/) const
864 {
865  return "Insert a hardware extension.";
866 }
867 
868 void ExtCmd::tabCompletion(vector<string>& tokens) const
869 {
870  completeString(tokens, Reactor::getHwConfigs("extensions"));
871 }
872 
873 
874 // RemoveExtCmd
876  : RecordedCommand(motherBoard_.getCommandController(),
877  motherBoard_.getStateChangeDistributor(),
878  motherBoard_.getScheduler(),
879  "remove_extension")
880  , motherBoard(motherBoard_)
881 {
882 }
883 
885  EmuTime::param /*time*/)
886 {
887  checkNumArgs(tokens, 2, "extension");
888  std::string_view extName = tokens[1].getString();
889  HardwareConfig* extension = motherBoard.findExtension(extName);
890  if (!extension) {
891  throw CommandException("No such extension: ", extName);
892  }
893  try {
894  motherBoard.removeExtension(*extension);
895  } catch (MSXException& e) {
896  throw CommandException("Can't remove extension '", extName,
897  "': ", e.getMessage());
898  }
899 }
900 
901 string RemoveExtCmd::help(const vector<string>& /*tokens*/) const
902 {
903  return "Remove an extension from the MSX machine.";
904 }
905 
906 void RemoveExtCmd::tabCompletion(vector<string>& tokens) const
907 {
908  if (tokens.size() == 2) {
909  auto names = to_vector(view::transform(
910  motherBoard.getExtensions(),
911  [](auto& e) { return e->getName(); }));
912  completeString(tokens, names);
913  }
914 }
915 
916 
917 // MachineNameInfo
918 
920  : InfoTopic(motherBoard_.getMachineInfoCommand(), "config_name")
921  , motherBoard(motherBoard_)
922 {
923 }
924 
926  TclObject& result) const
927 {
928  result = motherBoard.getMachineName();
929 }
930 
931 string MachineNameInfo::help(const vector<string>& /*tokens*/) const
932 {
933  return "Returns the configuration name for this machine.";
934 }
935 
936 // MachineTypeInfo
937 
939  : InfoTopic(motherBoard_.getMachineInfoCommand(), "type")
940  , motherBoard(motherBoard_)
941 {
942 }
943 
945  TclObject& result) const
946 {
947  result = motherBoard.getMachineType();
948 }
949 
950 string MachineTypeInfo::help(const vector<string>& /*tokens*/) const
951 {
952  return "Returns the machine type for this machine.";
953 }
954 
955 
956 // MachineExtensionInfo
957 
959  : InfoTopic(motherBoard_.getMachineInfoCommand(), "extension")
960  , motherBoard(motherBoard_)
961 {
962 }
963 
965  TclObject& result) const
966 {
967  checkNumArgs(tokens, Between{2, 3}, Prefix{2}, "?extension-instance-name?");
968  if (tokens.size() == 2) {
969  result.addListElements(
970  view::transform(motherBoard.getExtensions(),
971  [&](auto& e) { return e->getName(); }));
972  } else if (tokens.size() == 3) {
973  std::string_view extName = tokens[2].getString();
974  HardwareConfig* extension = motherBoard.findExtension(extName);
975  if (!extension) {
976  throw CommandException("No such extension: ", extName);
977  }
978  if (extension->getType() == HardwareConfig::Type::EXTENSION) {
979  // A 'true' extension, as specified in an XML file
980  result.addDictKeyValue("config", extension->getConfigName());
981  } else {
982  assert(extension->getType() == HardwareConfig::Type::ROM);
983  // A ROM cartridge, peek into the internal config for the original filename
984  const auto& filename = extension->getConfig()
985  .getChild("devices").getChild("primary").getChild("secondary")
986  .getChild("ROM").getChild("rom").getChildData("filename");
987  result.addDictKeyValue("rom", filename);
988  }
989  TclObject deviceList;
990  deviceList.addListElements(
991  view::transform(extension->getDevices(),
992  [&](auto& e) { return e->getName(); }));
993  result.addDictKeyValue("devices", deviceList);
994  }
995 }
996 
997 string MachineExtensionInfo::help(const vector<string>& /*tokens*/) const
998 {
999  return "Returns information about the given extension instance.";
1000 }
1001 
1002 void MachineExtensionInfo::tabCompletion(vector<string>& tokens) const
1003 {
1004  if (tokens.size() == 3) {
1005  auto names = to_vector(view::transform(
1006  motherBoard.getExtensions(),
1007  [](auto& e) { return e->getName(); }));
1008  completeString(tokens, names);
1009  }
1010 }
1011 
1012 
1013 // DeviceInfo
1014 
1016  : InfoTopic(motherBoard_.getMachineInfoCommand(), "device")
1017  , motherBoard(motherBoard_)
1018 {
1019 }
1020 
1022 {
1023  checkNumArgs(tokens, Between{2, 3}, Prefix{2}, "?device?");
1024  switch (tokens.size()) {
1025  case 2:
1026  result.addListElements(
1027  view::transform(motherBoard.availableDevices,
1028  [](auto& d) { return d->getName(); }));
1029  break;
1030  case 3: {
1031  std::string_view deviceName = tokens[2].getString();
1032  MSXDevice* device = motherBoard.findDevice(deviceName);
1033  if (!device) {
1034  throw CommandException("No such device: ", deviceName);
1035  }
1036  device->getDeviceInfo(result);
1037  break;
1038  }
1039  }
1040 }
1041 
1042 string DeviceInfo::help(const vector<string>& /*tokens*/) const
1043 {
1044  return "Without any arguments, returns the list of used device names.\n"
1045  "With a device name as argument, returns the type (and for some "
1046  "devices the subtype) of the given device.";
1047 }
1048 
1049 void DeviceInfo::tabCompletion(vector<string>& tokens) const
1050 {
1051  if (tokens.size() == 3) {
1052  auto names = to_vector(view::transform(
1053  motherBoard.availableDevices,
1054  [](auto& d) { return d->getName(); }));
1055  completeString(tokens, names);
1056  }
1057 }
1058 
1059 
1060 // FastForwardHelper
1061 
1063  : Schedulable(motherBoard_.getScheduler())
1064  , motherBoard(motherBoard_)
1065 {
1066 }
1067 
1068 void FastForwardHelper::setTarget(EmuTime::param targetTime)
1069 {
1070  setSyncPoint(targetTime);
1071 }
1072 
1073 void FastForwardHelper::executeUntil(EmuTime::param /*time*/)
1074 {
1075  motherBoard.exitCPULoopSync();
1076 }
1077 
1078 
1079 // class JoyPortDebuggable
1080 
1082  : SimpleDebuggable(motherBoard_, "joystickports", "MSX Joystick Ports", 2)
1083 {
1084 }
1085 
1086 byte JoyPortDebuggable::read(unsigned address, EmuTime::param time)
1087 {
1088  return getMotherBoard().getJoystickPort(address).read(time);
1089 }
1090 
1091 void JoyPortDebuggable::write(unsigned /*address*/, byte /*value*/)
1092 {
1093  // ignore
1094 }
1095 
1096 
1097 // class SettingObserver
1098 
1100  : motherBoard(motherBoard_)
1101 {
1102 }
1103 
1104 void SettingObserver::update(const Setting& setting) noexcept
1105 {
1106  if (&setting == &motherBoard.powerSetting) {
1107  if (motherBoard.powerSetting.getBoolean()) {
1108  motherBoard.powerUp();
1109  } else {
1110  motherBoard.powerDown();
1111  }
1112  } else {
1113  UNREACHABLE;
1114  }
1115 }
1116 
1117 
1118 // serialize
1119 // version 1: initial version
1120 // version 2: added reRecordCount
1121 // version 3: removed reRecordCount (moved to ReverseManager)
1122 // version 4: moved joystickportA/B from MSXPSG to here
1123 template<typename Archive>
1124 void MSXMotherBoard::serialize(Archive& ar, unsigned version)
1125 {
1126  // don't serialize:
1127  // machineID, userNames, availableDevices, addRemoveUpdate,
1128  // sharedStuffMap, msxCliComm, msxEventDistributor,
1129  // msxCommandController, slotManager, eventDelay,
1130  // debugger, msxMixer, panasonicMemory, renShaTurbo,
1131  // ledStatus
1132 
1133  // Scheduler must come early so that devices can query current time
1134  ar.serialize("scheduler", *scheduler);
1135  // MSXMixer has already set syncpoints, those are invalid now
1136  // the following call will fix this
1137  if constexpr (Archive::IS_LOADER) {
1138  msxMixer->reInit();
1139  }
1140 
1141  ar.serialize("name", machineName);
1142  ar.serializeWithID("config", machineConfig2, std::ref(*this));
1143  assert(getMachineConfig() == machineConfig2.get());
1144  ar.serializeWithID("extensions", extensions, std::ref(*this));
1145 
1146  if (mapperIO) ar.serialize("mapperIO", *mapperIO);
1147 
1148  MSXDeviceSwitch& devSwitch = getDeviceSwitch();
1149  if (devSwitch.hasRegisteredDevices()) {
1150  ar.serialize("deviceSwitch", devSwitch);
1151  }
1152 
1153  if (getMachineConfig()) {
1154  ar.serialize("cpu", getCPU());
1155  }
1156  ar.serialize("cpuInterface", getCPUInterface());
1157 
1158  if (auto* port = dynamic_cast<CassettePort*>(&getCassettePort())) {
1159  ar.serialize("cassetteport", *port);
1160  }
1161  if (ar.versionAtLeast(version, 4)) {
1162  if (auto* port = dynamic_cast<JoystickPort*>(
1163  joystickPort[0].get())) {
1164  ar.serialize("joystickportA", *port);
1165  }
1166  if (auto* port = dynamic_cast<JoystickPort*>(
1167  joystickPort[1].get())) {
1168  ar.serialize("joystickportB", *port);
1169  }
1170  }
1171 
1172  if constexpr (Archive::IS_LOADER) {
1173  powered = true; // must come before changing power setting
1174  powerSetting.setBoolean(true);
1176  msxMixer->unmute();
1177  }
1178 
1179  if (version == 2) {
1180  assert(Archive::IS_LOADER);
1181  unsigned reRecordCount = 0; // silence warning
1182  ar.serialize("reRecordCount", reRecordCount);
1183  getReverseManager().setReRecordCount(reRecordCount);
1184  }
1185 }
1187 
1188 } // namespace openmsx
Assign new value to some variable and restore the original value when this object goes out of scope.
Definition: ScopedAssign.hh:8
Definition: one_of.hh:7
AddRemoveUpdate(const AddRemoveUpdate &)=delete
AddRemoveUpdate(MSXMotherBoard &motherBoard)
AddRemoveUpdate & operator=(const AddRemoveUpdate &)=delete
bool getBoolean() const noexcept
virtual void update(UpdateType type, std::string_view name, std::string_view value)=0
void setAllowedInEmptyMachine(bool value)
Definition: Command.hh:64
void checkNumArgs(span< const TclObject > tokens, unsigned exactly, const char *errMessage) const
Definition: Completer.cc:176
static void completeString(std::vector< std::string > &tokens, ITER begin, ITER end, bool caseSensitive=true)
Definition: Completer.hh:130
static std::unique_ptr< MSXDeviceSwitch > createDeviceSwitch(const HardwareConfig &hwConf)
static std::unique_ptr< MSXMapperIO > createMapperIO(const HardwareConfig &hwConf)
DeviceInfo(MSXMotherBoard &motherBoard)
string help(const vector< string > &tokens) const override
Print help for this topic.
void execute(span< const TclObject > tokens, TclObject &result) const override
Show info on this topic.
void tabCompletion(vector< string > &tokens) const override
Attempt tab completion for this topic.
void distributeEvent(const EventPtr &event)
Schedule the given event for delivery.
std::string help(const std::vector< std::string > &tokens) const override
Print help for this command.
void tabCompletion(std::vector< std::string > &tokens) const override
Attempt tab completion for this command.
ExtCmd(MSXMotherBoard &motherBoard, std::string commandName)
void execute(span< const TclObject > tokens, TclObject &result, EmuTime::param time) override
This is like the execute() method of the Command class, it only has an extra time parameter.
void setTarget(EmuTime::param targetTime)
FastForwardHelper(MSXMotherBoard &motherBoard)
void update(UpdateType type, std::string_view name, std::string_view value) override
const XMLElement & getConfig() const
const std::vector< std::unique_ptr< MSXDevice > > & getDevices() const
const std::string & getConfigName() const
const std::string & getName() const
static std::unique_ptr< HardwareConfig > createExtensionConfig(MSXMotherBoard &motherBoard, std::string extensionName, std::string_view slotname)
static std::unique_ptr< HardwareConfig > createMachineConfig(MSXMotherBoard &motherBoard, std::string machineName)
void testRemove() const
Checks whether this HardwareConfig can be deleted.
void write(unsigned address, byte value) override
JoyPortDebuggable(MSXMotherBoard &motherBoard)
byte read(unsigned address, EmuTime::param time) override
virtual byte read(EmuTime::param time)=0
void setLed(Led led, bool status)
Definition: LedStatus.cc:40
void execute(span< const TclObject > tokens, TclObject &result) override
Execute this command.
ListExtCmd(MSXMotherBoard &motherBoard)
string help(const vector< string > &tokens) const override
Print help for this command.
LoadMachineCmd(MSXMotherBoard &motherBoard)
string help(const vector< string > &tokens) const override
Print help for this command.
void tabCompletion(vector< string > &tokens) const override
Attempt tab completion for this command.
void execute(span< const TclObject > tokens, TclObject &result) override
Execute this command.
void register_IO_Out(byte port, MSXDevice *device)
Devices can register their Out ports.
void register_IO_In(byte port, MSXDevice *device)
Devices can register their In ports.
void unregister_IO_In(byte port, MSXDevice *device)
void reset()
Reset (the slot state)
void unregister_IO_Out(byte port, MSXDevice *device)
void exitCPULoopSync()
See CPUCore::exitCPULoopsync()
Definition: MSXCPU.cc:131
void doReset(EmuTime::param time)
Reset CPU.
Definition: MSXCPU.cc:85
void setPaused(bool paused)
(un)pause CPU.
Definition: MSXCPU.cc:364
void exitCPULoopAsync()
See CPUCore::exitCPULoopAsync()
Definition: MSXCPU.cc:136
bool hasRegisteredDevices() const
An MSXDevice is an emulated hardware component connected to the bus of the emulated MSX.
Definition: MSXDevice.hh:33
void getDeviceInfo(TclObject &result) const
Get device info.
Definition: MSXDevice.cc:391
const std::string & getMessage() const &
Definition: MSXException.hh:23
HardwareConfig * findExtension(std::string_view extensionName)
PluggingController & getPluggingController()
void activate(bool active)
std::string getMachineType() const
void setMachineConfig(HardwareConfig *machineConfig)
RenShaTurbo & getRenShaTurbo()
void freeUserName(const std::string &hwName, const std::string &userName)
bool execute()
Run emulation.
MSXCPUInterface & getCPUInterface()
std::string getUserName(const std::string &hwName)
Keep track of which 'usernames' are in use.
EmuTime::param getCurrentTime()
Convenience method: This is the same as getScheduler().getCurrentTime().
std::string loadMachine(const std::string &machine)
std::string_view getMachineName() const
ReverseManager & getReverseManager()
MSXDevice * findDevice(std::string_view name)
Find a MSXDevice by name.
CommandController & getCommandController()
void pause()
Pause MSX machine.
const Extensions & getExtensions() const
std::string insertExtension(std::string_view name, std::unique_ptr< HardwareConfig > extension)
void fastForward(EmuTime::param time, bool fast)
Run emulation until a certain time in fast forward mode.
void exitCPULoopAsync()
See CPU::exitCPULoopAsync().
MSXMotherBoard(const MSXMotherBoard &)=delete
MSXDeviceSwitch & getDeviceSwitch()
void serialize(Archive &ar, unsigned version)
void removeDevice(MSXDevice &device)
std::string_view getMachineID() const
const HardwareConfig * getMachineConfig() const
void removeExtension(const HardwareConfig &extension)
JoystickPortIf & getJoystickPort(unsigned port)
std::string loadExtension(std::string_view extensionName, std::string_view slotname)
CassettePortInterface & getCassettePort()
void addDevice(MSXDevice &device)
All MSXDevices should be registered by the MotherBoard.
PanasonicMemory & getPanasonicMemory()
MSXMapperIO & createMapperIO()
All memory mappers in one MSX machine share the same four (logical) memory mapper registers.
InfoCommand & getMachineInfoCommand()
void execute(span< const TclObject > tokens, TclObject &result) const override
Show info on this topic.
string help(const vector< string > &tokens) const override
Print help for this topic.
void tabCompletion(vector< string > &tokens) const override
Attempt tab completion for this topic.
MachineExtensionInfo(MSXMotherBoard &motherBoard)
string help(const vector< string > &tokens) const override
Print help for this topic.
MachineNameInfo(MSXMotherBoard &motherBoard)
void execute(span< const TclObject > tokens, TclObject &result) const override
Show info on this topic.
void execute(span< const TclObject > tokens, TclObject &result) const override
Show info on this topic.
MachineTypeInfo(MSXMotherBoard &motherBoard)
string help(const vector< string > &tokens) const override
Print help for this topic.
Generic Gang-of-Four Observer class, templatized edition.
Definition: Observer.hh:10
Central administration of Connectors and Pluggables.
Contains the main loop of openMSX.
Definition: Reactor.hh:67
EventDistributor & getEventDistributor()
Definition: Reactor.hh:81
GlobalSettings & getGlobalSettings()
Definition: Reactor.hh:103
GlobalCliComm & getGlobalCliComm()
Definition: Reactor.hh:82
RTScheduler & getRTScheduler()
Definition: Reactor.hh:80
static std::vector< std::string > getHwConfigs(std::string_view type)
Definition: Reactor.cc:335
Commands that directly influence the MSX state should send and events so that they can be recorded by...
void execute(span< const TclObject > tokens, TclObject &result, EmuTime::param time) override
This is like the execute() method of the Command class, it only has an extra time parameter.
string help(const vector< string > &tokens) const override
Print help for this command.
RemoveExtCmd(MSXMotherBoard &motherBoard)
void tabCompletion(vector< string > &tokens) const override
Attempt tab completion for this command.
Ren-Sha Turbo is the autofire in several MSX 2+ models and in the MSX turbo R.
Definition: RenShaTurbo.hh:21
string help(const vector< string > &tokens) const override
Print help for this command.
void execute(span< const TclObject > tokens, TclObject &result, EmuTime::param time) override
This is like the execute() method of the Command class, it only has an extra time parameter.
ResetCmd(MSXMotherBoard &motherBoard)
void setReRecordCount(unsigned count)
Every class that wants to get scheduled at some point must inherit from this class.
Definition: Schedulable.hh:34
void setSyncPoint(EmuTime::param timestamp)
Definition: Schedulable.cc:23
SettingObserver(MSXMotherBoard &motherBoard)
void update(const Setting &setting) noexcept override
MSXMotherBoard & getMotherBoard() const
void detach(Observer< T > &observer)
Definition: Subject.hh:56
void attach(Observer< T > &observer)
Definition: Subject.hh:50
void addListElements(ITER first, ITER last)
Definition: TclObject.hh:131
void addDictKeyValue(const Key &key, const Value &value)
Definition: TclObject.hh:144
const XMLElement * findChild(std::string_view childName) const
Definition: XMLElement.cc:67
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 index_type size() const noexcept
Definition: span.hh:296
This file implemented 3 utility functions:
Definition: Autofire.cc:5
@ OPENMSX_BOOT_EVENT
Definition: Event.hh:36
@ OPENMSX_MACHINE_DEACTIVATED
Definition: Event.hh:65
@ OPENMSX_MACHINE_ACTIVATED
Send when a machine is (de)activated.
Definition: Event.hh:64
constexpr const char *const filename
auto find_if(InputRange &&range, UnaryPredicate pred)
Definition: ranges.hh:113
constexpr auto transform(Range &&range, UnaryOp op)
Definition: view.hh:306
#define INSTANTIATE_SERIALIZE_METHODS(CLASS)
Definition: serialize.hh:983
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
constexpr auto rfind_if_unguarded(RANGE &range, PRED pred)
Definition: stl.hh:165
auto to_vector(Range &&range) -> std::vector< detail::ToVectorType< T, decltype(std::begin(range))>>
Definition: stl.hh:316
std::string strCat(Ts &&...ts)
Definition: strCat.hh:591
#define UNREACHABLE
Definition: unreachable.hh:38
constexpr auto end(const zstring_view &x)
Definition: zstring_view.hh:83