summaryrefslogtreecommitdiffstatshomepage
path: root/src/emu/audit.c
blob: b8ab208d6a00e6ad753c08b7b954c691fc648334 (plain) (blame)
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
// license:BSD-3-Clause
// copyright-holders:Aaron Giles
/***************************************************************************

    audit.c

    ROM set auditing functions.

***************************************************************************/

#include "emu.h"
#include "emuopts.h"
#include "audit.h"
#include "chd.h"
#include "sound/samples.h"


//**************************************************************************
//  CORE FUNCTIONS
//**************************************************************************

//-------------------------------------------------
//  media_auditor - constructor
//-------------------------------------------------

media_auditor::media_auditor(const driver_enumerator &enumerator)
	: m_enumerator(enumerator),
		m_validation(AUDIT_VALIDATE_FULL),
		m_searchpath(NULL)
{
}


//-------------------------------------------------
//  audit_media - audit the media described by the
//  currently-enumerated driver
//-------------------------------------------------

media_auditor::summary media_auditor::audit_media(const char *validation)
{
	// start fresh
	m_record_list.reset();

	// store validation for later
	m_validation = validation;

// temporary hack until romload is update: get the driver path and support it for
// all searches
const char *driverpath = m_enumerator.config().root_device().searchpath();

	int found = 0;
	int required = 0;
	int shared_found = 0;
	int shared_required = 0;

	// iterate over devices and regions
	device_iterator deviter(m_enumerator.config().root_device());
	for (device_t *device = deviter.first(); device != NULL; device = deviter.next())
	{
		// determine the search path for this source and iterate through the regions
		m_searchpath = device->searchpath();

		// now iterate over regions and ROMs within
		for (const rom_entry *region = rom_first_region(*device); region != NULL; region = rom_next_region(region))
		{
// temporary hack: add the driver path & region name
std::string combinedpath = std::string(device->searchpath()).append(";").append(driverpath);
if (device->shortname())
	combinedpath.append(";").append(device->shortname());
m_searchpath = combinedpath.c_str();

			for (const rom_entry *rom = rom_first_file(region); rom; rom = rom_next_file(rom))
			{
				const char *name = ROM_GETNAME(rom);
				hash_collection hashes(ROM_GETHASHDATA(rom));
				device_t *shared_device = find_shared_device(*device, name, hashes, ROM_GETLENGTH(rom));

				// count the number of files with hashes
				if (!hashes.flag(hash_collection::FLAG_NO_DUMP) && !ROM_ISOPTIONAL(rom))
				{
					required++;
					if (shared_device != NULL)
						shared_required++;
				}

				// audit a file
				audit_record *record = NULL;
				if (ROMREGION_ISROMDATA(region))
					record = audit_one_rom(rom);

				// audit a disk
				else if (ROMREGION_ISDISKDATA(region))
					record = audit_one_disk(rom);

				if (record != NULL)
				{
					// count the number of files that are found.
					if (record->status() == audit_record::STATUS_GOOD || (record->status() == audit_record::STATUS_FOUND_INVALID && find_shared_device(*device, name, record->actual_hashes(), record->actual_length()) == NULL))
					{
						found++;
						if (shared_device != NULL)
							shared_found++;
					}

					record->set_shared_device(shared_device);
				}
			}
		}
	}

	// if we only find files that are in the parent & either the set has no unique files or the parent is not found, then assume we don't have the set at all
	if (found == shared_found && required > 0 && (required != shared_required || shared_found == 0))
	{
		m_record_list.reset();
		return NOTFOUND;
	}

	// return a summary
	return summarize(m_enumerator.driver().name);
}


//-------------------------------------------------
//  audit_device - audit the device
//-------------------------------------------------

