// For licensing and usage information, read docs/winui_license.txt // MASTER //**************************************************************************** /*************************************************************************** emu_opts.cpp Interface to MAME's options and ini files. ***************************************************************************/ // standard windows headers #include #include // standard C headers #include // MAME/MAMEUI headers #include "emu.h" #include "winmain.h" #include "ui/moptions.h" #include "drivenum.h" #include "emu_opts.h" static emu_options mameopts; // core options static ui_options emu_ui; // ui.ini static windows_options emu_global; // Global 'default' options #define UI_FILENAME "ini\\ui.ini" typedef std::string string; // char names void emu_set_value(windows_options *o, const char* name, float value) { std::ostringstream ss; ss << value; string svalue(ss.str()); string sname = string(name); o->set_value(sname, svalue, OPTION_PRIORITY_CMDLINE); } void emu_set_value(windows_options *o, const char* name, int value) { string svalue = std::to_string(value); string sname = string(name); o->set_value(sname, svalue, OPTION_PRIORITY_CMDLINE); } void emu_set_value(windows_options *o, const char* name, string value) { string sname = string(name); o->set_value(sname, value, OPTION_PRIORITY_CMDLINE); } // string names void emu_set_value(windows_options *o, string name, float value) { std::ostringstream ss; ss << value; string svalue(ss.str()); o->set_value(name, svalue, OPTION_PRIORITY_CMDLINE); } void emu_set_value(windows_options *o, string name, int value) { string svalue = std::to_string(value); o->set_value(name, svalue, OPTION_PRIORITY_CMDLINE); } void emu_set_value(windows_options *o, string name, string value) { o->set_value(name, value, OPTION_PRIORITY_CMDLINE); } // char names void emu_set_value(windows_options &o, const char* name, float value) { std::ostringstream ss; ss << value; string svalue(ss.str()); string sname = string(name); o.set_value(sname, svalue, OPTION_PRIORITY_CMDLINE); } void emu_set_value(windows_options &o, const char* name, int value) { string svalue = std::to_string(value); string sname = string(name); o.set_value(sname, svalue, OPTION_PRIORITY_CMDLINE); } void emu_set_value(windows_options &o, const char* name, string value) { string sname = string(name); o.set_value(sname, value, OPTION_PRIORITY_CMDLINE); } // string names void emu_set_value(windows_options &o, string name, float value) { std::ostringstream ss; ss << value; string svalue(ss.str()); o.set_value(name, svalue, OPTION_PRIORITY_CMDLINE); } void emu_set_value(windows_options &o, string name, int value) { string svalue = std::to_string(value); o.set_value(name, svalue, OPTION_PRIORITY_CMDLINE); } void emu_set_value(windows_options &o, string name, string value) { o.set_value(name, value, OPTION_PRIORITY_CMDLINE); } void ui_set_value(ui_options &o, string name, string value) { o.set_value(name, value, OPTION_PRIORITY_CMDLINE); } string emu_get_value(windows_options *o, string name) { const char* t = o->value(name.c_str()); if (t) return string(o->value(name.c_str())); else return ""; } string emu_get_value(windows_options &o, string name) { const char* t = o.value(name.c_str()); if (t) return string(o.value(name.c_str())); else return ""; } string ui_get_value(ui_options &o, string name) { const char* t = o.value(name.c_str()); if (t) return string(o.value(name.c_str())); else return ""; } struct dir_data { string dir_path; int which; }; static std::map dir_map; static string emu_path; string GetIniDir(void) { /// const char *ini_dir; // const char *s; // ini_dir = global.value(OPTION_INIPATH); // while((s = strchr(ini_dir, ';')) != NULL) // { // ini_dir = s + 1; // } /// ini_dir = "ini\0"; /// return ini_dir; return emu_path + "ini\0"; } // load mewui settings static void LoadSettingsFile(ui_options &opts, const char *filename) { osd_file::error filerr; util::core_file::ptr file; filerr = util::core_file::open(filename, OPEN_FLAG_READ, file); if (filerr == osd_file::error::NONE) { opts.parse_ini_file(*file, OPTION_PRIORITY_CMDLINE, true, true); file.reset(); } } // load a game ini static void LoadSettingsFile(windows_options &opts, const char *filename) { osd_file::error filerr; util::core_file::ptr file; filerr = util::core_file::open(filename, OPEN_FLAG_READ, file); if (filerr == osd_file::error::NONE) { opts.parse_ini_file(*file, OPTION_PRIORITY_CMDLINE, true, true); file.reset(); } } // This saves changes to .INI or MAME.INI only static void SaveSettingsFile(windows_options &opts, const char *filename) { osd_file::error filerr = osd_file::error::NONE; util::core_file::ptr file; filerr = util::core_file::open(filename, OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS, file); if (filerr == osd_file::error::NONE) { string inistring = opts.output_ini(); // printf("=====%s=====\n%s\n",filename,inistring.c_str()); // for debugging file->puts(inistring.c_str()); file.reset(); } } /* get options, based on passed in game number. */ void load_options(windows_options &opts, OPTIONS_TYPE opt_type, int game_num, bool set_system_name) { const game_driver *driver = NULL; if (game_num > -1) driver = &driver_list::driver(game_num); // Try base ini first string fname = string(emulator_info::get_configname()).append(".ini"); LoadSettingsFile(opts, fname.c_str()); if (opt_type == OPTIONS_SOURCE) { fname = GetIniDir() + PATH_SEPARATOR + "source" + PATH_SEPARATOR + core_filename_extract_base(driver->type.source(), true) + ".ini"; LoadSettingsFile(opts, fname.c_str()); return; } fname.clear(); if (opt_type == OPTIONS_COMPUTER) fname = GetIniDir() + PATH_SEPARATOR + "computer.ini"; else if (opt_type == OPTIONS_CONSOLE) fname = GetIniDir() + PATH_SEPARATOR + "console.ini"; else if (opt_type == OPTIONS_HORIZONTAL) fname = GetIniDir() + PATH_SEPARATOR + "horizontal.ini"; else if (opt_type == OPTIONS_RASTER) fname = GetIniDir() + PATH_SEPARATOR + "raster.ini"; else if (opt_type == OPTIONS_VECTOR) fname = GetIniDir() + PATH_SEPARATOR + "vector.ini"; else if (opt_type == OPTIONS_VERTICAL) fname = GetIniDir() + PATH_SEPARATOR + "vertical.ini"; if (!fname.empty()) { LoadSettingsFile(opts, fname.c_str()); return; } if (game_num > -2) { // Now try global ini fname = GetIniDir() + PATH_SEPARATOR + string(emulator_info::get_configname()).append(".ini"); LoadSettingsFile(opts, fname.c_str()); if (game_num > -1) { // Lastly, gamename.ini if (driver) { fname = GetIniDir() + PATH_SEPARATOR + string(driver->name).append(".ini"); if (set_system_name) opts.set_value(OPTION_SYSTEMNAME, driver->name, OPTION_PRIORITY_CMDLINE); LoadSettingsFile(opts, fname.c_str()); } } } if (game_num > -1) SetDirectories(opts); } /* Save ini file based on game_number. */ void save_options(windows_options &opts, OPTIONS_TYPE opt_type, int game_num) { const game_driver *driver = NULL; string fname, filepath; if (opt_type == OPTIONS_COMPUTER) fname = GetIniDir() + PATH_SEPARATOR + "computer.ini"; else if (opt_type == OPTIONS_CONSOLE) fname = GetIniDir() + PATH_SEPARATOR + "console.ini"; else if (opt_type == OPTIONS_HORIZONTAL) fname = GetIniDir() + PATH_SEPARATOR + "horizontal.ini"; else if (opt_type == OPTIONS_RASTER) fname = GetIniDir() + PATH_SEPARATOR + "raster.ini"; else if (opt_type == OPTIONS_VECTOR) fname = GetIniDir() + PATH_SEPARATOR + "vector.ini"; else if (opt_type == OPTIONS_VERTICAL) fname = GetIniDir() + PATH_SEPARATOR + "vertical.ini"; if (!fname.empty()) { SaveSettingsFile(opts, fname.c_str()); return; } if (game_num >= 0) { driver = &driver_list::driver(game_num); if (driver) { fname.assign(driver->name); if (opt_type == OPTIONS_SOURCE) filepath = GetIniDir() + PATH_SEPARATOR + "source" + PATH_SEPARATOR + core_filename_extract_base(driver->type.source(), true) + ".ini"; } } else if (game_num == -1) fname = string(emulator_info::get_configname()); if (!fname.empty() && filepath.empty()) filepath = GetIniDir().append(PATH_SEPARATOR).append(fname.c_str()).append(".ini"); if (game_num == -2) filepath = string(emulator_info::get_configname()).append(".ini"); if (!filepath.empty()) { if (game_num > -1) SetDirectories(opts); SaveSettingsFile(opts, filepath.c_str()); // printf("Settings saved to %s\n",filepath.c_str()); } // else // printf("Unable to save settings\n"); } void emu_opts_init(bool b) { printf("emuOptsInit: About to load %s\n",UI_FILENAME);fflush(stdout); LoadSettingsFile(emu_ui, UI_FILENAME); // parse UI.INI printf("emuOptsInit: About to load Global Options\n");fflush(stdout); load_options(emu_global, OPTIONS_GLOBAL, -1, 0); // parse MAME.INI printf("emuOptsInit: Finished\n");fflush(stdout); if (b) return; char exe_path[MAX_PATH]; GetModuleFileNameA(nullptr, exe_path, MAX_PATH); emu_path = string(exe_path); std::size_t pos = emu_path.find_last_of("\\"); emu_path = emu_path.substr(0,++pos); emu_path.resize(pos); printf("%s\n",emu_path.c_str()); dir_map[1] = dir_data { OPTION_HOMEPATH, 0 }; dir_map[2] = dir_data { OPTION_MEDIAPATH, 0 }; dir_map[3] = dir_data { OPTION_HASHPATH, 0 }; dir_map[4] = dir_data { OPTION_SAMPLEPATH, 0 }; dir_map[5] = dir_data { OPTION_ARTPATH, 0 }; dir_map[6] = dir_data { OPTION_CTRLRPATH, 0 }; dir_map[7] = dir_data { OPTION_INIPATH, 0 }; dir_map[8] = dir_data { OPTION_FONTPATH, 0 }; dir_map[9] = dir_data { OPTION_CHEATPATH, 0 }; dir_map[10] = dir_data { OPTION_CROSSHAIRPATH, 0 }; dir_map[11] = dir_data { OPTION_PLUGINSPATH, 0 }; dir_map[12] = dir_data { OPTION_LANGUAGEPATH, 0 }; dir_map[13] = dir_data { OPTION_SWPATH, 0 }; dir_map[14] = dir_data { OPTION_CFG_DIRECTORY, 0 }; dir_map[15] = dir_data { OPTION_NVRAM_DIRECTORY, 0 }; dir_map[16] = dir_data { OPTION_INPUT_DIRECTORY, 0 }; dir_map[17] = dir_data { OPTION_STATE_DIRECTORY, 0 }; dir_map[18] = dir_data { OPTION_SNAPSHOT_DIRECTORY, 0 }; dir_map[19] = dir_data { OPTION_DIFF_DIRECTORY, 0 }; dir_map[20] = dir_data { OPTION_COMMENT_DIRECTORY, 0 }; dir_map[21] = dir_data { OSDOPTION_BGFX_PATH, 0 }; dir_map[22] = dir_data { WINOPTION_HLSLPATH, 0 }; dir_map[23] = dir_data { OPTION_HISTORY_PATH, 1 }; dir_map[24] = dir_data { OPTION_CATEGORYINI_PATH, 1 }; dir_map[25] = dir_data { OPTION_CABINETS_PATH, 1 }; dir_map[26] = dir_data { OPTION_CPANELS_PATH, 1 }; dir_map[27] = dir_data { OPTION_PCBS_PATH, 1 }; dir_map[28] = dir_data { OPTION_FLYERS_PATH, 1 }; dir_map[29] = dir_data { OPTION_TITLES_PATH, 1 }; dir_map[30] = dir_data { OPTION_ENDS_PATH, 1 }; dir_map[31] = dir_data { OPTION_MARQUEES_PATH, 1 }; dir_map[32] = dir_data { OPTION_ARTPREV_PATH, 1 }; dir_map[33] = dir_data { OPTION_BOSSES_PATH, 1 }; dir_map[34] = dir_data { OPTION_LOGOS_PATH, 1 }; dir_map[35] = dir_data { OPTION_SCORES_PATH, 1 }; dir_map[36] = dir_data { OPTION_VERSUS_PATH, 1 }; dir_map[37] = dir_data { OPTION_GAMEOVER_PATH, 1 }; dir_map[38] = dir_data { OPTION_HOWTO_PATH, 1 }; dir_map[39] = dir_data { OPTION_SELECT_PATH, 1 }; dir_map[40] = dir_data { OPTION_ICONS_PATH, 1 }; dir_map[41] = dir_data { OPTION_COVER_PATH, 1 }; dir_map[42] = dir_data { OPTION_UI_PATH, 1 }; } void dir_set_value(int dir_index, string value) { if (dir_index) { if (dir_map.count(dir_index) > 0) { string sname = dir_map[dir_index].dir_path; int which = dir_map[dir_index].which; if (which) ui_set_value(emu_ui, sname, value); else emu_set_value(emu_global, sname, value); } } } string dir_get_value(int dir_index) { if (dir_index) { if (dir_map.count(dir_index) > 0) { string sname = dir_map[dir_index].dir_path; int which = dir_map[dir_index].which; if (which) return ui_get_value(emu_ui, sname); else return emu_get_value(emu_global, sname); } } return ""; } // This saves changes to UI.INI only static void SaveSettingsFile(ui_options &opts, const char *filename) { osd_file::error filerr = osd_file::error::NONE; util::core_file::ptr file; filerr = util::core_file::open(filename, OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS, file); if (filerr == osd_file::error::NONE) { string inistring = opts.output_ini(); file->puts(inistring.c_str()); file.reset(); } } void ui_save_ini() { SaveSettingsFile(emu_ui, UI_FILENAME); } void SetDirectories(windows_options &o) { emu_set_value(o, OPTION_MEDIAPATH, dir_get_value(2)); emu_set_value(o, OPTION_SAMPLEPATH, dir_get_value(4)); emu_set_value(o, OPTION_INIPATH, dir_get_value(7)); emu_set_value(o, OPTION_CFG_DIRECTORY, dir_get_value(14)); emu_set_value(o, OPTION_SNAPSHOT_DIRECTORY, dir_get_value(18)); emu_set_value(o, OPTION_INPUT_DIRECTORY, dir_get_value(16)); emu_set_value(o, OPTION_STATE_DIRECTORY, dir_get_value(17)); emu_set_value(o, OPTION_ARTPATH, dir_get_value(5)); emu_set_value(o, OPTION_NVRAM_DIRECTORY, dir_get_value(15)); emu_set_value(o, OPTION_CTRLRPATH, dir_get_value(6)); emu_set_value(o, OPTION_CHEATPATH, dir_get_value(9)); emu_set_value(o, OPTION_CROSSHAIRPATH, dir_get_value(10)); emu_set_value(o, OPTION_FONTPATH, dir_get_value(8)); emu_set_value(o, OPTION_DIFF_DIRECTORY, dir_get_value(19)); emu_set_value(o, OPTION_SNAPNAME, emu_get_value(emu_global, OPTION_SNAPNAME)); emu_set_value(o, OPTION_DEBUG, "0"); emu_set_value(o, OPTION_SPEAKER_REPORT, "0"); emu_set_value(o, OPTION_VERBOSE, "0"); } // For dialogs.cpp const char* GetSnapName(void) { return emu_global.value(OPTION_SNAPNAME); } void SetSnapName(const char* value) { string nvalue = value ? string(value) : ""; emu_set_value(emu_global, OPTION_SNAPNAME, nvalue); global_save_ini(); } // For winui.cpp const string GetLanguageUI(void) { return emu_global.value(OPTION_LANGUAGE); } bool GetEnablePlugins(void) { return emu_global.bool_value(OPTION_PLUGINS); } const string GetPlugins(void) { return emu_global.value(OPTION_PLUGIN); } bool GetSkipWarnings(void) { return emu_ui.bool_value(OPTION_SKIP_WARNINGS); } void SetSkipWarnings(BOOL val) { string c = val ? "1" : "0"; ui_set_value(emu_ui, OPTION_SKIP_WARNINGS, c); } void SetSelectedSoftware(int driver_index, string opt_name, const char *software) { if (opt_name.empty()) { // Software List Item, we write to SOFTWARENAME to ensure all parts of a multipart set are loaded windows_options o; printf("About to write %s to OPTION_SOFTWARENAME\n",software);fflush(stdout); load_options(o, OPTIONS_GAME, driver_index, 1); o.set_value(OPTION_SOFTWARENAME, software, OPTION_PRIORITY_CMDLINE); save_options(o, OPTIONS_GAME, driver_index); } else { // Loose software, we write the filename to the requested image device const char *s = opt_name.c_str(); printf("SetSelectedSoftware(): slot=%s driver=%s software='%s'\n", s, driver_list::driver(driver_index).name, software); printf("About to load %s into slot %s\n",software,s);fflush(stdout); windows_options o; load_options(o, OPTIONS_GAME, driver_index, 1); o.set_value(s, software, OPTION_PRIORITY_CMDLINE); //o.image_option(opt_name).specify(software); printf("Done\n");;fflush(stdout); save_options(o, OPTIONS_GAME, driver_index); } } // See if this driver has software support bool DriverHasSoftware(uint32_t drvindex) { if (drvindex < driver_list::total()) { windows_options o; load_options(o, OPTIONS_GAME, drvindex, 1); machine_config config(driver_list::driver(drvindex), o); for (device_image_interface &img : image_interface_enumerator(config.root_device())) if (img.user_loadable()) return 1; } return 0; } void global_save_ini(void) { string fname = GetIniDir() + PATH_SEPARATOR + string(emulator_info::get_configname()).append(".ini"); SaveSettingsFile(emu_global, fname.c_str()); } bool AreOptionsEqual(windows_options &opts1, windows_options &opts2) { for (auto &curentry : opts1.entries()) { if (curentry->type() != OPTION_HEADER) { const char *value = curentry->value(); const char *comp = opts2.value(curentry->name().c_str()); if (!value && !comp) // both empty, they are the same {} else if (!value || !comp) // only one empty, they are different return false; else if (strcmp(value, comp) != 0) // both not empty, do proper compare return false; } } return true; } void OptionsCopy(windows_options &source, windows_options &dest) { for (auto &dest_entry : source.entries()) { if (dest_entry->names().size() > 0) { // identify the source entry const core_options::entry::shared_ptr source_entry = source.get_entry(dest_entry->name()); if (source_entry) { const char *value = source_entry->value(); if (value) dest_entry->set_value(value, source_entry->priority(), true); } } } } // Reset the given windows_options to their default settings. static void ResetToDefaults(windows_options &opts, int priority) { // iterate through the options setting each one back to the default value. windows_options dummy; OptionsCopy(dummy, opts); } void ResetGameOptions(int driver_index) { //save_options(NULL, OPTIONS_GAME, driver_index); } void ResetGameDefaults(void) { // Walk the global settings and reset everything to defaults; ResetToDefaults(emu_global, OPTION_PRIORITY_CMDLINE); save_options(emu_global, OPTIONS_GLOBAL, GLOBAL_OPTIONS); } /* * Reset all game, vector and source options to defaults. * No reason to reboot if this is done. */ void ResetAllGameOptions(void) { for (int i = 0; i < driver_list::total(); i++) ResetGameOptions(i); } windows_options & MameUIGlobal(void) { return emu_global; } void SetSystemName(windows_options &opts, OPTIONS_TYPE opt_type, int driver_index) { if (driver_index >= 0) mameopts.set_system_name(driver_list::driver(driver_index).name); } a> 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
// license:BSD-3-Clause
// copyright-holders:Andrew Gardner
#define NO_MEM_TRACKING

