1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
|
#!/usr/bin/env python
# $Id: convert_hardwareconfig.py,v 1.24 2004/10/04 21:42:51 mthuurne Exp $
#
# Script for updating openMSX 0.4.0 configurations (hardwareconfig.xml)
# to the new format used by openMSX 0.5.0.
# If you run this script and see "NOTE:" in the output, please verify the
# created XML files manually.
# TODO:
# - Clean up output.
import os, os.path, sys
from StringIO import StringIO
from xml.dom.minidom import parse
ioAddresses = {
# Generic internal:
'PPI': [ (0xA8, 4, 'IO') ],
'S1990': [ (0xE4, 2, 'IO') ],
'F4Device': [ (0xF4, 1, 'IO') ],
'E6Timer': [ (0xE6, 2, 'IO') ],
'TurboRLeds': [ (0xA7, 1, 'O') ],
'TurboRPause': [ (0xA7, 1, 'I') ],
'RTC': [ (0xB4, 2, 'O'), (0xB5, 1, 'I') ],
'PrinterPort': [ (0x90, 2, 'IO') ],
# Kanji is actually a device with only 2 IO ports and only 128kb ROM
# In case of 256kb the device is repeated on the next 2 IO ports (and with
# different ROM of course).
# So we could simplify the code slightly if we treat it like this.
'Kanji1': [ (0xD8, 2, 'O'), (0xD9, 1, 'I') ],
'Kanji2': [ (0xDA, 2, 'O'), (0xDB, 1, 'I') ],
# TODO: [ (0xFC, 4, 'IO') ],
# Memory mapper IO ports are hardcoded in openMSX (because they are
# shared between diffent memory mappers).
'MemoryMapper': [],
# Video:
'VDP1': [ (0x98, 2, 'IO') ], # TMSxxxx
'VDP2': [ (0x98, 4, 'O'), (0x98, 2, 'I') ], # V9938/V9958
'V9990': [ (0x60, 16, 'IO') ],
# Audio:
'PSG': [ (0xA0, 2, 'O'), (0xA2, 1, 'I') ],
'MSX-MUSIC': [ (0x7C, 2, 'O') ],
'FMPAC': [ (0x7C, 2, 'O') ],
'MSX-AUDIO': [ (0xC0, 2, 'IO') ],
'Music Module MIDI': [ (0x00, 2, 'O'), (0x04, 2, 'I') ],
'MoonSound': [ (0x7E, 2, 'IO'), (0xC4, 4, 'IO') ],
'MSX-MIDI': [ (0xE8, 8, 'IO') ],
'TurboRPCM': [ (0xA4, 2, 'IO') ],
# Extensions:
'MSX-RS232': [ (0x80, 8, 'IO') ],
'MegaRam': [ (0x8E, 1, 'IO') ],
'HBI55': [ (0xB0, 4, 'IO') ],
'DebugDevice': [ (0x2E, 2, 'O') ], # can be any (free) port
# FDCs:
'MB8877A': [],
'TC8566AF': [],
'WD2793': [],
# TODO: Microsol FDC uses IO ports (0xd0 - 0xd4 5(!) ports), but I doubt
# this FDC really works in openMSX.
'Microsol': [],
# Devices without I/O addresses:
'ROM': [],
'RAM': [],
'PanasonicRAM': [],
'Bunsetsu': [],
'SunriseIDE': [],
'PAC': [],
'SCC+': [],
# Switched devices (share ports 0x40-0x4F):
'Matsushita': [],
'S1985': [],
'Kanji12': [],
}
def hexFill(number, size):
return ('0x%0' + str(size) + 'X') % number
def getText(node):
assert len(node.childNodes) == 1
textNode = node.childNodes[0]
assert textNode.nodeType == node.TEXT_NODE
return textNode.nodeValue
def getParameter(node, name):
for child in node.childNodes:
if child.nodeType == node.ELEMENT_NODE and child.nodeName == name:
return getText(child)
return None
def renameElement(node, name):
newNode = node.ownerDocument.createElement(name)
for index in range(node.attributes.length):
attribute = node.attributes.item(index)
newNode.setAttribute(attribute.name, attribute.nodeValue)
for child in list(node.childNodes):
node.removeChild(child)
newNode.appendChild(child)
node.parentNode.replaceChild(newNode, node)
node.unlink()
return newNode
def extractElements(node, names):
ret = []
for child in list(node.childNodes):
if child.nodeType == node.ELEMENT_NODE:
if child.nodeName in names:
node.removeChild(child)
ret.append(child)
return ret
def convertDoc(dom, checksums):
assert dom.nodeType == dom.DOCUMENT_NODE
if dom.doctype.systemId == 'msxconfig2.dtd':
print ' already in new format, skipping'
return
elif dom.doctype.systemId != 'msxconfig.dtd':
print ' NOTE: unknown format, skipping'
return
dom.doctype.systemId = 'msxconfig2.dtd'
sawCVSid = False
for child in dom.childNodes:
if child.nodeType == dom.COMMENT_NODE:
if child.nodeValue.startswith(' $Id') \
and child.nodeValue.endswith('$ '):
sawCVSid = True
elif child.nodeType == dom.DOCUMENT_TYPE_NODE:
if child.nodeName != 'msxconfig':
print ' NOTE: unknown document type "%s", skipping' % \
child.nodeName
return
elif child.nodeType == dom.ELEMENT_NODE:
if child.nodeName == 'msxconfig':
convertRoot(child, checksums)
else:
print ' NOTE: wrong root node "%s", skipping' % child.nodeName
return
if not sawCVSid:
print ' NOTE: no CVS id'
def convertRoot(node, checksums):
doc = node.ownerDocument
# Process everything except devices.
externalSlotsNode = None
motherBoardNode = None
sawInfo = False
for child in list(node.childNodes):
if child.nodeType == node.ELEMENT_NODE:
if child.nodeName == 'config':
child = convertConfig(child)
if child is not None:
if child.nodeName == 'ExternalSlots':
externalSlotsNode = child
node.removeChild(child)
elif child.nodeName == 'MotherBoard':
motherBoardNode = child
node.removeChild(child)
elif child.nodeName == 'info':
sawInfo = True
elif child.nodeName != 'device':
print ' NOTE: ignoring element at top level:', child.nodeName
# Insert <info> if necessary.
if not sawInfo:
print ' NOTE: inserting empty info block, please fill it'
infoNode = doc.createElement('info')
infoNode.appendChild(doc.createElement('manufacturer'))
infoNode.appendChild(doc.createElement('code'))
infoNode.appendChild(doc.createElement('release_year'))
infoNode.appendChild(doc.createElement('description'))
infoNode.appendChild(doc.createElement('type'))
node.insertBefore(infoNode, node.firstChild)
# Determine which slots are expanded.
slotExpanded = [ None ] * 4
if motherBoardNode is not None:
for child in motherBoardNode.childNodes:
if child.nodeType == node.ELEMENT_NODE:
assert child.nodeName == 'slot'
num = int(child.attributes['num'].nodeValue)
assert 0 <= num < 4
expanded = bool([ 'false', 'true' ].index(
child.attributes['expanded'].nodeValue
))
slotExpanded[num] = expanded
motherBoardNode.unlink()
# Determine which slots are external.
externalSlots = {}
if externalSlotsNode is not None:
for child in externalSlotsNode.childNodes:
if child.nodeType == node.ELEMENT_NODE:
assert child.nodeName.startswith('slot')
slot = map(int, getText(child).split('-'))
assert len(slot) == 2
externalSlots[tuple(slot)] = None
# Process devices.
devicesNode = doc.createElement('devices')
node.appendChild(devicesNode)
slottedDevices = {}
for child in list(node.childNodes):
if child.nodeType == node.ELEMENT_NODE and child.nodeName == 'device':
slotted, child = convertDevice(child, checksums)
if child is not None:
node.removeChild(child)
# Insert slot mapping, if any.
if slotted == []:
devicesNode.appendChild(child)
else:
primary, secondary, page = slotted[0]
pages = [ False ] * 4
for ps, ss, pg in slotted:
assert primary == ps and secondary == ss
assert -1 <= ps < 4
if ps == -1:
assert ss == -1
elif slotExpanded[ps]:
assert 0 <= ss < 4
else:
assert ss == 0
assert 0 <= pg < 4
pages[pg] = True
devices = slottedDevices.setdefault(
(primary, secondary), [] )
devices.append((child, pages))
def convertSlotted(parentNode, primary, secondary = 0):
if (primary, secondary) in externalSlots:
assert primary != -1
print ' external'
del externalSlots[(primary, secondary)]
parentNode.setAttribute('external', 'true')
else:
devices = slottedDevices.get((primary, secondary))
if devices is None:
return
del slottedDevices[primary, secondary]
for deviceNode, pages in devices:
page = 0
while page < 4:
# Skip empty pages.
while page < 4 and not pages[page]:
page += 1
if page == 4: break
# Iterate through non-empty pages.
start = page
while page < 4 and pages[page]:
page += 1
if page == start + 1:
print ' device "%s" in page %d' % (
deviceNode.tagName, start )
else:
print ' device "%s" in pages %d-%d' % (
deviceNode.tagName, start, page - 1 )
memNode = parentNode.ownerDocument.createElement('mem')
memNode.setAttribute(
'base', hexFill(start * 0x4000, 4) )
memNode.setAttribute(
'size', hexFill((page - start) * 0x4000, 4) )
deviceNode.appendChild(memNode)
parentNode.appendChild(deviceNode)
if (-1, -1) in slottedDevices:
print ' cartridge devices:'
primaryNode = doc.createElement('primary')
primaryNode.setAttribute('slot', 'any')
devicesNode.appendChild(primaryNode)
secondaryNode = doc.createElement('secondary')
secondaryNode.setAttribute('slot', 'any')
primaryNode.appendChild(secondaryNode)
convertSlotted(secondaryNode, primary, secondary)
if slottedDevices != {}:
print ' NOTE: file contains both fixed and variable slots'
if slottedDevices != {}:
for primary in range(4):
primaryNode = doc.createElement('primary')
primaryNode.setAttribute('slot', str(primary))
devicesNode.appendChild(primaryNode)
if slotExpanded[primary]:
for secondary in range(4):
print ' slot %d.%d:' % (primary, secondary)
secondaryNode = doc.createElement('secondary')
secondaryNode.setAttribute('slot', str(secondary))
primaryNode.appendChild(secondaryNode)
convertSlotted(secondaryNode, primary, secondary)
else:
print ' slot %d:' % primary
convertSlotted(primaryNode, primary)
leftoverDevices = list(slottedDevices.items())
leftoverDevices.sort()
for slot, deviceNode in leftoverDevices:
print ' NOTE: skipping device "%s" in unavailable ' \
'slot %d.%d page %d' % (
deviceNode.tagName, slot[0], slot[1], slot[2]
)
leftoverExternalSlots = list(externalSlots)
leftoverExternalSlots.sort()
for primary, secondary in leftoverExternalSlots:
print ' NOTE: skipping unavailable external slot %d.%d' % (
primary, secondary
)
def convertConfig(node):
doc = node.ownerDocument
configId = node.attributes['id'].nodeValue
print ' config:', configId
for child in list(node.childNodes):
if child.nodeType == node.ELEMENT_NODE:
if child.nodeName == 'parameter':
child = convertParameter(child)
# Type is now stored in tag name instead of "id" attribute.
node.removeAttribute('id')
node = renameElement(node, configId)
if configId == 'MapperType':
# Store type in body text instead of "type" tag.
value = getParameter(node, 'type')
newValue = { 'Philips': 'largest', 'TurboR': '5' }.get(value)
if newValue is None:
print ' NOTE: MapperReadBackBits has invalid value "%s"' % value
newValue = value
newNode = doc.createElement('MapperReadBackBits')
newNode.appendChild(doc.createTextNode(newValue))
node.parentNode.replaceChild(newNode, node)
node.unlink()
return None
elif configId not in [
'CassettePort', 'ExternalSlots', 'MotherBoard', 'RenShaTurbo'
]:
print ' NOTE: conversion of config type "%s" may be wrong' \
% configId
# TODO: CassettePort: if only whitespace text nodes, then remove them
# TODO: myHD: conversion of IDE HD configuration is not implemented
return node
def convertDevice(node, checksums):
doc = node.ownerDocument
print ' device:', node.attributes['id'].nodeValue
deviceType = getParameter(node, 'type')
assert deviceType is not None
newDeviceType = {
'FM-PAC': 'FMPAC',
'Rom': 'ROM',
'PanasonicRam': 'PanasonicRAM',
'Music': 'MSX-MUSIC',
'Audio': 'MSX-AUDIO',
'Audio-Midi': 'Music Module MIDI',
'MSX-AUDIO MIDI': 'Music Module MIDI',
'SCCPlusCart': 'SCC+',
'MSX-Midi': 'MSX-MIDI',
}.get(deviceType)
if newDeviceType is not None:
print ' rename type "' + deviceType + '" to "' + newDeviceType + '"'
deviceType = newDeviceType
if deviceType == 'CPU':
print ' removing CPU device'
node.parentNode.removeChild(node)
node.unlink()
return None, None
# Convert parameters.
slotted = []
drives = 0
for child in list(node.childNodes):
if child.nodeType == node.ELEMENT_NODE:
if child.nodeName == 'type':
node.removeChild(child)
child.unlink()
else:
if child.nodeName == 'parameter':
child = convertParameter(child)
newName = getNewParameterName(deviceType, child.nodeName)
if deviceType == 'FDC' and newName == 'fdc_type':
deviceType = getText(child)
newName = None
elif newName == 'slotted':
slotted.append(parseSlotted(child))
newName = None
elif newName is not None and newName.startswith('drivename'):
drives += 1
newName = None
if newName is None:
print ' remove parameter "' + child.nodeName + '"'
node.removeChild(child)
child.unlink()
elif newName != child.nodeName:
print ' rename parameter "' + child.nodeName + '" ' \
'to "' + newName + '"'
child = renameElement(child, newName)
# Note: must happen here because fdc_type can rename node.
node = renameElement(node, deviceType)
# Insert <drives> tag to replace "drivename" parameters.
if drives != 0:
print ' inserting drive tag'
drivesNode = doc.createElement('drives')
numNode = doc.createTextNode(str(drives))
drivesNode.appendChild(numNode)
node.appendChild(drivesNode)
# Bundle generic ROM parameters in <rom> tag.
def convertFileName(fileNameParam):
romParams = extractElements(node, [ fileNameParam ])
if romParams == []:
return None
assert len(romParams) == 1
paramNode = romParams[0]
print ' grouping rom parameters'
romNode = doc.createElement('rom')
romNode.appendChild(paramNode)
if paramNode.tagName != 'filename':
paramNode = renameElement(paramNode, 'filename')
fileName = getText(paramNode)
fileName = fileName[fileName.rfind('/') + 1 : ]
checksum = checksums.get(fileName)
if checksum is None:
print ' NOTE: no sha1 found for "%s"' % fileName
else:
print ' inserting sha1 for "%s"' % fileName
checksumNode = doc.createElement('sha1')
checksumNode.appendChild(doc.createTextNode(checksum))
romNode.appendChild(checksumNode)
return romNode
if deviceType != 'DebugDevice':
romNode = convertFileName('filename')
if romNode is not None:
node.appendChild(romNode)
romNode2 = convertFileName('jisyofilename')
if romNode2 is not None:
romNode.setAttribute('id', 'bunsetsu')
romNode2.setAttribute('id', 'jisyo')
node.appendChild(romNode2)
# Bundle generic sound parameters in <sound> tag.
soundParams = extractElements(node, ['mode', 'volume'])
if soundParams != []:
print ' grouping sound parameters'
soundNode = doc.createElement('sound')
for param in soundParams:
soundNode.appendChild(param)
node.appendChild(soundNode)
# Insert I/O addresses.
if deviceType == 'VDP':
deviceType = {
'TMS99X8A': 'VDP1', 'TMS9929A': 'VDP1',
'V9938': 'VDP2', 'V9958': 'VDP2',
}[getParameter(node, 'version')]
elif deviceType == 'Kanji':
print ' NOTE: Check whether machine has 2 Kanji devices'
deviceType = 'Kanji1'
ioList = ioAddresses.get(deviceType)
if ioList is None:
print 'no I/O list for device:', deviceType
assert False
else:
if len(node.getElementsByTagName('io')) == 0:
if len(ioList) != 0:
print ' inserting I/O addresses'
for base, num, direction in ioList:
assert 0 <= base < 0x100
assert num in [ 1, 2, 4, 8, 16]
assert direction in ['I', 'O', 'IO']
ioNode = doc.createElement('io')
ioNode.setAttribute('base', hexFill(base, 2))
ioNode.setAttribute('num', str(num))
if direction != 'IO':
ioNode.setAttribute('type', direction)
node.appendChild(ioNode)
return slotted, node
def getNewParameterName(deviceType, name):
return {
'FDC': {
'type': 'fdc_type',
'brokenFDCread': 'broken_fdc_read',
},
'RTC': {
'mode': None,
},
}.get(deviceType, {}).get(name, name)
def convertParameter(node):
name = node.attributes['name'].nodeValue
node.removeAttribute('name')
if len(node.attributes) == 0:
parent = node.parentNode
deviceType = getParameter(parent, 'type')
print ' convert parameter "%s"' % name
assert len(node.childNodes) == 1
return renameElement(node, name)
else:
assert len(node.attributes) == 1
clazz = node.attributes['class'].nodeValue
node.removeAttribute('class')
assert clazz == 'subslotted', clazz
print ' convert parameter "%s": %s' % (clazz, name)
assert len(node.childNodes) == 1
value = node.childNodes[0].nodeValue
assert value in [ 'true', 'false' ], value
newNode = node.ownerDocument.createElement('slot')
newNode.setAttribute('num', name)
newNode.setAttribute('expanded', value)
node.parentNode.replaceChild(newNode, node)
node.unlink()
return newNode
def parseSlotted(node):
primary, secondary, page = None, None, None
for child in list(node.childNodes):
if child.nodeType == node.ELEMENT_NODE:
if child.nodeName == 'ps':
primary = int(getText(child))
elif child.nodeName == 'ss':
secondary = int(getText(child))
elif child.nodeName == 'page':
page = int(getText(child))
return primary, secondary, page
def stripSpaces(node):
if node.nodeType == node.TEXT_NODE:
if node.nodeValue.isspace():
node.parentNode.removeChild(node)
node.unlink()
else:
for child in list(node.childNodes):
stripSpaces(child)
def layoutDocument(dom):
for child in dom.childNodes:
if child.nodeType == dom.ELEMENT_NODE:
layoutNode(child)
def layoutNode(node, indent = '', lineSpacing = 2):
hasElements = False
for child in list(node.childNodes):
if child.nodeType == node.ELEMENT_NODE:
if child.tagName == 'secondary': lineSpacing = 2
hasElements = True
node.insertBefore(
child.ownerDocument.createTextNode(
'\n' * lineSpacing + ' ' + indent
),
child
)
layoutNode(
child,
indent + ' ',
1 + int(child.tagName in ['devices'])
)
elif child.nodeType == node.COMMENT_NODE:
node.insertBefore(
child.ownerDocument.createTextNode(
'\n' * lineSpacing + ' ' + indent
),
child
)
if hasElements:
node.appendChild(node.ownerDocument.createTextNode(
'\n' * lineSpacing + indent
))
if len(sys.argv) != 3:
print 'Usage: convert_hardwareconfig.py <indir> <outdir>'
sys.exit(2)
indir = sys.argv[1]
outdir = sys.argv[2]
if outdir[-1] != '/': outdir += '/'
for root, dirs, files in os.walk(indir):
if 'hardwareconfig.xml' in files:
print 'Converting ' + root.split('/')[-1] + '...'
assert root.startswith(indir)
outpath = outdir + root[len(indir) : ]
checksums = {}
if os.path.isdir(root + '/roms') \
and os.path.isfile(root + '/roms/SHA1SUMS'):
for line in open(root + '/roms/SHA1SUMS'):
checksum, empty, fileName = line[ : -1].split(' ')
assert empty == ''
checksums[fileName] = checksum
dom = parse(root + '/hardwareconfig.xml')
dom.normalize()
stripSpaces(dom)
convertDoc(dom, checksums)
layoutDocument(dom)
if not os.path.isdir(outpath):
os.makedirs(outpath)
out = StringIO()
dom.writexml(out)
out.seek(0)
outFile = open(outpath + '/hardwareconfig.xml', 'w')
# Minidom doesn't seem to allow text nodes at document level,
# so do some postprocessing using string manipulation.
afterDoctype = False
for line in out.readlines():
if line.startswith('<!--'):
index = 0
while True:
start = index
index = line.find('-->', start)
if index == -1:
line = line[start : ]
break
index += 3
outFile.write(line[start : index] + '\n')
if line.startswith('<!DOCTYPE'):
outFile.write(line[ : -1])
afterDoctype = True
elif afterDoctype:
index = 0
while line[index].isspace(): index += 1
outFile.write(' ' + line[index : ])
afterDoctype = False
else:
outFile.write(line)
outFile.write('\n')
outFile.close()
out.close()
dom.unlink()
|