media_auditor::summary media_auditor::audit_device(device_t *device, const char *validation)
{
	// start fresh
	m_record_list.reset();

	// store validation for later
	m_validation = validation;
	m_searchpath = device->shortname();

	int found = 0;
	int required = 0;

	// now iterate over regions and ROMs within
	for (const rom_entry *region = rom_first_region(*device); region != NULL; region = rom_next_region(region))
	{
		for (const rom_entry *rom = rom_first_file(region); rom; rom = rom_next_file(rom))
		{
			hash_collection hashes(ROM_GETHASHDATA(rom));

			// count the number of files with hashes
			if (!hashes.flag(hash_collection::FLAG_NO_DUMP) && !ROM_ISOPTIONAL(rom))
			{
				required++;
			}

			// audit a file
			audit_record *record = NULL;
			if (ROMREGION_ISROMDATA(region))
				record = audit_one_rom(rom);

			// audit a disk
			else if (ROMREGION_ISDISKDATA(region))
				record = audit_one_disk(rom);

			// count the number of files that are found.
			if (record != NULL && (record->status() == audit_record::STATUS_GOOD || record->status() == audit_record::STATUS_FOUND_INVALID))
			{
				found++;
			}
		}
	}

	if (found == 0 && required > 0)
	{
		m_record_list.reset();
		return NOTFOUND;
	}

	// return a summary
	return summarize(device->shortname());
}


//-------------------------------------------------
//  audit_software
//-------------------------------------------------
media_auditor::summary media_auditor::audit_software(const char *list_name, software_info *swinfo, const char *validation)
{
	// start fresh
	m_record_list.reset();

	// store validation for later
	m_validation = validation;

	std::string combinedpath(swinfo->shortname());
	combinedpath.append(";");
	combinedpath.append(list_name);
	combinedpath.append(PATH_SEPARATOR);
	combinedpath.append(swinfo->shortname());
	std::string locationtag(list_name);
	locationtag.append("%");
	locationtag.append(swinfo->shortname());
	locationtag.append("%");
	if (swinfo->parentname() != NULL)
	{
		locationtag.append(swinfo->parentname());
		combinedpath.append(";").append(swinfo->parentname()).append(";").append(list_name).append(PATH_SEPARATOR).append(swinfo->parentname());
	}
	m_searchpath = combinedpath.c_str();

	int found = 0;
	int required = 0;

	// now iterate over software parts
	for ( software_part *part = swinfo->first_part(); part != NULL; part = part->next() )
	{
		// now iterate over regions
		for ( const rom_entry *region = part->romdata(); region; region = rom_next_region( region ) )
		{
			// now iterate over rom definitions
			for (const rom_entry *rom = rom_first_file(region); rom; rom = rom_next_file(rom))
			{
				hash_collection hashes(ROM_GETHASHDATA(rom));

				// count the number of files with hashes
				if (!hashes.flag(hash_collection::FLAG_NO_DUMP) && !ROM_ISOPTIONAL(rom))
				{
					required++;
				}

				// audit a file
				audit_record *record = NULL;
				if (ROMREGION_ISROMDATA(region))
				{
					record = audit_one_rom(rom);
				}
				// audit a disk
				else if (ROMREGION_ISDISKDATA(region))
				{
					record = audit_one_disk(rom, locationtag.c_str());
				}

				// count the number of files that are found.
				if (record != NULL && (record->status() == audit_record::STATUS_GOOD || record->status() == audit_record::STATUS_FOUND_INVALID))
				{
					found++;
				}
			}
		}
	}

	if (found == 0 && required > 0)
	{
		m_record_list.reset();
		return NOTFOUND;
	}

	// return a summary
	return summarize(list_name);
}


//-------------------------------------------------
//  audit_samples - validate the samples for the
//  currently-enumerated driver
//-------------------------------------------------

media_auditor::summary media_auditor::audit_samples()
{
	// start fresh
	m_record_list.reset();

	int required = 0;
	int found = 0;

	// iterate over sample entries
	samples_device_iterator iter(m_enumerator.config().root_device());
	for (samples_device *device = iter.first(); device != NULL; device = iter.next())
	{
		// by default we just search using the driver name
		std::string searchpath(m_enumerator.driver().name);

		// add the alternate path if present
		samples_iterator iter(*device);
		if (iter.altbasename() != NULL)
			searchpath.append(";").append(iter.altbasename());

		// iterate over samples in this entry
		for (const char *samplename = iter.first(); samplename != NULL; samplename = iter.next())
		{
			required++;

			// create a new record
			audit_record &record = m_record_list.append(*global_alloc(audit_record(samplename, audit_record::MEDIA_SAMPLE)));

			// look for the files
			emu_file file(m_enumerator.options().sample_path(), OPEN_FLAG_READ | OPEN_FLAG_NO_PRELOAD);
			path_iterator path(searchpath.c_str());
			std::string curpath;
			while (path.next(curpath, samplename))
			{
				// attempt to access the file (.flac) or (.wav)
				file_error filerr = file.open(curpath.c_str(), ".flac");
				if (filerr != FILERR_NONE)
					filerr = file.open(curpath.c_str(), ".wav");

				if (filerr == FILERR_NONE)
				{
					record.set_status(audit_record::STATUS_GOOD, audit_record::SUBSTATUS_GOOD);
					found++;
				}
				else
					record.set_status(audit_record::STATUS_NOT_FOUND, audit_record::SUBSTATUS_NOT_FOUND);
			}
		}
	}

	if (found == 0 && required > 0)
	{
		m_record_list.reset();
		return NOTFOUND;
	}

	// return a summary
	return summarize(m_enumerator.driver().name);
}