#include "mainwindow.h"

#include "debug/debugcon.h"
#include "debug/debugcpu.h"
#include "debug/dvdisasm.h"


MainWindow::MainWindow(running_machine* machine, QWidget* parent) :
	WindowQt(machine, NULL),
	m_historyIndex(0),
	m_inputHistory()
{
	setGeometry(300, 300, 1000, 600);

	//
	// The main frame and its input and log widgets
	//
	QFrame* mainWindowFrame = new QFrame(this);

	// The input line
	m_inputEdit = new QLineEdit(mainWindowFrame);
	connect(m_inputEdit, SIGNAL(returnPressed()), this, SLOT(executeCommand()));
	m_inputEdit->installEventFilter(this);


	// The log view
	m_consoleView = new DebuggerView(DVT_CONSOLE,
										m_machine,
										mainWindowFrame);
	m_consoleView->setFocusPolicy(Qt::NoFocus);
	m_consoleView->setPreferBottom(true);

	QVBoxLayout* vLayout = new QVBoxLayout(mainWindowFrame);
	vLayout->addWidget(m_consoleView);
	vLayout->addWidget(m_inputEdit);
	vLayout->setSpacing(3);
	vLayout->setContentsMargins(4,0,4,2);

	setCentralWidget(mainWindowFrame);

	//
	// Options Menu
	//
	// Create three commands
	m_breakpointToggleAct = new QAction("Toggle Breakpoint at Cursor", this);
	m_breakpointEnableAct = new QAction("Disable Breakpoint at Cursor", this);
	m_runToCursorAct = new QAction("Run to Cursor", this);
	m_breakpointToggleAct->setShortcut(Qt::Key_F9);
	m_breakpointEnableAct->setShortcut(Qt::SHIFT + Qt::Key_F9);
	m_runToCursorAct->setShortcut(Qt::Key_F4);
	connect(m_breakpointToggleAct, SIGNAL(triggered(bool)), this, SLOT(toggleBreakpointAtCursor(bool)));
	connect(m_breakpointEnableAct, SIGNAL(triggered(bool)), this, SLOT(enableBreakpointAtCursor(bool)));
	connect(m_runToCursorAct, SIGNAL(triggered(bool)), this, SLOT(runToCursor(bool)));

	// Right bar options
	QActionGroup* rightBarGroup = new QActionGroup(this);
	rightBarGroup->setObjectName("rightbargroup");
	QAction* rightActRaw = new QAction("Raw Opcodes", this);
	QAction* rightActEncrypted = new QAction("Encrypted Opcodes", this);
	QAction* rightActComments = new QAction("Comments", this);
	rightActRaw->setCheckable(true);
	rightActEncrypted->setCheckable(true);
	rightActComments->setCheckable(true);
	rightActRaw->setActionGroup(rightBarGroup);
	rightActEncrypted->setActionGroup(rightBarGroup);
	rightActComments->setActionGroup(rightBarGroup);
	rightActRaw->setShortcut(QKeySequence("Ctrl+R"));
	rightActEncrypted->setShortcut(QKeySequence("Ctrl+E"));
	rightActComments->setShortcut(QKeySequence("Ctrl+C"));
	rightActRaw->setChecked(true);
	connect(rightBarGroup, SIGNAL(triggered(QAction*)), this, SLOT(rightBarChanged(QAction*)));

	// Assemble the options menu
	QMenu* optionsMenu = menuBar()->addMenu("&Options");
	optionsMenu->addAction(m_breakpointToggleAct);
	optionsMenu->addAction(m_breakpointEnableAct);
	optionsMenu->addAction(m_runToCursorAct);
	optionsMenu->addSeparator();
	optionsMenu->addActions(rightBarGroup->actions());

	//
	// Images menu
	//
	image_interface_iterator imageIterTest(m_machine->root_device());
	if (imageIterTest.first() != NULL)
	{
		createImagesMenu();
	}

	//
	// Dock window menu
	//
	QMenu* dockMenu = menuBar()->addMenu("Doc&ks");

	setCorner(Qt::TopRightCorner, Qt::TopDockWidgetArea);
	setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);

	// The processor dock
	QDockWidget* cpuDock = new QDockWidget("processor", this);
	cpuDock->setObjectName("cpudock");
	cpuDock->setAllowedAreas(Qt::LeftDockWidgetArea);
	m_procFrame = new ProcessorDockWidget(m_machine, cpuDock);
	cpuDock->setWidget(dynamic_cast<QWidget*>(m_procFrame));

	addDockWidget(Qt::LeftDockWidgetArea, cpuDock);
	dockMenu->addAction(cpuDock->toggleViewAction());

	// The disassembly dock
	QDockWidget* dasmDock = new QDockWidget("dasm", this);
	dasmDock->setObjectName("dasmdock");
	dasmDock->setAllowedAreas(Qt::TopDockWidgetArea);
	m_dasmFrame = new DasmDockWidget(m_machine, dasmDock);
	dasmDock->setWidget(m_dasmFrame);
	connect(m_dasmFrame->view(), SIGNAL(updated()), this, SLOT(dasmViewUpdated()));

	addDockWidget(Qt::TopDockWidgetArea, dasmDock);
	dockMenu->addAction(dasmDock->toggleViewAction());
}


