openMSX
CartridgeSlotManager.cc
Go to the documentation of this file.
2#include "HardwareConfig.hh"
3#include "CommandException.hh"
4#include "FileContext.hh"
5#include "TclObject.hh"
6#include "MSXException.hh"
7#include "MSXCPUInterface.hh"
8#include "MSXRom.hh"
9#include "MSXCliComm.hh"
10#include "narrow.hh"
11#include "one_of.hh"
12#include "outer.hh"
13#include "ranges.hh"
14#include "unreachable.hh"
15#include "xrange.hh"
16#include <array>
17#include <cassert>
18#include <memory>
19
20using std::string;
21
22namespace openmsx {
23
24// CartridgeSlotManager::Slot
25CartridgeSlotManager::Slot::~Slot()
26{
27 assert(!config);
28 assert(useCount == 0);
29}
30
31bool CartridgeSlotManager::Slot::exists() const
32{
33 return cartCommand.has_value();
34}
35
36bool CartridgeSlotManager::Slot::used(const HardwareConfig* allowed) const
37{
38 assert((useCount == 0) == (config == nullptr));
39 return config && (config != allowed);
40}
41
42void CartridgeSlotManager::Slot::getMediaInfo(TclObject& result)
43{
44 if (config) {
45 if (config->getType() == HardwareConfig::Type::EXTENSION) {
46 // A 'true' extension, as specified in an XML file
47 result.addDictKeyValues("target", config->getConfigName(),
48 "devicename", config->getName(),
49 "type", "extension");
50 } else {
51 assert(config->getType() == HardwareConfig::Type::ROM);
52 result.addDictKeyValue("type", "rom");
53 // A ROM cartridge, peek into the internal config for the original filename
54 const auto& romConfig = config->getConfig()
55 .getChild("devices").getChild("primary").getChild("secondary")
56 .getChild("ROM").getChild("rom");
57 result.addDictKeyValue("target", romConfig.getChildData("filename"));
58 TclObject patches;
59 if (const auto* patchesElem = romConfig.findChild("patches")) {
60 for (const auto* p : patchesElem->getChildren("ips")) {
61 patches.addListElement(p->getData());
62 }
63 }
64 result.addDictKeyValue("patches", patches);
65 if (auto* rom = dynamic_cast<MSXRom*>(cpuInterface->getMSXDevice(ps, ss < 0 ? 0: ss, 1))) {
66 rom->getInfo(result);
67 }
68 }
69 } else {
70 result.addDictKeyValue("target", std::string_view{});
71 }
72}
73
74
75// CartridgeSlotManager
77 : motherBoard(motherBoard_)
78 , cartCmd(*this, motherBoard, "cart")
79 , extSlotInfo(motherBoard.getMachineInfoCommand())
80{
81}
82
84{
85 for (auto slot : xrange(MAX_SLOTS)) {
86 (void)slot;
87 assert(!slots[slot].exists());
88 assert(!slots[slot].used());
89 }
90}
91
92int CartridgeSlotManager::getSlotNum(std::string_view slot)
93{
94 if (slot.size() == 1) {
95 if (('0' <= slot[0]) && (slot[0] <= '3')) {
96 return slot[0] - '0';
97 } else if (('a' <= slot[0]) && (slot[0] <= 'p')) {
98 return -(1 + slot[0] - 'a');
99 } else if (slot[0] == 'X') {
100 return -256;
101 }
102 } else if (slot.size() == 2) {
103 if ((slot[0] == '?') && ('0' <= slot[1]) && (slot[1] <= '3')) {
104 return slot[1] - '0' - 128;
105 }
106 } else if (slot == "any") {
107 return -256;
108 }
109 throw MSXException("Invalid slot specification: ", slot);
110}
111
116
118{
119 if (isExternalSlot(ps, ss, false)) {
120 throw MSXException("Slot is already an external slot.");
121 }
122 for (auto slotNum : xrange(MAX_SLOTS)) {
123 auto& slot = slots[slotNum];
124 if (!slot.exists()) {
125 slot.ps = ps;
126 slot.ss = ss;
127
128 std::array slotName = {'c','a','r','t','X','\0'};
129 slotName[4] = narrow<char>('a' + slotNum);
130 motherBoard.getMSXCliComm().update(
131 CliComm::HARDWARE, slotName.data(), "add");
132 slot.cartCommand.emplace(
133 *this, motherBoard, slotName.data());
134 motherBoard.registerMediaInfo(
135 slot.cartCommand->getName(), slot);
136
137 std::array extName = {'e','x','t','X','\0'};
138 extName[3] = narrow<char>('a' + slotNum);
139 slot.extCommand.emplace(
140 motherBoard, extName.data());
141 slot.cpuInterface = &motherBoard.getCPUInterface();
142 return;
143 }
144 }
146}
147
148
149unsigned CartridgeSlotManager::getSlot(int ps, int ss) const
150{
151 for (auto slot : xrange(MAX_SLOTS)) {
152 if (slots[slot].exists() &&
153 (slots[slot].ps == ps) && (slots[slot].ss == ss)) {
154 return slot;
155 }
156 }
157 UNREACHABLE; // was not an external slot
158}
159
161 int ps, const HardwareConfig& allowed) const
162{
163 testRemoveExternalSlot(ps, -1, allowed);
164}
165
167 int ps, int ss, const HardwareConfig& allowed) const
168{
169 auto slot = getSlot(ps, ss);
170 if (slots[slot].used(&allowed)) {
171 throw MSXException("Slot still in use.");
172 }
173}
174
179
181{
182 auto slotNum = getSlot(ps, ss);
183 auto& slot = slots[slotNum];
184 assert(!slot.used());
185 motherBoard.unregisterMediaInfo(slot);
186 motherBoard.getMSXCliComm().update(
187 CliComm::HARDWARE, slot.cartCommand->getName(), "remove");
188 slot.cartCommand.reset();
189 slot.extCommand.reset();
190}
191
192void CartridgeSlotManager::getSpecificSlot(unsigned slot, int& ps, int& ss) const
193{
194 assert(slot < MAX_SLOTS);
195 if (!slots[slot].exists()) {
196 throw MSXException("slot-", char('a' + slot), " not defined.");
197 }
198 if (slots[slot].used()) {
199 throw MSXException("slot-", char('a' + slot), " already in use.");
200 }
201 ps = slots[slot].ps;
202 ss = slots[slot].ss;
203}
204
206{
207 assert(slot < MAX_SLOTS);
208 if (!slots[slot].exists()) {
209 throw MSXException("slot-", char('a' + slot), " not defined.");
210 }
211 if (slots[slot].used()) {
212 throw MSXException("slot-", char('a' + slot), " already in use.");
213 }
214 if (slots[slot].ss != -1) {
215 throw MSXException("slot-", char('a' + slot), " is not a primary slot.");
216 }
217 assert(slots[slot].useCount == 0);
218 slots[slot].config = &hwConfig;
219 slots[slot].useCount = 1;
220 return slots[slot].ps;
221}
222
223void CartridgeSlotManager::getAnyFreeSlot(int& ps, int& ss) const
224{
225 // search for the lowest free slot
226 ps = 4; // mark no free slot
227 for (auto slot : xrange(MAX_SLOTS)) {
228 if (slots[slot].exists() && !slots[slot].used()) {
229 int p = slots[slot].ps;
230 int s = slots[slot].ss;
231 if ((p < ps) || ((p == ps) && (s < ss))) {
232 ps = p;
233 ss = s;
234 }
235 }
236 }
237 if (ps == 4) {
238 throw MSXException("Not enough free cartridge slots");
239 }
240}
241
243{
244 for (auto slot : xrange(MAX_SLOTS)) {
245 if (slots[slot].exists() && (slots[slot].ss == -1) &&
246 !slots[slot].used()) {
247 assert(slots[slot].useCount == 0);
248 slots[slot].config = &hwConfig;
249 slots[slot].useCount = 1;
250 return slots[slot].ps;
251 }
252 }
253 throw MSXException("No free primary slot");
254}
255
257 int ps, const HardwareConfig& hwConfig)
258{
259 auto slot = getSlot(ps, -1);
260 assert(slots[slot].config == &hwConfig); (void)hwConfig;
261 assert(slots[slot].useCount == 1);
262 slots[slot].config = nullptr;
263 slots[slot].useCount = 0;
264}
265
267 int ps, int ss, const HardwareConfig& hwConfig)
268{
269 for (auto slot : xrange(MAX_SLOTS)) {
270 if (!slots[slot].exists()) continue;
271 if ((slots[slot].ps == ps) && (slots[slot].ss == ss)) {
272 if (slots[slot].useCount == 0) {
273 slots[slot].config = &hwConfig;
274 } else {
275 if (slots[slot].config != &hwConfig) {
276 throw MSXException(
277 "Slot ", ps, '-', ss,
278 " already in use by ",
279 slots[slot].config->getName());
280 }
281 }
282 ++slots[slot].useCount;
283 }
284 }
285 // Slot not found, was not an external slot. No problem.
286}
287
289 int ps, int ss, const HardwareConfig& hwConfig)
290{
291 for (auto slot : xrange(MAX_SLOTS)) {
292 if (!slots[slot].exists()) continue;
293 if ((slots[slot].ps == ps) && (slots[slot].ss == ss)) {
294 assert(slots[slot].config == &hwConfig); (void)hwConfig;
295 assert(slots[slot].useCount > 0);
296 --slots[slot].useCount;
297 if (slots[slot].useCount == 0) {
298 slots[slot].config = nullptr;
299 }
300 return;
301 }
302 }
303 // Slot not found, was not an external slot. No problem.
304}
305
306bool CartridgeSlotManager::isExternalSlot(int ps, int ss, bool convert) const
307{
308 return ranges::any_of(xrange(MAX_SLOTS), [&](auto slot) {
309 int tmp = (convert && (slots[slot].ss == -1)) ? 0 : slots[slot].ss;
310 return slots[slot].exists() && (slots[slot].ps == ps) && (tmp == ss);
311 });
312}
313
314
315// CartCmd
316CartridgeSlotManager::CartCmd::CartCmd(
317 CartridgeSlotManager& manager_, MSXMotherBoard& motherBoard_,
318 std::string_view commandName)
319 : RecordedCommand(motherBoard_.getCommandController(),
320 motherBoard_.getStateChangeDistributor(),
321 motherBoard_.getScheduler(),
322 commandName)
323 , manager(manager_)
324 , cliComm(motherBoard_.getMSXCliComm())
325{
326}
327
328const HardwareConfig* CartridgeSlotManager::CartCmd::getExtensionConfig(
329 std::string_view cartName)
330{
331 if (cartName.size() != 5) {
332 throw SyntaxError();
333 }
334 return manager.getConfigForSlot(cartName[4] - 'a');
335}
336
337void CartridgeSlotManager::CartCmd::execute(
338 std::span<const TclObject> tokens, TclObject& result, EmuTime::param /*time*/)
339{
340 std::string_view cartName = tokens[0].getString();
341
342 // strip namespace qualification
343 // TODO investigate whether it's a good idea to strip namespace at a
344 // higher level for all commands. How does that interact with
345 // the event recording feature?
346 if (auto pos = cartName.rfind("::"); pos != std::string_view::npos) {
347 cartName = cartName.substr(pos + 2);
348 }
349 if (tokens.size() == 1) {
350 // query name of cartridge
351 const auto* extConf = getExtensionConfig(cartName);
352 result.addListElement(tmpStrCat(cartName, ':'),
353 extConf ? extConf->getName() : string{});
354 if (!extConf) {
355 TclObject options = makeTclList("empty");
356 result.addListElement(options);
357 }
358 } else if (tokens[1] == one_of("eject", "-eject")) {
359 // remove cartridge (or extension)
360 if (tokens[1] == "-eject") {
361 result =
362 "Warning: use of '-eject' is deprecated, "
363 "instead use the 'eject' subcommand";
364 }
365 if (const auto* extConf = getExtensionConfig(cartName)) {
366 try {
367 manager.motherBoard.removeExtension(*extConf);
368 cliComm.update(CliComm::MEDIA, cartName, {});
369 } catch (MSXException& e) {
370 throw CommandException("Can't remove cartridge: ",
371 e.getMessage());
372 }
373 }
374 } else {
375 // insert cartridge
376 auto slotName = (cartName.size() == 5)
377 ? cartName.substr(4, 1)
378 : "any";
379 size_t extensionNameToken = 1;
380 if (tokens[1] == "insert") {
381 if (tokens.size() > 2) {
382 extensionNameToken = 2;
383 } else {
384 throw CommandException("Missing argument to insert subcommand");
385 }
386 }
387 auto options = tokens.subspan(extensionNameToken + 1);
388 try {
389 std::string_view romName = tokens[extensionNameToken].getString();
390 auto extension = HardwareConfig::createRomConfig(
391 manager.motherBoard, string(romName), string(slotName), options);
392 if (slotName != "any") {
393 if (const auto* extConf = getExtensionConfig(cartName)) {
394 // still a cartridge inserted, (try to) remove it now
395 manager.motherBoard.removeExtension(*extConf);
396 }
397 }
398 result = manager.motherBoard.insertExtension(
399 "ROM", std::move(extension));
400 cliComm.update(CliComm::MEDIA, cartName, romName);
401 } catch (MSXException& e) {
402 throw CommandException(std::move(e).getMessage());
403 }
404 }
405}
406
407string CartridgeSlotManager::CartCmd::help(std::span<const TclObject> tokens) const
408{
409 auto cart = tokens[0].getString();
410 return strCat(
411 cart, " eject : remove the ROM cartridge from this slot\n",
412 cart, " insert <filename> : insert ROM cartridge with <filename>\n",
413 cart, " <filename> : insert ROM cartridge with <filename>\n",
414 cart, " : show which ROM cartridge is in this slot\n",
415 "The following options are supported when inserting a cartridge:\n"
416 "-ips <filename> : apply the given IPS patch to the ROM image\n"
417 "-romtype <romtype> : specify the ROM mapper type\n");
418}
419
420void CartridgeSlotManager::CartCmd::tabCompletion(std::vector<string>& tokens) const
421{
422 using namespace std::literals;
423 static constexpr std::array extra = {"eject"sv, "insert"sv};
424 completeFileName(tokens, userFileContext(),
425 (tokens.size() < 3) ? extra : std::span<const std::string_view>{});
426
427}
428
429bool CartridgeSlotManager::CartCmd::needRecord(std::span<const TclObject> tokens) const
430{
431 return tokens.size() > 1;
432}
433
434
435// class CartridgeSlotInfo
436
437CartridgeSlotManager::CartridgeSlotInfo::CartridgeSlotInfo(
438 InfoCommand& machineInfoCommand)
439 : InfoTopic(machineInfoCommand, "external_slot")
440{
441}
442
443void CartridgeSlotManager::CartridgeSlotInfo::execute(
444 std::span<const TclObject> tokens, TclObject& result) const
445{
446 checkNumArgs(tokens, Between{2, 3}, Prefix{2}, "?slot?");
447 auto& manager = OUTER(CartridgeSlotManager, extSlotInfo);
448 switch (tokens.size()) {
449 case 2: {
450 // return list of slots
451 string slot = "slotX";
452 for (auto i : xrange(CartridgeSlotManager::MAX_SLOTS)) {
453 if (!manager.slots[i].exists()) continue;
454 slot[4] = char('a' + i);
455 result.addListElement(slot);
456 }
457 break;
458 }
459 case 3: {
460 // return info on a particular slot
461 const auto& slotName = tokens[2].getString();
462 if ((slotName.size() != 5) || !slotName.starts_with("slot")) {
463 throw CommandException("Invalid slot name: ", slotName);
464 }
465 unsigned num = slotName[4] - 'a';
467 throw CommandException("Invalid slot name: ", slotName);
468 }
469 auto& slot = manager.slots[num];
470 if (!slot.exists()) {
471 throw CommandException("Slot '", slotName, "' doesn't currently exist in this msx machine.");
472 }
473 result.addListElement(slot.ps);
474 if (slot.ss == -1) {
475 result.addListElement("X");
476 } else {
477 result.addListElement(slot.ss);
478 }
479 if (slot.config) {
480 result.addListElement(slot.config->getName());
481 } else {
482 result.addListElement(std::string_view{});
483 }
484 break;
485 }
486 }
487}
488
489string CartridgeSlotManager::CartridgeSlotInfo::help(
490 std::span<const TclObject> /*tokens*/) const
491{
492 return "Without argument: show list of available external slots.\n"
493 "With argument: show primary and secondary slot number for "
494 "given external slot.\n";
495}
496
497} // namespace openmsx
CartridgeSlotManager(MSXMotherBoard &motherBoard)
void getAnyFreeSlot(int &ps, int &ss) const
static int getSlotNum(std::string_view slot)
void testRemoveExternalSlot(int ps, const HardwareConfig &allowed) const
static constexpr unsigned MAX_SLOTS
void getSpecificSlot(unsigned slot, int &ps, int &ss) const
bool isExternalSlot(int ps, int ss, bool convert) const
void freeSlot(int ps, int ss, const HardwareConfig &hwConfig)
int allocateAnyPrimarySlot(const HardwareConfig &hwConfig)
int allocateSpecificPrimarySlot(unsigned slot, const HardwareConfig &hwConfig)
void allocateSlot(int ps, int ss, const HardwareConfig &hwConfig)
void freePrimarySlot(int ps, const HardwareConfig &hwConfig)
static std::unique_ptr< HardwareConfig > createRomConfig(MSXMotherBoard &motherBoard, std::string_view romFile, std::string_view slotName, std::span< const TclObject > options)
void update(UpdateType type, std::string_view name, std::string_view value) override
Definition MSXCliComm.cc:21
MSXCPUInterface & getCPUInterface()
void registerMediaInfo(std::string_view name, MediaInfoProvider &provider)
Register and unregister providers of media info, for the media info topic.
void unregisterMediaInfo(MediaInfoProvider &provider)
Commands that directly influence the MSX state should send and events so that they can be recorded by...
constexpr double e
Definition Math.hh:21
This file implemented 3 utility functions:
Definition Autofire.cc:9
const FileContext & userFileContext()
TclObject makeTclList(Args &&... args)
Definition TclObject.hh:293
bool any_of(InputRange &&range, UnaryPredicate pred)
Definition ranges.hh:198
STL namespace.
#define OUTER(type, member)
Definition outer.hh:42
std::string strCat()
Definition strCat.hh:703
TemporaryString tmpStrCat(Ts &&... ts)
Definition strCat.hh:742
#define UNREACHABLE
constexpr auto xrange(T e)
Definition xrange.hh:132