//-------------------------------------------------
//  summary - generate a summary, with an optional
//  string format
//-------------------------------------------------

media_auditor::summary media_auditor::summarize(const char *name, std::string *output)
{
	if (m_record_list.count() == 0)
	{
		return NONE_NEEDED;
	}

	// loop over records
	summary overall_status = CORRECT;
	for (audit_record *record = m_record_list.first(); record != NULL; record = record->next())
	{
		summary best_new_status = INCORRECT;

		// skip anything that's fine
		if (record->substatus() == audit_record::SUBSTATUS_GOOD)
			continue;

		// output the game name, file name, and length (if applicable)
		if (output != NULL)
		{
			strcatprintf(*output,"%-12s: %s", name, record->name());
			if (record->expected_length() > 0)
				strcatprintf(*output," (%" I64FMT "d bytes)", record->expected_length());
			strcatprintf(*output," - ");
		}

		// use the substatus for finer details
		switch (record->substatus())
		{
			case audit_record::SUBSTATUS_GOOD_NEEDS_REDUMP:
				if (output != NULL) strcatprintf(*output,"NEEDS REDUMP\n");
				best_new_status = BEST_AVAILABLE;
				break;

			case audit_record::SUBSTATUS_FOUND_NODUMP:
				if (output != NULL) strcatprintf(*output,"NO GOOD DUMP KNOWN\n");
				best_new_status = BEST_AVAILABLE;
				break;

			case audit_record::SUBSTATUS_FOUND_BAD_CHECKSUM:
				if (output != NULL)
				{
					std::string tempstr;
					strcatprintf(*output,"INCORRECT CHECKSUM:\n");
					strcatprintf(*output,"EXPECTED: %s\n", record->expected_hashes().macro_string(tempstr));
					strcatprintf(*output,"   FOUND: %s\n", record->actual_hashes().macro_string(tempstr));
				}
				break;

			case audit_record::SUBSTATUS_FOUND_WRONG_LENGTH:
				if (output != NULL) strcatprintf(*output,"INCORRECT LENGTH: %" I64FMT "d bytes\n", record->actual_length());
				break;

			case audit_record::SUBSTATUS_NOT_FOUND:
				if (output != NULL)
				{
					device_t *shared_device = record->shared_device();
					if (shared_device == NULL)
						strcatprintf(*output,"NOT FOUND\n");
					else
						strcatprintf(*output,"NOT FOUND (%s)\n", shared_device->shortname());
				}
				best_new_status = NOTFOUND;
				break;

			case audit_record::SUBSTATUS_NOT_FOUND_NODUMP:
				if (output != NULL) strcatprintf(*output,"NOT FOUND - NO GOOD DUMP KNOWN\n");
				best_new_status = BEST_AVAILABLE;
				break;

			case audit_record::SUBSTATUS_NOT_FOUND_OPTIONAL:
				if (output != NULL) strcatprintf(*output,"NOT FOUND BUT OPTIONAL\n");
				best_new_status = BEST_AVAILABLE;
				break;

			default:
				assert(false);
		}

		// downgrade the overall status if necessary
		overall_status = MAX(overall_status, best_new_status);
	}
	return overall_status;
}


//-------------------------------------------------
//  audit_one_rom - validate a single ROM entry
//-------------------------------------------------