MainWindow::~MainWindow()
{
}


void MainWindow::setProcessor(device_t* processor)
{
	// Cpu swap
	m_procFrame->view()->view()->set_source(*m_procFrame->view()->view()->source_for_device(processor));
	m_dasmFrame->view()->view()->set_source(*m_dasmFrame->view()->view()->source_for_device(processor));

	// Scrollbar refresh - seems I should be able to do in the DebuggerView
	m_dasmFrame->view()->verticalScrollBar()->setValue(m_dasmFrame->view()->view()->visible_position().y);
	m_dasmFrame->view()->verticalScrollBar()->setValue(m_dasmFrame->view()->view()->visible_position().y);

	// Window title
	std::string title;
	strprintf(title,"Debug: %s - %s '%s'", m_machine->system().name, processor->name(), processor->tag());
	setWindowTitle(title.c_str());
}


// Used to intercept the user clicking 'X' in the upper corner
void MainWindow::closeEvent(QCloseEvent* event)
{
	debugActQuit();

	// Insure the window doesn't disappear before we get a chance to save its parameters
	event->ignore();
}


// Used to intercept the user hitting the up arrow in the input widget
bool MainWindow::eventFilter(QObject* obj, QEvent* event)
{
	// Only filter keypresses
	QKeyEvent* keyEvent = NULL;
	if (event->type() == QEvent::KeyPress)
	{
		keyEvent = static_cast<QKeyEvent*>(event);
	}
	else
	{
		return QObject::eventFilter(obj, event);
	}

	// Catch up & down keys
	if (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)
	{
		if (keyEvent->key() == Qt::Key_Up)
		{
			if (m_historyIndex > 0)
				m_historyIndex--;
		}
		else if (keyEvent->key() == Qt::Key_Down)
		{
			if (m_historyIndex < m_inputHistory.size())
				m_historyIndex++;
		}

		// Populate the input edit or clear it if you're at the end
		if (m_historyIndex == m_inputHistory.size())
		{
			m_inputEdit->setText("");
		}
		else
		{
			m_inputEdit->setText(m_inputHistory[m_historyIndex]);
		}
	}
	else if (keyEvent->key() == Qt::Key_Enter)
	{
		executeCommand(false);
	}
	else
	{
		return QObject::eventFilter(obj, event);
	}

	return true;
}


void MainWindow::toggleBreakpointAtCursor(bool changedTo)
{
	debug_view_disasm *const dasmView = downcast<debug_view_disasm*>(m_dasmFrame->view()->view());
	if (dasmView->cursor_visible() && (debug_cpu_get_visible_cpu(*m_machine) == dasmView->source()->device()))
	{
		offs_t const address = downcast<debug_view_disasm *>(dasmView)->selected_address();
		device_debug *const cpuinfo = dasmView->source()->device()->debug();

		// Find an existing breakpoint at this address
		INT32 bpindex = -1;
		for (device_debug::breakpoint* bp = cpuinfo->breakpoint_first();
				bp != NULL;
				bp = bp->next())
		{
			if (address == bp->address())
			{
				bpindex = bp->index();
				break;
			}
		}

		// If none exists, add a new one
		std::string command;
		if (bpindex == -1)
		{
			strprintf(command,"bpset 0x%X", address);
		}
		else
		{
			strprintf(command,"bpclear 0x%X", bpindex);
		}
		debug_console_execute_command(*m_machine, command.c_str(), 1);
	}

	refreshAll();
}


void MainWindow::enableBreakpointAtCursor(bool changedTo)
{
	debug_view_disasm *const dasmView = downcast<debug_view_disasm*>(m_dasmFrame->view()->view());
	if (dasmView->cursor_visible() && (debug_cpu_get_visible_cpu(*m_machine) == dasmView->source()->device()))
	{
		offs_t const address = dasmView->selected_address();
		device_debug *const cpuinfo = dasmView->source()->device()->debug();

		// Find an existing breakpoint at this address
		device_debug::breakpoint* bp = cpuinfo->breakpoint_first();
		while ((bp != NULL) && (bp->address() != address))
			bp = bp->next();

		if (bp != NULL)
		{
			INT32 const bpindex = bp->index();
			std::string command;
			strprintf(command,bp->enabled() ? "bpdisable 0x%X" : "bpenable 0x%X", bpindex);
			debug_console_execute_command(*m_machine, command.c_str(), 1);
		}
	}

	refreshAll();
}