audit_record *media_auditor::audit_one_rom(const rom_entry *rom)
{
	// allocate and append a new record
	audit_record &record = m_record_list.append(*global_alloc(audit_record(*rom, audit_record::MEDIA_ROM)));

	// see if we have a CRC and extract it if so
	UINT32 crc = 0;
	bool has_crc = record.expected_hashes().crc(crc);

	// find the file and checksum it, getting the file length along the way
	emu_file file(m_enumerator.options().media_path(), OPEN_FLAG_READ | OPEN_FLAG_NO_PRELOAD);
	file.set_restrict_to_mediapath(true);
	path_iterator path(m_searchpath);
	std::string curpath;
	while (path.next(curpath, record.name()))
	{
		// open the file if we can
		file_error filerr;
		if (has_crc)
			filerr = file.open(curpath.c_str(), crc);
		else
			filerr = file.open(curpath.c_str());

		// if it worked, get the actual length and hashes, then stop
		if (filerr == FILERR_NONE)
		{
			record.set_actual(file.hashes(m_validation), file.size());
			break;
		}
	}

	// compute the final status
	compute_status(record, rom, record.actual_length() != 0);
	return &record;
}


//-------------------------------------------------
//  audit_one_disk - validate a single disk entry
//-------------------------------------------------

audit_record *media_auditor::audit_one_disk(const rom_entry *rom, const char *locationtag)
{
	// allocate and append a new record
	audit_record &record = m_record_list.append(*global_alloc(audit_record(*rom, audit_record::MEDIA_DISK)));

	// open the disk
	chd_file source;
	chd_error err = chd_error(open_disk_image(m_enumerator.options(), &m_enumerator.driver(), rom, source, locationtag));

	// if we succeeded, get the hashes
	if (err == CHDERR_NONE)
	{
		hash_collection hashes;

		// if there's a SHA1 hash, add them to the output hash
		if (source.sha1() != sha1_t::null)
			hashes.add_sha1(source.sha1());

		// update the actual values
		record.set_actual(hashes);
	}

	// compute the final status
	compute_status(record, rom, err == CHDERR_NONE);
	return &record;
}


//-------------------------------------------------
//  compute_status - compute a detailed status
//  based on the information we have
//-------------------------------------------------

void media_auditor::compute_status(audit_record &record, const rom_entry *rom, bool found)
{
	// if not found, provide more details
	if (!found)
	{
		// no good dump
		if (record.expected_hashes().flag(hash_collection::FLAG_NO_DUMP))
			record.set_status(audit_record::STATUS_NOT_FOUND, audit_record::SUBSTATUS_NOT_FOUND_NODUMP);

		// optional ROM
		else if (ROM_ISOPTIONAL(rom))
			record.set_status(audit_record::STATUS_NOT_FOUND, audit_record::SUBSTATUS_NOT_FOUND_OPTIONAL);

		// just plain old not found
		else
			record.set_status(audit_record::STATUS_NOT_FOUND, audit_record::SUBSTATUS_NOT_FOUND);
	}

	// if found, provide more details
	else
	{
		// length mismatch
		if (record.expected_length() != record.actual_length())
			record.set_status(audit_record::STATUS_FOUND_INVALID, audit_record::SUBSTATUS_FOUND_WRONG_LENGTH);

		// found but needs a dump
		else if (record.expected_hashes().flag(hash_collection::FLAG_NO_DUMP))
			record.set_status(audit_record::STATUS_GOOD, audit_record::SUBSTATUS_FOUND_NODUMP);

		// incorrect hash
		else if (record.expected_hashes() != record.actual_hashes())
			record.set_status(audit_record::STATUS_FOUND_INVALID, audit_record::SUBSTATUS_FOUND_BAD_CHECKSUM);

		// correct hash but needs a redump
		else if (record.expected_hashes().flag(hash_collection::FLAG_BAD_DUMP))
			record.set_status(audit_record::STATUS_GOOD, audit_record::SUBSTATUS_GOOD_NEEDS_REDUMP);

		// just plain old good
		else
			record.set_status(audit_record::STATUS_GOOD, audit_record::SUBSTATUS_GOOD);
	}
}


//-------------------------------------------------
//  find_shared_device - return the source that
//  shares a media entry with the same hashes
//-------------------------------------------------