void MainWindow::runToCursor(bool changedTo)
{
	debug_view_disasm* dasmView = downcast<debug_view_disasm*>(m_dasmFrame->view()->view());
	if (dasmView->cursor_visible() && (debug_cpu_get_visible_cpu(*m_machine) == dasmView->source()->device()))
	{
		offs_t address = downcast<debug_view_disasm*>(dasmView)->selected_address();
		std::string command;
		strprintf(command,"go 0x%X", address);
		debug_console_execute_command(*m_machine, command.c_str(), 1);
	}
}


void MainWindow::rightBarChanged(QAction* changedTo)
{
	debug_view_disasm* dasmView = downcast<debug_view_disasm*>(m_dasmFrame->view()->view());
	if (changedTo->text() == "Raw Opcodes")
	{
		dasmView->set_right_column(DASM_RIGHTCOL_RAW);
	}
	else if (changedTo->text() == "Encrypted Opcodes")
	{
		dasmView->set_right_column(DASM_RIGHTCOL_ENCRYPTED);
	}
	else if (changedTo->text() == "Comments")
	{
		dasmView->set_right_column(DASM_RIGHTCOL_COMMENTS);
	}
	m_dasmFrame->view()->viewport()->update();
}


void MainWindow::executeCommand(bool withClear)
{
	QString command = m_inputEdit->text();

	// A blank command is a "silent step"
	if (command == "")
	{
		debug_cpu_get_visible_cpu(*m_machine)->debug()->single_step();
		return;
	}

	// Send along the command
	debug_console_execute_command(*m_machine,
									command.toLocal8Bit().data(),
									true);

	// Add history & set the index to be the top of the stack
	addToHistory(command);

	// Clear out the text and reset the history pointer only if asked
	if (withClear)
	{
		m_inputEdit->clear();
		m_historyIndex = m_inputHistory.size();
	}

	// Refresh
	m_consoleView->viewport()->update();
	refreshAll();
}


void MainWindow::mountImage(bool changedTo)
{
	// The image interface index was assigned to the QAction's data memeber
	const int imageIndex = dynamic_cast<QAction*>(sender())->data().toInt();
	image_interface_iterator iter(m_machine->root_device());
	device_image_interface *img = iter.byindex(imageIndex);
	if (img == NULL)
	{
		debug_console_printf(*m_machine, "Something is wrong with the mount menu.\n");
		refreshAll();
		return;
	}

	// File dialog
	QString filename = QFileDialog::getOpenFileName(this,
													"Select an image file",
													QDir::currentPath(),
													tr("All files (*.*)"));

	if (img->load(filename.toUtf8().data()) != IMAGE_INIT_PASS)
	{
		debug_console_printf(*m_machine, "Image could not be mounted.\n");
		refreshAll();
		return;
	}

	// Activate the unmount menu option
	QAction* unmountAct = sender()->parent()->findChild<QAction*>("unmount");
	unmountAct->setEnabled(true);

	// Set the mount name
	QMenu* parentMenuItem = dynamic_cast<QMenu*>(sender()->parent());
	QString baseString = parentMenuItem->title();
	baseString.truncate(baseString.lastIndexOf(QString(" : ")));
	const QString newTitle = baseString + QString(" : ") + QString(img->filename());
	parentMenuItem->setTitle(newTitle);

	debug_console_printf(*m_machine, "Image %s mounted successfully.\n", filename.toUtf8().data());
	refreshAll();
}