device_t *media_auditor::find_shared_device(device_t &device, const char *name, const hash_collection &romhashes, UINT64 romlength)
{
	bool dumped = !romhashes.flag(hash_collection::FLAG_NO_DUMP);

	// special case for non-root devices
	device_t *highest_device = NULL;
	if (device.owner() != NULL)
	{
		for (const rom_entry *region = rom_first_region(device); region != NULL; region = rom_next_region(region))
			for (const rom_entry *rom = rom_first_file(region); rom != NULL; rom = rom_next_file(rom))
				if (ROM_GETLENGTH(rom) == romlength)
				{
					hash_collection hashes(ROM_GETHASHDATA(rom));
					if ((dumped && hashes == romhashes) || (!dumped && ROM_GETNAME(rom) == name))
						highest_device = &device;
				}
	}
	else
	{
		// iterate up the parent chain
		for (int drvindex = m_enumerator.find(m_enumerator.driver().parent); drvindex != -1; drvindex = m_enumerator.find(m_enumerator.driver(drvindex).parent))
		{
			device_iterator deviter(m_enumerator.config(drvindex).root_device());
			for (device_t *scandevice = deviter.first(); scandevice != NULL; scandevice = deviter.next())
				for (const rom_entry *region = rom_first_region(*scandevice); region; region = rom_next_region(region))
					for (const rom_entry *rom = rom_first_file(region); rom; rom = rom_next_file(rom))
						if (ROM_GETLENGTH(rom) == romlength)
						{
							hash_collection hashes(ROM_GETHASHDATA(rom));
							if ((dumped && hashes == romhashes) || (!dumped && ROM_GETNAME(rom) == name))
								highest_device = scandevice;
						}
		}
	}

	return highest_device;
}


//-------------------------------------------------
//  audit_record - constructor
//-------------------------------------------------

audit_record::audit_record(const rom_entry &media, media_type type)
	: m_next(NULL),
		m_type(type),
		m_status(STATUS_ERROR),
		m_substatus(SUBSTATUS_ERROR),
		m_name(ROM_GETNAME(&media)),
		m_explength(rom_file_size(&media)),
		m_length(0),
		m_shared_device(NULL)
{
	m_exphashes.from_internal_string(ROM_GETHASHDATA(&media));
}