void MainWindow::unmountImage(bool changedTo)
{
	// The image interface index was assigned to the QAction's data memeber
	const int imageIndex = dynamic_cast<QAction*>(sender())->data().toInt();
	image_interface_iterator iter(m_machine->root_device());
	device_image_interface *img = iter.byindex(imageIndex);

	img->unload();

	// Deactivate the unmount menu option
	dynamic_cast<QAction*>(sender())->setEnabled(false);

	// Set the mount name
	QMenu* parentMenuItem = dynamic_cast<QMenu*>(sender()->parent());
	QString baseString = parentMenuItem->title();
	baseString.truncate(baseString.lastIndexOf(QString(" : ")));
	const QString newTitle = baseString + QString(" : ") + QString("[empty slot]");
	parentMenuItem->setTitle(newTitle);

	debug_console_printf(*m_machine, "Image successfully unmounted.\n");
	refreshAll();
}


void MainWindow::dasmViewUpdated()
{
	debug_view_disasm *const dasmView = downcast<debug_view_disasm*>(m_dasmFrame->view()->view());
	bool const haveCursor = dasmView->cursor_visible() && (debug_cpu_get_visible_cpu(*m_machine) == dasmView->source()->device());
	bool haveBreakpoint = false;
	bool breakpointEnabled = false;
	if (haveCursor)
	{
		offs_t const address = dasmView->selected_address();
		device_t *const device = dasmView->source()->device();
		device_debug *const cpuinfo = device->debug();

		// Find an existing breakpoint at this address
		device_debug::breakpoint* bp = cpuinfo->breakpoint_first();
		while ((bp != NULL) && (bp->address() != address))
			bp = bp->next();

		if (bp != NULL)
		{
			haveBreakpoint = true;
			breakpointEnabled = bp->enabled();
		}
	}

	m_breakpointToggleAct->setText(haveBreakpoint ? "Clear Breakpoint at Cursor" : haveCursor ? "Set Breakpoint at Cursor" : "Toggle Breakpoint at Cursor");
	m_breakpointEnableAct->setText((!haveBreakpoint || breakpointEnabled) ? "Disable Breakpoint at Cursor" : "Enable Breakpoint at Cursor");
	m_breakpointToggleAct->setEnabled(haveCursor);
	m_breakpointEnableAct->setEnabled(haveBreakpoint);
	m_runToCursorAct->setEnabled(haveCursor);
}


void MainWindow::debugActClose()
{
	m_machine->schedule_exit();
}


void MainWindow::addToHistory(const QString& command)
{
	if (command == "")
		return;

	// Always push back when there is no previous history
	if (m_inputHistory.size() == 0)
	{
		m_inputHistory.push_back(m_inputEdit->text());
		return;
	}

	// If there is previous history, make sure it's not what you just executed
	if (m_inputHistory.back() != m_inputEdit->text())
	{
		m_inputHistory.push_back(m_inputEdit->text());
	}
}


void MainWindow::createImagesMenu()
{
	QMenu* imagesMenu = menuBar()->addMenu("&Images");

	int interfaceIndex = 0;
	image_interface_iterator iter(m_machine->root_device());
	for (device_image_interface *img = iter.first(); img != NULL; img = iter.next())
	{
		std::string menuName;
		strprintf(menuName,"%s : %s", img->device().name(), img->exists() ? img->filename() : "[empty slot]");

		QMenu* interfaceMenu = imagesMenu->addMenu(menuName.c_str());
		interfaceMenu->setObjectName(img->device().name());

		QAction* mountAct = new QAction("Mount...", interfaceMenu);
		QAction* unmountAct = new QAction("Unmount", interfaceMenu);
		mountAct->setObjectName("mount");
		mountAct->setData(QVariant(interfaceIndex));
		unmountAct->setObjectName("unmount");
		unmountAct->setData(QVariant(interfaceIndex));
		connect(mountAct, SIGNAL(triggered(bool)), this, SLOT(mountImage(bool)));
		connect(unmountAct, SIGNAL(triggered(bool)), this, SLOT(unmountImage(bool)));

		if (!img->exists())
			unmountAct->setEnabled(false);

		interfaceMenu->addAction(mountAct);
		interfaceMenu->addAction(unmountAct);

		// TODO: Cassette operations

		interfaceIndex++;
	}
}


//=========================================================================
//  MainWindowQtConfig
//=========================================================================
void MainWindowQtConfig::buildFromQWidget(QWidget* widget)
{
	WindowQtConfig::buildFromQWidget(widget);
	MainWindow* window = dynamic_cast<MainWindow*>(widget);
	m_windowState = window->saveState();

	QActionGroup* rightBarGroup = window->findChild<QActionGroup*>("rightbargroup");
	if (rightBarGroup->checkedAction()->text() == "Raw Opcodes")
		m_rightBar = 0;
	else if (rightBarGroup->checkedAction()->text() == "Encrypted Opcodes")
		m_rightBar = 1;
	else if (rightBarGroup->checkedAction()->text() == "Comments")
		m_rightBar = 2;
}


void MainWindowQtConfig::applyToQWidget(QWidget* widget)
{
	WindowQtConfig::applyToQWidget(widget);
	MainWindow* window = dynamic_cast<MainWindow*>(widget);
	window->restoreState(m_windowState);

	QActionGroup* rightBarGroup = window->findChild<QActionGroup*>("rightbargroup");
	rightBarGroup->actions()[m_rightBar]->trigger();
}


void MainWindowQtConfig::addToXmlDataNode(xml_data_node* node) const
{
	WindowQtConfig::addToXmlDataNode(node);
	xml_set_attribute_int(node, "rightbar", m_rightBar);
	xml_set_attribute(node, "qtwindowstate", m_windowState.toPercentEncoding().data());
}


void MainWindowQtConfig::recoverFromXmlNode(xml_data_node* node)
{
	WindowQtConfig::recoverFromXmlNode(node);
	const char* state = xml_get_attribute_string(node, "qtwindowstate", "");
	m_windowState = QByteArray::fromPercentEncoding(state);
	m_rightBar = xml_get_attribute_int(node, "rightbar", m_rightBar);
}

DasmDockWidget::~DasmDockWidget()
{
}

ProcessorDockWidget::~ProcessorDockWidget()
{
}