audit_record::audit_record(const char *name, media_type type)
	: m_next(NULL),
		m_type(type),
		m_status(STATUS_ERROR),
		m_substatus(SUBSTATUS_ERROR),
		m_name(name),
		m_explength(0),
		m_length(0),
		m_shared_device(NULL)
{
}
an class="kt">void natural_keyboard::set_in_use(bool usage) { if (m_in_use != usage) { // update active usage m_in_use = usage; machine().options().set_value(OPTION_NATURAL_KEYBOARD, usage, OPTION_PRIORITY_CMDLINE); // lock out (or unlock) all keyboard inputs for (auto &port : machine().ioport().ports()) for (ioport_field &field : port.second->fields()) if (field.type() == IPT_KEYBOARD) { field.live().lockout = usage; // clear pressed status when going out of use if (!usage) field.set_value(0); } } } //------------------------------------------------- // post - post a single character //------------------------------------------------- void natural_keyboard::post(char32_t ch) { // ignore any \n that are preceded by \r if (m_last_cr && ch == '\n') { m_last_cr = false; return; } // change all eolns to '\r' if (ch == '\n') ch = '\r'; else m_last_cr = (ch == '\r'); // logging if (LOG_NATURAL_KEYBOARD) { const keycode_map_entry *code = find_code(ch); machine().logerror("natural_keyboard::post(): code=%i (%s) field.name='%s'\n", int(ch), unicode_to_string(ch).c_str(), (code != nullptr && code->field[0] != nullptr) ? code->field[0]->name() : "<null>"); } // can we post this key in the queue directly? if (can_post_directly(ch)) internal_post(ch); // can we post this key with an alternate representation? else if (can_post_alternate(ch)) { const char_info *info = char_info::find(ch); assert(info != nullptr && info->alternate != nullptr); const char *altstring = info->alternate; while (*altstring != 0) { altstring += uchar_from_utf8(&ch, altstring, strlen(altstring)); internal_post(ch); } } } //------------------------------------------------- // post - post a unicode encoded string //------------------------------------------------- void natural_keyboard::post(const char32_t *text, size_t length, const attotime &rate) { // set the fixed rate m_current_rate = rate; // 0 length means strlen if (length == 0) for (const char32_t *scan = text; *scan != 0; scan++) length++; // iterate over characters or until the buffer is full up while (length > 0 && !full()) { // fetch next character post(*text++); length--; } } //------------------------------------------------- // post_utf8 - post a UTF-8 encoded string //------------------------------------------------- void natural_keyboard::post_utf8(const char *text, size_t length, const attotime &rate) { // set the fixed rate m_current_rate = rate; // 0-length means strlen if (length == 0) length = strlen(text); // iterate until out of characters while (length > 0) { // decode the next character char32_t uc; int count = uchar_from_utf8(&uc, text, length); if (count < 0) { count = 1; uc = INVALID_CHAR; } // append to the buffer post(uc); text += count; length -= count; } } //------------------------------------------------- // post_coded - post a coded string //------------------------------------------------- void natural_keyboard::post_coded(const char *text, size_t length, const attotime &rate) { static const struct { const char *key; char32_t code; } codes[] = { { "BACKSPACE", 8 }, { "BS", 8 }, { "BKSP", 8 }, { "DEL", UCHAR_MAMEKEY(DEL) }, { "DELETE", UCHAR_MAMEKEY(DEL) }, { "END", UCHAR_MAMEKEY(END) }, { "ENTER", 13 }, { "ESC", '\033' }, { "HOME", UCHAR_MAMEKEY(HOME) }, { "INS", UCHAR_MAMEKEY(INSERT) }, { "INSERT", UCHAR_MAMEKEY(INSERT) }, { "PGDN", UCHAR_MAMEKEY(PGDN) }, { "PGUP", UCHAR_MAMEKEY(PGUP) }, { "SPACE", 32 }, { "TAB", 9 }, { "F1", UCHAR_MAMEKEY(F1) }, { "F2", UCHAR_MAMEKEY(F2) }, { "F3", UCHAR_MAMEKEY(F3) }, { "F4", UCHAR_MAMEKEY(F4) }, { "F5", UCHAR_MAMEKEY(F5) }, { "F6", UCHAR_MAMEKEY(F6) }, { "F7", UCHAR_MAMEKEY(F7) }, { "F8", UCHAR_MAMEKEY(F8) }, { "F9", UCHAR_MAMEKEY(F9) }, { "F10", UCHAR_MAMEKEY(F10) }, { "F11", UCHAR_MAMEKEY(F11) }, { "F12", UCHAR_MAMEKEY(F12) }, { "QUOTE", '\"' } }; // set the fixed rate m_current_rate = rate; // 0-length means strlen if (length == 0) length = strlen(text); // iterate through the source string size_t curpos = 0; while (curpos < length) { // extract next character char32_t ch = text[curpos]; size_t increment = 1; // look for escape characters if (ch == '{') for (auto & code : codes) { size_t keylen = strlen(code.key); if (curpos + keylen + 2 <= length) if (core_strnicmp(code.key, &text[curpos + 1], keylen) == 0 && text[curpos + keylen + 1] == '}') { ch = code.code; increment = keylen + 2; } } // if we got a code, post it if (ch != 0) post(ch); curpos += increment; } } //------------------------------------------------- // build_codes - given an input port table, create // an input code table useful for mapping unicode // chars //------------------------------------------------- void natural_keyboard::build_codes(ioport_manager &manager) { // find all shift keys unsigned mask = 0; ioport_field *shift[SHIFT_COUNT]; std::fill(std::begin(shift), std::end(shift), nullptr); for (auto const &port : manager.ports()) { for (ioport_field &field : port.second->fields()) { if (field.type() == IPT_KEYBOARD) { std::vector<char32_t> const codes = field.keyboard_codes(0); for (char32_t code : codes) { if ((code >= UCHAR_SHIFT_BEGIN) && (code <= UCHAR_SHIFT_END)) { mask |= 1U << (code - UCHAR_SHIFT_BEGIN); shift[code - UCHAR_SHIFT_BEGIN] = &field; } } } } } // iterate over ports and fields for (auto const &port : manager.ports()) { for (ioport_field &field : port.second->fields()) { if (field.type() == IPT_KEYBOARD) { // iterate over all shift states for (unsigned curshift = 0; curshift < SHIFT_STATES; ++curshift) { if (!(curshift & ~mask)) { // fetch the code, ignoring 0 and shiters std::vector<char32_t> const codes = field.keyboard_codes(curshift); for (char32_t code : codes) { if (((code < UCHAR_SHIFT_BEGIN) || (code > UCHAR_SHIFT_END)) && (code != 0)) { // prefer lowest shift state keycode_map::iterator const found(m_keycode_map.find(code)); if ((m_keycode_map.end() == found) || (found->second.shift > curshift)) { keycode_map_entry newcode; std::fill(std::begin(newcode.field), std::end(newcode.field), nullptr); newcode.shift = curshift; unsigned fieldnum = 0; for (unsigned i = 0, bits = curshift; (i < SHIFT_COUNT) && bits; ++i, bits >>= 1) { if (BIT(bits, 0)) newcode.field[fieldnum++] = shift[i]; } assert(fieldnum < ARRAY_LENGTH(newcode.field)); newcode.field[fieldnum] = &field; if (m_keycode_map.end() == found) m_keycode_map.emplace(code, newcode); else found->second = newcode; if (LOG_NATURAL_KEYBOARD) { machine().logerror("natural_keyboard: code=%u (%s) port=%p field.name='%s'\n", code, unicode_to_string(code), (void *)&port, field.name()); } } } } } } } } } } //------------------------------------------------- // can_post_directly - determine if the given // unicode character can be directly posted //------------------------------------------------- bool natural_keyboard::can_post_directly(char32_t ch) { // if we have a queueing callback, then it depends on whether we can accept the character if (!m_queue_chars.isnull()) return m_accept_char.isnull() ? true : m_accept_char(ch); // otherwise, it depends on the input codes const keycode_map_entry *code = find_code(ch); return (code != nullptr && code->field[0] != nullptr); } //------------------------------------------------- // can_post_alternate - determine if the given // unicode character can be posted via translation //------------------------------------------------- bool natural_keyboard::can_post_alternate(char32_t ch) { const char_info *info = char_info::find(ch); if (info == nullptr) return false; const char *altstring = info->alternate; if (altstring == nullptr) return false; while (*altstring != 0) { char32_t uchar; int count = uchar_from_utf8(&uchar, altstring, strlen(altstring)); if (count <= 0) return false; if (!can_post_directly(uchar)) return false; altstring += count; } return true; } //------------------------------------------------- // choose_delay - determine the delay between // posting keyboard events //------------------------------------------------- attotime natural_keyboard::choose_delay(char32_t ch) { // if we have a live rate, just use that if (m_current_rate != attotime::zero) return m_current_rate; // systems with queue_chars can afford a much smaller delay if (!m_queue_chars.isnull()) return attotime::from_msec(10); // otherwise, default to constant delay with a longer delay on CR return attotime::from_msec((ch == '\r') ? 200 : 50); } //------------------------------------------------- // internal_post - post a keyboard event //------------------------------------------------- void natural_keyboard::internal_post(char32_t ch) { // need to start up the timer? if (empty()) { m_timer->adjust(choose_delay(ch)); m_fieldnum = 0; m_status_keydown = false; } // add to the buffer, resizing if necessary m_buffer[m_bufend++] = ch; if ((m_bufend + 1) % m_buffer.size() == m_bufbegin) m_buffer.resize(m_buffer.size() + KEY_BUFFER_SIZE); m_bufend %= m_buffer.size(); } //------------------------------------------------- // timer - timer callback to keep things flowing // when posting a string of characters //------------------------------------------------- void natural_keyboard::timer(void *ptr, int param) { if (!m_queue_chars.isnull()) { // the driver has a queue_chars handler while (!empty() && m_queue_chars(&m_buffer[m_bufbegin], 1)) { m_bufbegin = (m_bufbegin + 1) % m_buffer.size(); if (m_current_rate != attotime::zero) break; } } else { // the driver does not have a queue_chars handler // loop through this character's component codes const keycode_map_entry *const code = find_code(m_buffer[m_bufbegin]); bool advance; if (code) { do { assert(m_fieldnum < ARRAY_LENGTH(code->field)); ioport_field *const field = code->field[m_fieldnum]; if (field) { // special handling for toggle fields if (!field->live().toggle) field->set_value(!m_status_keydown); else if (!m_status_keydown) field->set_value(!field->digital_value()); } } while (code->field[m_fieldnum] && (++m_fieldnum < ARRAY_LENGTH(code->field)) && m_status_keydown); advance = (m_fieldnum >= ARRAY_LENGTH(code->field)) || !code->field[m_fieldnum]; } else { advance = true; } if (advance) { m_fieldnum = 0; m_status_keydown = !m_status_keydown; // proceed to next character when keydown expires if (!m_status_keydown) m_bufbegin = (m_bufbegin + 1) % m_buffer.size(); } } // need to make sure timerproc is called again if buffer not empty if (!empty()) m_timer->adjust(choose_delay(m_buffer[m_bufbegin])); } //------------------------------------------------- // unicode_to_string - obtain a string // representation of a given code; used for // logging and debugging //------------------------------------------------- std::string natural_keyboard::unicode_to_string(char32_t ch) const { std::string buffer; switch (ch) { // check some magic values case '\0': buffer.assign("\\0"); break; case '\r': buffer.assign("\\r"); break; case '\n': buffer.assign("\\n"); break; case '\t': buffer.assign("\\t"); break; default: // seven bit ASCII is easy if (ch >= 32 && ch < 128) { char temp[2] = { char(ch), 0 }; buffer.assign(temp); } else if (ch >= UCHAR_MAMEKEY_BEGIN) { // try to obtain a codename with code_name(); this can result in an empty string input_code code(DEVICE_CLASS_KEYBOARD, 0, ITEM_CLASS_SWITCH, ITEM_MODIFIER_NONE, input_item_id(ch - UCHAR_MAMEKEY_BEGIN)); buffer = machine().input().code_name(code); } // did we fail to resolve? if so, we have a last resort if (buffer.empty()) buffer = string_format("U+%04X", unsigned(ch)); break; } return buffer; } //------------------------------------------------- // find_code - find a code in our lookup table //------------------------------------------------- const natural_keyboard::keycode_map_entry *natural_keyboard::find_code(char32_t ch) const { keycode_map::const_iterator const found(m_keycode_map.find(ch)); return (m_keycode_map.end() != found) ? &found->second : nullptr; } //------------------------------------------------- // dump - dumps info to stream //------------------------------------------------- void natural_keyboard::dump(std::ostream &str) const { constexpr size_t left_column_width = 24; // loop through all codes bool first(true); for (auto &code : m_keycode_map) { // describe the character code std::string const description(string_format("%08X (%s) ", code.first, unicode_to_string(code.first))); // pad with spaces util::stream_format(str, "%-*s", left_column_width, description); // identify the keys used for (std::size_t field = 0; (ARRAY_LENGTH(code.second.field) > field) && code.second.field[field]; ++field) util::stream_format(str, "%s'%s'", first ? "" : ", ", code.second.field[field]->name()); // carriage return str << '\n'; first = false; } } //------------------------------------------------- // dump - dumps info to string //------------------------------------------------- std::string natural_keyboard::dump() const { std::ostringstream buffer; dump(buffer); return buffer.str(); } /*************************************************************************** MISCELLANEOUS ***************************************************************************/ //------------------------------------------------- // find - look up information about a particular // character //------------------------------------------------- const char_info *char_info::find(char32_t target) { // perform a simple binary search to find the proper alternate int low = 0; int high = ARRAY_LENGTH(charinfo); while (high > low) { int middle = (high + low) / 2; char32_t ch = charinfo[middle].ch; if (ch < target) low = middle + 1; else if (ch > target) high = middle; else return &charinfo[middle]; } return nullptr; } //------------------------------------------------- // validate_natural_keyboard_statics - // validates natural keyboard static data //------------------------------------------------- /* bool validate_natural_keyboard_statics(void) { int i; bool error = false; char32_t last_char = 0; const char_info *ci; // check to make sure that charinfo is in order for (i = 0; i < ARRAY_LENGTH(charinfo); i++) { if (last_char >= charinfo[i].ch) { osd_printf_error("inputx: charinfo is out of order; 0x%08x should be higher than 0x%08x\n", charinfo[i].ch, last_char); error = true; } last_char = charinfo[i].ch; } // check to make sure that I can look up everything on alternate_charmap for (i = 0; i < ARRAY_LENGTH(charinfo); i++) { ci = char_info::find(charinfo[i].ch); if (ci != &charinfo[i]) { osd_printf_error("ioport: expected char_info::find(0x%08x) to work properly\n", charinfo[i].ch); error = true; } } return error; } */