text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185 values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Source file for Unix VM-managers (client-side)
*
*
*
* Authors: Teemu Korhonen
* Cacodemon345
*
*/
#include "qt_unixmanagerfilter.hpp"
UnixManagerSocket::UnixManagerSocket(QObject *obj)
: QLocalSocket(obj)
{
connect(this, &QLocalSocket::readyRead, this, &UnixManagerSocket::readyToRead);
}
void
UnixManagerSocket::readyToRead()
{
if (canReadLine()) {
QByteArray line = readLine();
if (line.size()) {
line.resize(line.size() - 1);
if (line == "showsettings") {
emit showsettings();
} else if (line == "pause") {
emit pause();
} else if (line == "cad") {
emit ctrlaltdel();
} else if (line == "reset") {
emit resetVM();
} else if (line == "shutdownnoprompt") {
emit force_shutdown();
} else if (line == "shutdown") {
emit request_shutdown();
}
}
}
}
bool
UnixManagerSocket::eventFilter(QObject *obj, QEvent *event)
{
if (state() == QLocalSocket::ConnectedState) {
if (event->type() == QEvent::WindowBlocked) {
write(QByteArray { "1" });
} else if (event->type() == QEvent::WindowUnblocked) {
write(QByteArray { "0" });
}
}
return QObject::eventFilter(obj, event);
}
``` | /content/code_sandbox/src/qt/qt_unixmanagerfilter.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 403 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Media menu UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
* Teemu Korhonen
*
*/
#include "qt_progsettings.hpp"
#include "qt_machinestatus.hpp"
#include <QMenu>
#include <QFileDialog>
#include <QMessageBox>
#include <QStringBuilder>
#include <QApplication>
#include <QStyle>
extern "C" {
#ifdef Q_OS_WINDOWS
#define BITMAP WINDOWS_BITMAP
#undef UNICODE
#include <windows.h>
#include <windowsx.h>
#undef BITMAP
#endif
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/config.h>
#include <86box/device.h>
#include <86box/timer.h>
#include <86box/plat.h>
#include <86box/cassette.h>
#include <86box/machine.h>
#include <86box/cartridge.h>
#include <86box/fdd.h>
#include <86box/fdd_86f.h>
#include <86box/cdrom.h>
#include <86box/scsi_device.h>
#include <86box/zip.h>
#include <86box/mo.h>
#include <86box/sound.h>
#include <86box/ui.h>
#include <86box/thread.h>
#include <86box/network.h>
};
#include "qt_newfloppydialog.hpp"
#include "qt_util.hpp"
#include "qt_deviceconfig.hpp"
#include "qt_mediahistorymanager.hpp"
#include "qt_mediamenu.hpp"
std::shared_ptr<MediaMenu> MediaMenu::ptr;
MediaMenu::MediaMenu(QWidget *parent)
: QObject(parent)
{
parentWidget = parent;
connect(this, &MediaMenu::onCdromUpdateUi, this, &MediaMenu::cdromUpdateUi, Qt::QueuedConnection);
}
void
MediaMenu::refresh(QMenu *parentMenu)
{
parentMenu->clear();
if (MachineStatus::hasCassette()) {
cassetteMenu = parentMenu->addMenu("");
cassetteMenu->addAction(tr("&New image..."), [this]() { cassetteNewImage(); });
cassetteMenu->addSeparator();
cassetteMenu->addAction(tr("&Existing image..."), [this]() { cassetteSelectImage(false); });
cassetteMenu->addAction(tr("Existing image (&Write-protected)..."), [this]() { cassetteSelectImage(true); });
cassetteMenu->addSeparator();
cassetteRecordPos = cassetteMenu->children().count();
cassetteMenu->addAction(tr("&Record"), [this] { pc_cas_set_mode(cassette, 1); cassetteUpdateMenu(); })->setCheckable(true);
cassettePlayPos = cassetteMenu->children().count();
cassetteMenu->addAction(tr("&Play"), [this] { pc_cas_set_mode(cassette, 0); cassetteUpdateMenu(); })->setCheckable(true);
cassetteRewindPos = cassetteMenu->children().count();
cassetteMenu->addAction(tr("&Rewind to the beginning"), [] { pc_cas_rewind(cassette); });
cassetteFastFwdPos = cassetteMenu->children().count();
cassetteMenu->addAction(tr("&Fast forward to the end"), [] { pc_cas_append(cassette); });
cassetteMenu->addSeparator();
cassetteEjectPos = cassetteMenu->children().count();
cassetteMenu->addAction(tr("E&ject"), [this]() { cassetteEject(); });
cassetteUpdateMenu();
}
cartridgeMenus.clear();
if (machine_has_cartridge(machine)) {
for (int i = 0; i < 2; i++) {
auto *menu = parentMenu->addMenu("");
menu->addAction(tr("&Image..."), [this, i]() { cartridgeSelectImage(i); });
menu->addSeparator();
cartridgeEjectPos = menu->children().count();
menu->addAction(tr("E&ject"), [this, i]() { cartridgeEject(i); });
cartridgeMenus[i] = menu;
cartridgeUpdateMenu(i);
}
}
floppyMenus.clear();
MachineStatus::iterateFDD([this, parentMenu](int i) {
auto *menu = parentMenu->addMenu("");
menu->addAction(tr("&New image..."), [this, i]() { floppyNewImage(i); });
menu->addSeparator();
menu->addAction(tr("&Existing image..."), [this, i]() { floppySelectImage(i, false); });
menu->addAction(tr("Existing image (&Write-protected)..."), [this, i]() { floppySelectImage(i, true); });
menu->addSeparator();
for (int slot = 0; slot < MAX_PREV_IMAGES; slot++) {
floppyImageHistoryPos[slot] = menu->children().count();
menu->addAction(QString::asprintf(tr("Image %i").toUtf8().constData(), slot), [this, i, slot]() { floppyMenuSelect(i, slot); })->setCheckable(false);
}
menu->addSeparator();
floppyExportPos = menu->children().count();
menu->addAction(tr("E&xport to 86F..."), [this, i]() { floppyExportTo86f(i); });
menu->addSeparator();
floppyEjectPos = menu->children().count();
menu->addAction(tr("E&ject"), [this, i]() { floppyEject(i); });
floppyMenus[i] = menu;
floppyUpdateMenu(i);
});
cdromMenus.clear();
MachineStatus::iterateCDROM([this, parentMenu](int i) {
auto *menu = parentMenu->addMenu("");
cdromMutePos = menu->children().count();
menu->addAction(ProgSettings::loadIcon("/cdrom_mute.ico"), tr("&Mute"), [this, i]() { cdromMute(i); })->setCheckable(true);
menu->addSeparator();
menu->addAction(ProgSettings::loadIcon("/cdrom_image.ico"), tr("&Image..."), [this, i]() { cdromMount(i, 0, nullptr); })->setCheckable(false);
menu->addAction(ProgSettings::loadIcon("/cdrom_folder.ico"), tr("&Folder..."), [this, i]() { cdromMount(i, 1, nullptr); })->setCheckable(false);
menu->addSeparator();
for (int slot = 0; slot < MAX_PREV_IMAGES; slot++) {
cdromImageHistoryPos[slot] = menu->children().count();
menu->addAction(QString::asprintf(tr("Image %i").toUtf8().constData(), slot), [this, i, slot]() { cdromReload(i, slot); })->setCheckable(false);
}
menu->addSeparator();
#ifdef Q_OS_WINDOWS
/* Loop through each Windows drive letter and test to see if
it's a CDROM */
for (const auto &letter : driveLetters) {
auto drive = QString("%1:\\").arg(letter);
if (GetDriveType(drive.toUtf8().constData()) == DRIVE_CDROM)
menu->addAction(ProgSettings::loadIcon("/cdrom_host.ico"), tr("Host CD/DVD Drive (%1:)").arg(letter), [this, i, letter] { cdromMount(i, 2, QString(R"(\\.\%1:)").arg(letter)); })->setCheckable(false);
}
menu->addSeparator();
#endif // Q_OS_WINDOWS
cdromImagePos = menu->children().count();
cdromDirPos = menu->children().count();
menu->addAction(tr("E&ject"), [this, i]() { cdromEject(i); })->setCheckable(false);
cdromMenus[i] = menu;
cdromUpdateMenu(i);
});
zipMenus.clear();
MachineStatus::iterateZIP([this, parentMenu](int i) {
auto *menu = parentMenu->addMenu("");
menu->addAction(tr("&New image..."), [this, i]() { zipNewImage(i); });
menu->addSeparator();
menu->addAction(tr("&Existing image..."), [this, i]() { zipSelectImage(i, false); });
menu->addAction(tr("Existing image (&Write-protected)..."), [this, i]() { zipSelectImage(i, true); });
menu->addSeparator();
zipEjectPos = menu->children().count();
menu->addAction(tr("E&ject"), [this, i]() { zipEject(i); });
zipReloadPos = menu->children().count();
menu->addAction(tr("&Reload previous image"), [this, i]() { zipReload(i); });
zipMenus[i] = menu;
zipUpdateMenu(i);
});
moMenus.clear();
MachineStatus::iterateMO([this, parentMenu](int i) {
auto *menu = parentMenu->addMenu("");
menu->addAction(tr("&New image..."), [this, i]() { moNewImage(i); });
menu->addSeparator();
menu->addAction(tr("&Existing image..."), [this, i]() { moSelectImage(i, false); });
menu->addAction(tr("Existing image (&Write-protected)..."), [this, i]() { moSelectImage(i, true); });
menu->addSeparator();
moEjectPos = menu->children().count();
menu->addAction(tr("E&ject"), [this, i]() { moEject(i); });
moReloadPos = menu->children().count();
menu->addAction(tr("&Reload previous image"), [this, i]() { moReload(i); });
moMenus[i] = menu;
moUpdateMenu(i);
});
netMenus.clear();
MachineStatus::iterateNIC([this, parentMenu](int i) {
auto *menu = parentMenu->addMenu("");
netDisconnPos = menu->children().count();
auto *action = menu->addAction(tr("&Connected"), [this, i] { network_is_connected(i) ? nicDisconnect(i) : nicConnect(i); });
action->setCheckable(true);
netMenus[i] = menu;
nicUpdateMenu(i);
});
parentMenu->addAction(tr("Clear image history"), [this]() { clearImageHistory(); });
}
void
MediaMenu::cassetteNewImage()
{
auto filename = QFileDialog::getSaveFileName(parentWidget, tr("Create..."));
QFileInfo fileinfo(filename);
if (fileinfo.suffix().isEmpty()) {
filename.append(".cas");
}
if (!filename.isNull()) {
if (filename.isEmpty())
cassetteEject();
else
cassetteMount(filename, false);
}
}
void
MediaMenu::cassetteSelectImage(bool wp)
{
auto filename = QFileDialog::getOpenFileName(parentWidget,
QString(),
getMediaOpenDirectory(),
tr("Cassette images") % util::DlgFilter({ "pcm", "raw", "wav", "cas" }) % tr("All files") % util::DlgFilter({ "*" }, true));
if (!filename.isEmpty())
cassetteMount(filename, wp);
}
void
MediaMenu::cassetteMount(const QString &filename, bool wp)
{
pc_cas_set_fname(cassette, nullptr);
memset(cassette_fname, 0, sizeof(cassette_fname));
cassette_ui_writeprot = wp ? 1 : 0;
if (!filename.isEmpty()) {
QByteArray filenameBytes = filename.toUtf8();
strncpy(cassette_fname, filenameBytes.data(), sizeof(cassette_fname) - 1);
pc_cas_set_fname(cassette, cassette_fname);
}
ui_sb_update_icon_state(SB_CASSETTE, filename.isEmpty() ? 1 : 0);
cassetteUpdateMenu();
ui_sb_update_tip(SB_CASSETTE);
config_save();
}
void
MediaMenu::cassetteEject()
{
pc_cas_set_fname(cassette, nullptr);
memset(cassette_fname, 0, sizeof(cassette_fname));
ui_sb_update_icon_state(SB_CASSETTE, 1);
cassetteUpdateMenu();
ui_sb_update_tip(SB_CASSETTE);
config_save();
}
void
MediaMenu::cassetteUpdateMenu()
{
QString name = cassette_fname;
const QString mode = cassette_mode;
auto childs = cassetteMenu->children();
auto *recordMenu = dynamic_cast<QAction *>(childs[cassetteRecordPos]);
auto *playMenu = dynamic_cast<QAction *>(childs[cassettePlayPos]);
auto *rewindMenu = dynamic_cast<QAction *>(childs[cassetteRewindPos]);
auto *fastFwdMenu = dynamic_cast<QAction *>(childs[cassetteFastFwdPos]);
auto *ejectMenu = dynamic_cast<QAction *>(childs[cassetteEjectPos]);
recordMenu->setEnabled(!name.isEmpty());
playMenu->setEnabled(!name.isEmpty());
rewindMenu->setEnabled(!name.isEmpty());
fastFwdMenu->setEnabled(!name.isEmpty());
ejectMenu->setEnabled(!name.isEmpty());
const bool isSaving = (mode == QStringLiteral("save"));
recordMenu->setChecked(isSaving);
playMenu->setChecked(!isSaving);
cassetteMenu->setTitle(QString::asprintf(tr("Cassette: %s").toUtf8().constData(),
(name.isEmpty() ? tr("(empty)") : name).toUtf8().constData()));
}
void
MediaMenu::cartridgeMount(int i, const QString &filename)
{
cart_close(i);
QByteArray filenameBytes = filename.toUtf8();
cart_load(i, filenameBytes.data());
ui_sb_update_icon_state(SB_CARTRIDGE | i, filename.isEmpty() ? 1 : 0);
cartridgeUpdateMenu(i);
ui_sb_update_tip(SB_CARTRIDGE | i);
config_save();
}
void
MediaMenu::cartridgeSelectImage(int i)
{
const auto filename = QFileDialog::getOpenFileName(
parentWidget,
QString(),
getMediaOpenDirectory(),
tr("Cartridge images") % util::DlgFilter({ "a", "b", "jrc" }) % tr("All files") % util::DlgFilter({ "*" }, true));
if (filename.isEmpty()) {
return;
}
cartridgeMount(i, filename);
}
void
MediaMenu::cartridgeEject(int i)
{
cart_close(i);
ui_sb_update_icon_state(SB_CARTRIDGE | i, 1);
cartridgeUpdateMenu(i);
ui_sb_update_tip(SB_CARTRIDGE | i);
config_save();
}
void
MediaMenu::cartridgeUpdateMenu(int i)
{
const QString name = cart_fns[i];
auto *menu = cartridgeMenus[i];
auto childs = menu->children();
auto *ejectMenu = dynamic_cast<QAction *>(childs[cartridgeEjectPos]);
ejectMenu->setEnabled(!name.isEmpty());
// menu->setTitle(tr("Cartridge %1: %2").arg(QString::number(i+1), name.isEmpty() ? tr("(empty)") : name));
menu->setTitle(QString::asprintf(tr("Cartridge %i: %ls").toUtf8().constData(), i + 1, name.isEmpty() ? tr("(empty)").toStdU16String().data() : name.toStdU16String().data()));
}
void
MediaMenu::floppyNewImage(int i)
{
NewFloppyDialog dialog(NewFloppyDialog::MediaType::Floppy, parentWidget);
switch (dialog.exec()) {
default:
break;
case QDialog::Accepted:
const QByteArray filename = dialog.fileName().toUtf8();
floppyMount(i, filename, false);
break;
}
}
void
MediaMenu::floppySelectImage(int i, bool wp)
{
auto filename = QFileDialog::getOpenFileName(
parentWidget,
QString(),
getMediaOpenDirectory(),
tr("All images") %
util::DlgFilter({ "0??","1??","??0","86f","bin","cq?","d??","flp","hdm","im?","json","td0","*fd?","mfm","xdf" }) %
tr("Advanced sector images") %
util::DlgFilter({ "imd","json","td0" }) %
tr("Basic sector images") %
util::DlgFilter({ "0??","1??","??0","bin","cq?","d??","flp","hdm","im?","xdf","*fd?" }) %
tr("Flux images") %
util::DlgFilter({ "fdi" }) %
tr("Surface images") %
util::DlgFilter({ "86f","mfm" }) %
tr("All files") %
util::DlgFilter({ "*" }, true));
if (!filename.isEmpty()) floppyMount(i, filename, wp);
}
void
MediaMenu::floppyMount(int i, const QString &filename, bool wp)
{
auto previous_image = QFileInfo(floppyfns[i]);
fdd_close(i);
ui_writeprot[i] = wp ? 1 : 0;
if (!filename.isEmpty()) {
QByteArray filenameBytes = filename.toUtf8();
fdd_load(i, filenameBytes.data());
}
ui_sb_update_icon_state(SB_FLOPPY | i, filename.isEmpty() ? 1 : 0);
mhm.addImageToHistory(i, ui::MediaType::Floppy, previous_image.filePath(), filename);
floppyUpdateMenu(i);
ui_sb_update_tip(SB_FLOPPY | i);
config_save();
}
void
MediaMenu::floppyEject(int i)
{
mhm.addImageToHistory(i, ui::MediaType::Floppy, floppyfns[i], QString());
fdd_close(i);
ui_sb_update_icon_state(SB_FLOPPY | i, 1);
floppyUpdateMenu(i);
ui_sb_update_tip(SB_FLOPPY | i);
config_save();
}
void
MediaMenu::floppyExportTo86f(int i)
{
auto filename = QFileDialog::getSaveFileName(parentWidget, QString(), QString(), tr("Surface images") % util::DlgFilter({ "86f" }, true));
if (!filename.isEmpty()) {
QByteArray filenameBytes = filename.toUtf8();
plat_pause(1);
if (d86f_export(i, filenameBytes.data()) == 0) {
QMessageBox::critical(parentWidget, tr("Unable to write file"), tr("Make sure the file is being saved to a writable directory"));
}
plat_pause(0);
}
}
void
MediaMenu::floppyUpdateMenu(int i)
{
QString name = floppyfns[i];
QFileInfo fi(floppyfns[i]);
if (!floppyMenus.contains(i))
return;
auto *menu = floppyMenus[i];
auto childs = menu->children();
auto *ejectMenu = dynamic_cast<QAction *>(childs[floppyEjectPos]);
auto *exportMenu = dynamic_cast<QAction *>(childs[floppyExportPos]);
ejectMenu->setEnabled(!name.isEmpty());
ejectMenu->setText(QString::asprintf(tr("Eject %s").toUtf8().constData(), name.isEmpty() ? QString().toUtf8().constData() : fi.fileName().toUtf8().constData()));
exportMenu->setEnabled(!name.isEmpty());
for (int slot = 0; slot < MAX_PREV_IMAGES; slot++) {
updateImageHistory(i, slot, ui::MediaType::Floppy);
}
int type = fdd_get_type(i);
// floppyMenus[i]->setTitle(tr("Floppy %1 (%2): %3").arg(QString::number(i+1), fdd_getname(type), name.isEmpty() ? tr("(empty)") : name));
floppyMenus[i]->setTitle(QString::asprintf(tr("Floppy %i (%s): %ls").toUtf8().constData(), i + 1, fdd_getname(type), name.isEmpty() ? tr("(empty)").toStdU16String().data() : name.toStdU16String().data()));
}
void
MediaMenu::floppyMenuSelect(int index, int slot)
{
QString filename = mhm.getImageForSlot(index, slot, ui::MediaType::Floppy);
floppyMount(index, filename.toUtf8().constData(), false);
floppyUpdateMenu(index);
ui_sb_update_tip(SB_FLOPPY | index);
}
void
MediaMenu::cdromMute(int i)
{
cdrom[i].sound_on ^= 1;
config_save();
cdromUpdateMenu(i);
sound_cd_thread_reset();
}
void
MediaMenu::cdromMount(int i, const QString &filename)
{
QByteArray fn = filename.toUtf8().data();
strcpy(cdrom[i].prev_image_path, cdrom[i].image_path);
if (cdrom[i].ops && cdrom[i].ops->exit)
cdrom[i].ops->exit(&(cdrom[i]));
cdrom[i].ops = nullptr;
memset(cdrom[i].image_path, 0, sizeof(cdrom[i].image_path));
#ifdef Q_OS_WINDOWS
if ((fn.data() != nullptr) && (strlen(fn.data()) >= 1) && (fn.data()[strlen(fn.data()) - 1] == '/'))
fn.data()[strlen(fn.data()) - 1] = '\\';
#else
if ((fn.data() != NULL) && (strlen(fn.data()) >= 1) && (fn.data()[strlen(fn.data()) - 1] == '\\'))
fn.data()[strlen(fn.data()) - 1] = '/';
#endif
if ((fn.data() != nullptr) && fn.contains("ioctl://"))
cdrom_ioctl_open(&(cdrom[i]), fn.data());
else
cdrom_image_open(&(cdrom[i]), fn.data());
/* Signal media change to the emulated machine. */
if (cdrom[i].insert)
cdrom[i].insert(cdrom[i].priv);
if (strlen(cdrom[i].image_path) > 0)
ui_sb_update_icon_state(SB_CDROM | i, 0);
else
ui_sb_update_icon_state(SB_CDROM | i, 1);
mhm.addImageToHistory(i, ui::MediaType::Optical, cdrom[i].prev_image_path, cdrom[i].image_path);
cdromUpdateMenu(i);
ui_sb_update_tip(SB_CDROM | i);
config_save();
}
void
MediaMenu::cdromMount(int i, int dir, const QString &arg)
{
QString filename;
QFileInfo fi(cdrom[i].image_path);
if (dir > 1)
filename = QString::asprintf(R"(ioctl://%s)", arg.toStdString().c_str());
else if (dir == 1)
filename = QFileDialog::getExistingDirectory(parentWidget);
else {
filename = QFileDialog::getOpenFileName(parentWidget, QString(),
QString(),
tr("CD-ROM images") % util::DlgFilter({ "iso", "cue" }) % tr("All files") % util::DlgFilter({ "*" }, true));
}
if (filename.isEmpty())
return;
cdromMount(i, filename);
}
void
MediaMenu::cdromEject(int i)
{
mhm.addImageToHistory(i, ui::MediaType::Optical, cdrom[i].image_path, QString());
cdrom_eject(i);
cdromUpdateMenu(i);
ui_sb_update_tip(SB_CDROM | i);
}
void
MediaMenu::cdromReload(int index, int slot)
{
const QString filename = mhm.getImageForSlot(index, slot, ui::MediaType::Optical);
cdromMount(index, filename.toUtf8().constData());
cdromUpdateMenu(index);
ui_sb_update_tip(SB_CDROM | index);
}
void
MediaMenu::cdromUpdateUi(int i)
{
cdrom_t *drv = &cdrom[i];
if (strlen(cdrom[i].image_path) == 0) {
mhm.addImageToHistory(i, ui::MediaType::Optical, drv->prev_image_path, QString());
ui_sb_update_icon_state(SB_CDROM | i, 1);
} else {
mhm.addImageToHistory(i, ui::MediaType::Optical, drv->prev_image_path, drv->image_path);
ui_sb_update_icon_state(SB_CDROM | i, 0);
}
cdromUpdateMenu(i);
ui_sb_update_tip(SB_CDROM | i);
}
void
MediaMenu::updateImageHistory(int index, int slot, ui::MediaType type)
{
QMenu *menu;
QAction *imageHistoryUpdatePos;
QObjectList children;
QFileInfo fi;
QIcon menu_icon;
const auto fn = mhm.getImageForSlot(index, slot, type);
QString menu_item_name;
switch (type) {
case ui::MediaType::Optical:
if (!cdromMenus.contains(index))
return;
menu = cdromMenus[index];
children = menu->children();
imageHistoryUpdatePos = dynamic_cast<QAction *>(children[cdromImageHistoryPos[slot]]);
if (fn.left(8) == "ioctl://") {
menu_icon = ProgSettings::loadIcon("/cdrom_host.ico");
#ifdef Q_OS_WINDOWS
menu_item_name = tr("Host CD/DVD Drive (%1)").arg(fn.right(2)).toUtf8().constData();
#else
menu_item_name = tr("Host CD/DVD Drive (%1)").arg(fn.right(fn.length() - 8));
#endif
} else {
fi.setFile(fn);
menu_icon = fi.isDir() ? ProgSettings::loadIcon("/cdrom_folder.ico") : ProgSettings::loadIcon("/cdrom_image.ico");
menu_item_name = fn.isEmpty() ? tr("previous image").toUtf8().constData() : fn.toUtf8().constData();
}
imageHistoryUpdatePos->setIcon(menu_icon);
break;
case ui::MediaType::Floppy:
if (!floppyMenus.contains(index))
return;
menu = floppyMenus[index];
children = menu->children();
imageHistoryUpdatePos = dynamic_cast<QAction *>(children[floppyImageHistoryPos[slot]]);
fi.setFile(fn);
menu_item_name = fi.fileName().isEmpty() ? tr("previous image").toUtf8().constData() : fi.fileName().toUtf8().constData();
break;
default:
menu_item_name = fi.fileName().isEmpty() ? tr("previous image").toUtf8().constData() : fi.fileName().toUtf8().constData();
return;
}
imageHistoryUpdatePos->setText(QString::asprintf(tr("%s").toUtf8().constData(), menu_item_name.toUtf8().constData()));
if (fn.left(8) == "ioctl://")
imageHistoryUpdatePos->setVisible(true);
else
imageHistoryUpdatePos->setVisible(!fn.isEmpty() && fi.exists());
}
void
MediaMenu::clearImageHistory()
{
mhm.clearImageHistory();
ui_sb_update_panes();
}
void
MediaMenu::cdromUpdateMenu(int i)
{
QString name = cdrom[i].image_path;
QString name2;
QIcon menu_icon;
if (!cdromMenus.contains(i))
return;
auto *menu = cdromMenus[i];
auto childs = menu->children();
auto *muteMenu = dynamic_cast<QAction *>(childs[cdromMutePos]);
muteMenu->setIcon(ProgSettings::loadIcon((cdrom[i].sound_on == 0) ? "/cdrom_unmute.ico" : "/cdrom_mute.ico"));
muteMenu->setText((cdrom[i].sound_on == 0) ? tr("&Unmute") : tr("&Mute"));
auto *imageMenu = dynamic_cast<QAction *>(childs[cdromImagePos]);
imageMenu->setEnabled(!name.isEmpty());
QString menu_item_name;
if (name.left(8) == "ioctl://") {
#ifdef Q_OS_WINDOWS
menu_item_name = tr("Host CD/DVD Drive (%1)").arg(name.right(2)).toUtf8().constData();
#else
menu_item_name = tr("Host CD/DVD Drive (%1)").arg(name.right(name.length() - 8));
#endif
name2 = menu_item_name;
menu_icon = ProgSettings::loadIcon("/cdrom_host.ico");
} else {
QFileInfo fi(cdrom[i].image_path);
menu_item_name = name.isEmpty() ? QString().toUtf8().constData() : name.toUtf8().constData();
name2 = name;
menu_icon = fi.isDir() ? ProgSettings::loadIcon("/cdrom_folder.ico") : ProgSettings::loadIcon("/cdrom_image.ico");
}
imageMenu->setIcon(menu_icon);
imageMenu->setText(QString::asprintf(tr("Eject %s").toUtf8().constData(), menu_item_name.toUtf8().constData()));
for (int slot = 0; slot < MAX_PREV_IMAGES; slot++)
updateImageHistory(i, slot, ui::MediaType::Optical);
QString busName = tr("Unknown Bus");
switch (cdrom[i].bus_type) {
default:
break;
case CDROM_BUS_ATAPI:
busName = "ATAPI";
break;
case CDROM_BUS_SCSI:
busName = "SCSI";
break;
case CDROM_BUS_MITSUMI:
busName = "Mitsumi";
break;
}
// menu->setTitle(tr("CD-ROM %1 (%2): %3").arg(QString::number(i+1), busName, name.isEmpty() ? tr("(empty)") : name));
menu->setTitle(QString::asprintf(tr("CD-ROM %i (%s): %s").toUtf8().constData(), i + 1, busName.toUtf8().data(), name.isEmpty() ? tr("(empty)").toUtf8().data() : name2.toUtf8().data()));
}
void
MediaMenu::zipNewImage(int i)
{
NewFloppyDialog dialog(NewFloppyDialog::MediaType::Zip, parentWidget);
switch (dialog.exec()) {
default:
break;
case QDialog::Accepted:
QByteArray filename = dialog.fileName().toUtf8();
zipMount(i, filename, false);
break;
}
}
void
MediaMenu::zipSelectImage(int i, bool wp)
{
const auto filename = QFileDialog::getOpenFileName(
parentWidget,
QString(),
QString(),
tr("ZIP images") % util::DlgFilter({ "im?", "zdi" }) % tr("All files") % util::DlgFilter({ "*" }, true));
if (!filename.isEmpty())
zipMount(i, filename, wp);
}
void
MediaMenu::zipMount(int i, const QString &filename, bool wp)
{
const auto dev = static_cast<zip_t *>(zip_drives[i].priv);
zip_disk_close(dev);
zip_drives[i].read_only = wp;
if (!filename.isEmpty()) {
QByteArray filenameBytes = filename.toUtf8();
zip_load(dev, filenameBytes.data());
zip_insert(dev);
}
ui_sb_update_icon_state(SB_ZIP | i, filename.isEmpty() ? 1 : 0);
zipUpdateMenu(i);
ui_sb_update_tip(SB_ZIP | i);
config_save();
}
void
MediaMenu::zipEject(int i)
{
const auto dev = static_cast<zip_t *>(zip_drives[i].priv);
zip_disk_close(dev);
zip_drives[i].image_path[0] = 0;
if (zip_drives[i].bus_type) {
/* Signal disk change to the emulated machine. */
zip_insert(dev);
}
ui_sb_update_icon_state(SB_ZIP | i, 1);
zipUpdateMenu(i);
ui_sb_update_tip(SB_ZIP | i);
config_save();
}
void
MediaMenu::zipReload(int i)
{
const auto dev = static_cast<zip_t *>(zip_drives[i].priv);
zip_disk_reload(dev);
if (strlen(zip_drives[i].image_path) == 0) {
ui_sb_update_icon_state(SB_ZIP | i, 1);
} else {
ui_sb_update_icon_state(SB_ZIP | i, 0);
}
zipUpdateMenu(i);
ui_sb_update_tip(SB_ZIP | i);
config_save();
}
void
MediaMenu::zipUpdateMenu(int i)
{
const QString name = zip_drives[i].image_path;
const QString prev_name = zip_drives[i].prev_image_path;
if (!zipMenus.contains(i))
return;
auto *menu = zipMenus[i];
auto childs = menu->children();
auto *ejectMenu = dynamic_cast<QAction *>(childs[zipEjectPos]);
auto *reloadMenu = dynamic_cast<QAction *>(childs[zipReloadPos]);
ejectMenu->setEnabled(!name.isEmpty());
reloadMenu->setEnabled(!prev_name.isEmpty());
QString busName = tr("Unknown Bus");
switch (zip_drives[i].bus_type) {
default:
break;
case ZIP_BUS_ATAPI:
busName = "ATAPI";
break;
case ZIP_BUS_SCSI:
busName = "SCSI";
break;
}
// menu->setTitle(tr("ZIP %1 %2 (%3): %4").arg((zip_drives[i].is_250 > 0) ? "250" : "100", QString::number(i+1), busName, name.isEmpty() ? tr("(empty)") : name));
menu->setTitle(QString::asprintf(tr("ZIP %03i %i (%s): %ls").toUtf8().constData(), (zip_drives[i].is_250 > 0) ? 250 : 100, i + 1, busName.toUtf8().data(), name.isEmpty() ? tr("(empty)").toStdU16String().data() : name.toStdU16String().data()));
}
void
MediaMenu::moNewImage(int i)
{
NewFloppyDialog dialog(NewFloppyDialog::MediaType::Mo, parentWidget);
switch (dialog.exec()) {
default:
break;
case QDialog::Accepted:
QByteArray filename = dialog.fileName().toUtf8();
moMount(i, filename, false);
break;
}
}
void
MediaMenu::moSelectImage(int i, bool wp)
{
const auto filename = QFileDialog::getOpenFileName(
parentWidget,
QString(),
getMediaOpenDirectory(),
tr("MO images") % util::DlgFilter({ "im?", "mdi" }) % tr("All files") % util::DlgFilter({
"*",
},
true));
if (!filename.isEmpty())
moMount(i, filename, wp);
}
void
MediaMenu::moMount(int i, const QString &filename, bool wp)
{
const auto dev = static_cast<mo_t *>(mo_drives[i].priv);
mo_disk_close(dev);
mo_drives[i].read_only = wp;
if (!filename.isEmpty()) {
QByteArray filenameBytes = filename.toUtf8();
mo_load(dev, filenameBytes.data());
mo_insert(dev);
}
ui_sb_update_icon_state(SB_MO | i, filename.isEmpty() ? 1 : 0);
moUpdateMenu(i);
ui_sb_update_tip(SB_MO | i);
config_save();
}
void
MediaMenu::moEject(int i)
{
const auto dev = static_cast<mo_t *>(mo_drives[i].priv);
mo_disk_close(dev);
mo_drives[i].image_path[0] = 0;
if (mo_drives[i].bus_type) {
/* Signal disk change to the emulated machine. */
mo_insert(dev);
}
ui_sb_update_icon_state(SB_MO | i, 1);
moUpdateMenu(i);
ui_sb_update_tip(SB_MO | i);
config_save();
}
void
MediaMenu::moReload(int i)
{
mo_t *dev = (mo_t *) mo_drives[i].priv;
mo_disk_reload(dev);
if (strlen(mo_drives[i].image_path) == 0) {
ui_sb_update_icon_state(SB_MO | i, 1);
} else {
ui_sb_update_icon_state(SB_MO | i, 0);
}
moUpdateMenu(i);
ui_sb_update_tip(SB_MO | i);
config_save();
}
void
MediaMenu::moUpdateMenu(int i)
{
QString name = mo_drives[i].image_path;
QString prev_name = mo_drives[i].prev_image_path;
if (!moMenus.contains(i))
return;
auto *menu = moMenus[i];
auto childs = menu->children();
auto *ejectMenu = dynamic_cast<QAction *>(childs[moEjectPos]);
auto *reloadMenu = dynamic_cast<QAction *>(childs[moReloadPos]);
ejectMenu->setEnabled(!name.isEmpty());
reloadMenu->setEnabled(!prev_name.isEmpty());
QString busName = tr("Unknown Bus");
switch (mo_drives[i].bus_type) {
default:
break;
case MO_BUS_ATAPI:
busName = "ATAPI";
break;
case MO_BUS_SCSI:
busName = "SCSI";
break;
}
menu->setTitle(QString::asprintf(tr("MO %i (%ls): %ls").toUtf8().constData(), i + 1, busName.toStdU16String().data(), name.isEmpty() ? tr("(empty)").toStdU16String().data() : name.toStdU16String().data()));
}
void
MediaMenu::nicConnect(int i)
{
network_connect(i, 1);
ui_sb_update_icon_state(SB_NETWORK | i, 0);
nicUpdateMenu(i);
config_save();
}
void
MediaMenu::nicDisconnect(int i)
{
network_connect(i, 0);
ui_sb_update_icon_state(SB_NETWORK | i, 1);
nicUpdateMenu(i);
config_save();
}
void
MediaMenu::nicUpdateMenu(int i)
{
if (!netMenus.contains(i))
return;
QString netType = tr("Null Driver");
switch (net_cards_conf[i].net_type) {
default:
break;
case NET_TYPE_SLIRP:
netType = "SLiRP";
break;
case NET_TYPE_PCAP:
netType = "PCAP";
break;
case NET_TYPE_VDE:
netType = "VDE";
break;
}
QString devName = DeviceConfig::DeviceName(network_card_getdevice(net_cards_conf[i].device_num), network_card_get_internal_name(net_cards_conf[i].device_num), 1);
auto *menu = netMenus[i];
auto childs = menu->children();
auto *connectedAction = dynamic_cast<QAction *>(childs[netDisconnPos]);
connectedAction->setChecked(network_is_connected(i));
menu->setTitle(QString::asprintf(tr("NIC %02i (%ls) %ls").toUtf8().constData(), i + 1, netType.toStdU16String().data(), devName.toStdU16String().data()));
}
QString
MediaMenu::getMediaOpenDirectory()
{
QString openDirectory;
if (open_dir_usr_path > 0)
openDirectory = QString::fromUtf8(usr_path);
return openDirectory;
}
// callbacks from 86box C code
extern "C" {
void
cassette_mount(char *fn, uint8_t wp)
{
MediaMenu::ptr->cassetteMount(QString(fn), wp);
}
void
cassette_eject(void)
{
MediaMenu::ptr->cassetteEject();
}
void
cartridge_mount(uint8_t id, char *fn, uint8_t wp)
{
MediaMenu::ptr->cartridgeMount(id, QString(fn));
}
void
cartridge_eject(uint8_t id)
{
MediaMenu::ptr->cartridgeEject(id);
}
void
floppy_mount(uint8_t id, char *fn, uint8_t wp)
{
MediaMenu::ptr->floppyMount(id, QString(fn), wp);
}
void
floppy_eject(uint8_t id)
{
MediaMenu::ptr->floppyEject(id);
}
void
cdrom_mount(uint8_t id, char *fn)
{
MediaMenu::ptr->cdromMount(id, QString(fn));
}
void
plat_cdrom_ui_update(uint8_t id, uint8_t reload)
{
emit MediaMenu::ptr->onCdromUpdateUi(id);
}
void
zip_eject(uint8_t id)
{
MediaMenu::ptr->zipEject(id);
}
void
zip_mount(uint8_t id, char *fn, uint8_t wp)
{
MediaMenu::ptr->zipMount(id, QString(fn), wp);
}
void
zip_reload(uint8_t id)
{
MediaMenu::ptr->zipReload(id);
}
void
mo_eject(uint8_t id)
{
MediaMenu::ptr->moEject(id);
}
void
mo_mount(uint8_t id, char *fn, uint8_t wp)
{
MediaMenu::ptr->moMount(id, QString(fn), wp);
}
void
mo_reload(uint8_t id)
{
MediaMenu::ptr->moReload(id);
}
}
``` | /content/code_sandbox/src/qt/qt_mediamenu.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 9,021 |
```c++
#ifndef QT_JOYSTICKCONFIGURATION_HPP
#define QT_JOYSTICKCONFIGURATION_HPP
#include <QDialog>
namespace Ui {
class JoystickConfiguration;
}
class JoystickConfiguration : public QDialog {
Q_OBJECT
public:
explicit JoystickConfiguration(int type, int joystick_nr, QWidget *parent = nullptr);
~JoystickConfiguration();
int selectedDevice();
int selectedAxis(int axis);
int selectedButton(int button);
int selectedPov(int pov);
private slots:
void on_comboBoxDevice_currentIndexChanged(int index);
private:
Ui::JoystickConfiguration *ui;
QList<QWidget *> widgets;
int type;
int joystick_nr;
};
#endif // QT_JOYSTICKCONFIGURATION_HPP
``` | /content/code_sandbox/src/qt/qt_joystickconfiguration.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 150 |
```c++
static std::unordered_map<uint8_t, uint16_t> be_keycodes = {
{B_F1_KEY, 0x3b},
{B_F2_KEY, 0x3c},
{B_F3_KEY, 0x3d},
{B_F4_KEY, 0x3e},
{B_F5_KEY, 0x3f},
{B_F6_KEY, 0x40},
{B_F7_KEY, 0x41},
{B_F8_KEY, 0x42},
{B_F9_KEY, 0x43},
{B_F10_KEY, 0x44},
{B_F11_KEY, 0x57},
{B_F12_KEY, 0x58},
{B_PRINT_KEY, 0x137},
{B_SCROLL_KEY, 0x46},
{B_PAUSE_KEY, 0x145},
{B_KATAKANA_HIRAGANA, 0x70},
{B_HANKAKU_ZENKAKU, 0x76},
{0x01, 0x01}, /* Escape */
{0x11, 0x29},
{0x12, 0x02},
{0x13, 0x03},
{0x14, 0x04},
{0x15, 0x05},
{0x16, 0x06},
{0x17, 0x07},
{0x18, 0x08},
{0x19, 0x09},
{0x1a, 0x0a},
{0x1b, 0x0b},
{0x1c, 0x0c},
{0x1d, 0x0d},
{0x1e, 0x0e}, /* Backspace */
{0x1f, 0x152}, /* Insert */
{0x20, 0x147}, /* Home */
{0x21, 0x149}, /* Page Up */
{0x22, 0x45},
{0x23, 0x135},
{0x24, 0x37},
{0x25, 0x4a},
{0x26, 0x0f}, /* Tab */
{0x27, 0x10},
{0x28, 0x11},
{0x29, 0x12},
{0x2a, 0x13},
{0x2b, 0x14},
{0x2c, 0x15},
{0x2d, 0x16},
{0x2e, 0x17},
{0x2f, 0x18},
{0x30, 0x19},
{0x31, 0x1a},
{0x32, 0x1b},
{0x33, 0x2b},
{0x34, 0x153}, /* Delete */
{0x35, 0x14f}, /* End */
{0x36, 0x151}, /* Page Down */
{0x37, 0x47},
{0x38, 0x48},
{0x39, 0x49},
{0x3a, 0x4e},
{0x3b, 0x3a},
{0x3c, 0x1e},
{0x3d, 0x1f},
{0x3e, 0x20},
{0x3f, 0x21},
{0x40, 0x22},
{0x41, 0x23},
{0x42, 0x24},
{0x43, 0x25},
{0x44, 0x26},
{0x45, 0x27},
{0x46, 0x28},
{0x47, 0x1c}, /* Enter */
{0x48, 0x4b},
{0x49, 0x4c},
{0x4a, 0x4d},
{0x4b, 0x2a},
{0x4c, 0x2c},
{0x4d, 0x2d},
{0x4e, 0x2e},
{0x4f, 0x2f},
{0x50, 0x30},
{0x51, 0x31},
{0x52, 0x32},
{0x53, 0x33},
{0x54, 0x34},
{0x55, 0x35},
{0x56, 0x36},
{0x57, 0x148}, /* up arrow */
{0x58, 0x51},
{0x59, 0x50},
{0x5a, 0x4f},
{0x5b, 0x11c},
{0x5c, 0x1d},
{0x5d, 0x38},
{0x5e, 0x39}, /* space bar */
{0x5f, 0x138},
{0x60, 0x11d},
{0x61, 0x14b}, /* left arrow */
{0x62, 0x150}, /* down arrow */
{0x63, 0x14d}, /* right arrow */
{0x64, 0x52},
{0x65, 0x53},
{0x66, 0x15b},
{0x67, 0x15c},
{0x68, 0x15d},
{0x69, 0x56},
{0x7e, 0x137}, /* System Request */
{0x7f, 0x145}, /* Break */
};
``` | /content/code_sandbox/src/qt/be_keyboard.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,394 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Header for OpenGL renderer options
*
*
*
* Authors: Teemu Korhonen
*
*/
#ifndef QT_OPENGLOPTIONS_HPP
#define QT_OPENGLOPTIONS_HPP
#include <QList>
#include <QObject>
#include <QOpenGLContext>
#include <QOpenGLShaderProgram>
class OpenGLShaderPass {
public:
OpenGLShaderPass(QOpenGLShaderProgram *shader, const QString &path)
: m_shader(shader)
, m_path(path)
, m_vertex_coord(shader->attributeLocation("VertexCoord"))
, m_tex_coord(shader->attributeLocation("TexCoord"))
, m_color(shader->attributeLocation("Color"))
, m_mvp_matrix(shader->uniformLocation("MVPMatrix"))
, m_input_size(shader->uniformLocation("InputSize"))
, m_output_size(shader->uniformLocation("OutputSize"))
, m_texture_size(shader->uniformLocation("TextureSize"))
, m_frame_count(shader->uniformLocation("FrameCount"))
{
}
bool bind() const { return m_shader->bind(); }
const QString &path() const { return m_path; }
const GLint &vertex_coord() const { return m_vertex_coord; }
const GLint &tex_coord() const { return m_tex_coord; }
const GLint &color() const { return m_color; }
const GLint &mvp_matrix() const { return m_mvp_matrix; }
const GLint &input_size() const { return m_input_size; }
const GLint &output_size() const { return m_output_size; }
const GLint &texture_size() const { return m_texture_size; }
const GLint &frame_count() const { return m_frame_count; }
private:
QOpenGLShaderProgram *m_shader;
QString m_path;
GLint m_vertex_coord;
GLint m_tex_coord;
GLint m_color;
GLint m_mvp_matrix;
GLint m_input_size;
GLint m_output_size;
GLint m_texture_size;
GLint m_frame_count;
};
class OpenGLOptions : public QObject {
Q_OBJECT
public:
enum RenderBehaviorType { SyncWithVideo,
TargetFramerate };
enum FilterType { Nearest,
Linear };
OpenGLOptions(QObject *parent, bool loadConfig, const QString &glslVersion);
RenderBehaviorType renderBehavior() const { return m_renderBehavior; }
int framerate() const { return m_framerate; }
bool vSync() const { return m_vsync; }
FilterType filter() const;
const QList<OpenGLShaderPass> &shaders() const { return m_shaders; }
void setRenderBehavior(RenderBehaviorType value);
void setFrameRate(int value);
void setVSync(bool value);
void setFilter(FilterType value);
void addShader(const QString &path);
void addDefaultShader();
void save() const;
private:
RenderBehaviorType m_renderBehavior = SyncWithVideo;
int m_framerate = -1;
bool m_vsync = false;
FilterType m_filter = Nearest;
QList<OpenGLShaderPass> m_shaders;
QString m_glslVersion;
};
#endif
``` | /content/code_sandbox/src/qt/qt_opengloptions.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 761 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implement threads and mutexes for the Win32 platform.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#define UNICODE
#define BITMAP WINDOWS_BITMAP
#include <windows.h>
#include <windowsx.h>
#include <process.h>
#undef BITMAP
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/thread.h>
typedef struct {
HANDLE handle;
} win_event_t;
/* For compatibility with thread.h, but Win32 does not allow named threads. */
thread_t *
thread_create_named(void (*func)(void *param), void *param, UNUSED(const char *name))
{
uintptr_t bt = _beginthread(func, 0, param);
return ((thread_t *) bt);
}
int
thread_test_mutex(thread_t *arg)
{
if (arg == NULL)
return (0);
return (WaitForSingleObject(arg, 0) == WAIT_OBJECT_0) ? 1 : 0;
}
int
thread_wait(thread_t *arg)
{
if (arg == NULL)
return (0);
if (WaitForSingleObject(arg, INFINITE))
return (1);
return (0);
}
event_t *
thread_create_event(void)
{
win_event_t *ev = malloc(sizeof(win_event_t));
ev->handle = CreateEvent(NULL, FALSE, FALSE, NULL);
return ((event_t *) ev);
}
void
thread_set_event(event_t *arg)
{
win_event_t *ev = (win_event_t *) arg;
if (arg == NULL)
return;
SetEvent(ev->handle);
}
void
thread_reset_event(event_t *arg)
{
win_event_t *ev = (win_event_t *) arg;
if (arg == NULL)
return;
ResetEvent(ev->handle);
}
int
thread_wait_event(event_t *arg, int timeout)
{
win_event_t *ev = (win_event_t *) arg;
if (arg == NULL)
return (0);
if (ev->handle == NULL)
return (0);
if (timeout == -1)
timeout = INFINITE;
if (WaitForSingleObject(ev->handle, timeout))
return (1);
return (0);
}
void
thread_destroy_event(event_t *arg)
{
win_event_t *ev = (win_event_t *) arg;
if (arg == NULL)
return;
CloseHandle(ev->handle);
free(ev);
}
mutex_t *
thread_create_mutex(void)
{
mutex_t *mutex = malloc(sizeof(CRITICAL_SECTION));
InitializeCriticalSection(mutex);
return mutex;
}
int
thread_wait_mutex(mutex_t *mutex)
{
if (mutex == NULL)
return (0);
LPCRITICAL_SECTION critsec = (LPCRITICAL_SECTION) mutex;
EnterCriticalSection(critsec);
return 1;
}
int
thread_release_mutex(mutex_t *mutex)
{
if (mutex == NULL)
return (0);
LPCRITICAL_SECTION critsec = (LPCRITICAL_SECTION) mutex;
LeaveCriticalSection(critsec);
return 1;
}
void
thread_close_mutex(mutex_t *mutex)
{
if (mutex == NULL)
return;
LPCRITICAL_SECTION critsec = (LPCRITICAL_SECTION) mutex;
DeleteCriticalSection(critsec);
free(critsec);
}
``` | /content/code_sandbox/src/qt/win_thread.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 824 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Header for the media history management module
*
*
*
* Authors: cold-brewed
*
*/
#ifndef QT_MEDIAHISTORYMANAGER_HPP
#define QT_MEDIAHISTORYMANAGER_HPP
#include <QString>
#include <QWidget>
#include <QVector>
#include <initializer_list>
extern "C" {
#include <86box/86box.h>
}
// This macro helps give us the required `qHash()` function in order to use the
// enum as a hash key
#define QHASH_FOR_CLASS_ENUM(T) \
inline uint qHash(const T &t, uint seed) \
{ \
return ::qHash(static_cast<typename std::underlying_type<T>::type>(t), seed); \
}
typedef QVector<QString> device_index_list_t;
typedef QHash<int, QVector<QString>> device_media_history_t;
namespace ui {
Q_NAMESPACE
enum class MediaType {
Floppy,
Optical,
Zip,
Mo,
Cassette
};
// This macro allows us to do a reverse lookup of the enum with `QMetaEnum`
Q_ENUM_NS(MediaType)
QHASH_FOR_CLASS_ENUM(MediaType)
typedef QHash<ui::MediaType, device_media_history_t> master_list_t;
// Used to iterate over all supported types when preparing data structures
// Also useful to indicate which types support history
static const MediaType AllSupportedMediaHistoryTypes[] = {
MediaType::Optical,
MediaType::Floppy,
};
class MediaHistoryManager {
public:
MediaHistoryManager();
virtual ~MediaHistoryManager();
// Get the image name for a particular slot,
// index, and type combination
QString getImageForSlot(int index, int slot, ui::MediaType type);
// Add an image to history
void addImageToHistory(int index, ui::MediaType type, const QString &image_name, const QString &new_image_name);
// Convert the enum value to a string
static QString mediaTypeToString(ui::MediaType type);
// Clear out the image history
void clearImageHistory();
private:
int max_images = MAX_PREV_IMAGES;
// Main hash of hash of vector of strings
master_list_t master_list;
[[nodiscard]] const master_list_t &getMasterList() const;
void setMasterList(const master_list_t &masterList);
device_index_list_t index_list;
device_index_list_t empty_device_index_list;
// Return a blank, initialized image history list
master_list_t &blankImageHistory(master_list_t &initialized_master_list) const;
// Initialize the image history
void initializeImageHistory();
// Max number of devices supported by media type
static int maxDevicesSupported(ui::MediaType type);
// Serialize the data back into the C array
// on the emu side
void serializeImageHistoryType(ui::MediaType type);
void serializeAllImageHistory();
// Deserialize the data from C array on the emu side
// for the ui side
void deserializeImageHistoryType(ui::MediaType type);
void deserializeAllImageHistory();
// Get emu history variable for a device type
static char **getEmuHistoryVarForType(ui::MediaType type, int index);
// Get or set the history for a specific device/index combo
const device_index_list_t &getHistoryListForDeviceIndex(int index, ui::MediaType type);
void setHistoryListForDeviceIndex(int index, ui::MediaType type, device_index_list_t history_list);
// Remove missing image files from history list
static device_index_list_t &removeMissingImages(device_index_list_t &device_history);
// If an absolute path is contained within `usr_path`, convert to a relative path
static device_index_list_t &pathAdjustFull(device_index_list_t &device_history);
static QString pathAdjustSingle(QString checked_path);
// Deduplicate history entries
static device_index_list_t &deduplicateList(device_index_list_t &device_history, const QVector<QString> &filenames);
void initialDeduplication();
// Gets the `usr_path` from the emu side and appends a
// trailing slash if necessary
static QString getUsrPath();
};
} // ui
#endif // QT_MEDIAHISTORYMANAGER_HPP
``` | /content/code_sandbox/src/qt/qt_mediahistorymanager.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 968 |
```c++
#ifndef QT_RENDERERCONTAINER_HPP
#define QT_RENDERERCONTAINER_HPP
#include <QDialog>
#include <QEvent>
#include <QKeyEvent>
#include <QStackedWidget>
#include <QWidget>
#include <QCursor>
#include <atomic>
#include <memory>
#include <tuple>
#include <vector>
#include "qt_renderercommon.hpp"
namespace Ui {
class RendererStack;
}
class RendererCommon;
class RendererStack : public QStackedWidget {
Q_OBJECT
public:
explicit RendererStack(QWidget *parent = nullptr, int monitor_index = 0);
~RendererStack();
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
void enterEvent(QEnterEvent *event) override;
#else
void enterEvent(QEvent *event) override;
#endif
void leaveEvent(QEvent *event) override;
void closeEvent(QCloseEvent *event) override;
void changeEvent(QEvent *event) override;
void resizeEvent(QResizeEvent *event) override
{
onResize(event->size().width(), event->size().height());
}
void keyPressEvent(QKeyEvent *event) override
{
event->ignore();
}
void keyReleaseEvent(QKeyEvent *event) override
{
event->ignore();
}
bool event(QEvent* event) override;
enum class Renderer {
Software,
OpenGL,
OpenGLES,
OpenGL3,
Vulkan,
None = -1
};
void switchRenderer(Renderer renderer);
/* Does current renderer implement options dialog */
bool hasOptions() const { return rendererWindow ? rendererWindow->hasOptions() : false; }
/* Reloads options of current renderer */
void reloadOptions() const { return rendererWindow->reloadOptions(); }
/* Returns options dialog for current renderer */
QDialog *getOptions(QWidget *parent) { return rendererWindow ? rendererWindow->getOptions(parent) : nullptr; }
void setFocusRenderer();
void onResize(int width, int height);
void (*mouse_capture_func)(QWindow *window) = nullptr;
void (*mouse_uncapture_func)() = nullptr;
void (*mouse_exit_func)() = nullptr;
signals:
void blitToRenderer(int buf_idx, int x, int y, int w, int h);
void rendererChanged();
public slots:
void blit(int x, int y, int w, int h);
private:
void createRenderer(Renderer renderer);
Ui::RendererStack *ui;
int x;
int y;
int w;
int h;
int sx;
int sy;
int sw;
int sh;
int currentBuf = 0;
int isMouseDown = 0;
int m_monitor_index = 0;
std::vector<std::tuple<uint8_t *, std::atomic_flag *>> imagebufs;
RendererCommon *rendererWindow { nullptr };
std::unique_ptr<QWidget> current;
};
#endif // QT_RENDERERCONTAINER_HPP
``` | /content/code_sandbox/src/qt/qt_rendererstack.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 683 |
```c++
#ifndef QT_DEVICECONFIG_HPP
#define QT_DEVICECONFIG_HPP
#include <QDialog>
#include "qt_settings.hpp"
extern "C" {
struct _device_;
}
namespace Ui {
class DeviceConfig;
}
class Settings;
class DeviceConfig : public QDialog {
Q_OBJECT
public:
explicit DeviceConfig(QWidget *parent = nullptr);
~DeviceConfig() override;
static void ConfigureDevice(const _device_ *device, int instance = 0,
Settings *settings = nullptr);
static QString DeviceName(const _device_ *device, const char *internalName, int bus);
private:
Ui::DeviceConfig *ui;
void ProcessConfig(void *dc, const void *c, bool is_dep);
};
#endif // QT_DEVICECONFIG_HPP
``` | /content/code_sandbox/src/qt/qt_deviceconfig.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 158 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
*
*/
/*
* C functionality for Qt platform, where the C equivalent is not easily
* implemented in Qt
*/
#if !defined(_WIN32) || !defined(__clang__)
# include <strings.h>
#endif
#include <string.h>
#include <stdint.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/plat.h>
#include <86box/timer.h>
#include <86box/nvr.h>
int
qt_nvr_save(void)
{
return nvr_save();
}
char icon_set[256] = ""; /* name of the iconset to be used */
int
plat_vidapi(const char *api)
{
if (!strcasecmp(api, "default") || !strcasecmp(api, "system")) {
return 0;
} else if (!strcasecmp(api, "qt_software")) {
return 0;
} else if (!strcasecmp(api, "qt_opengl")) {
return 1;
} else if (!strcasecmp(api, "qt_opengles")) {
return 2;
} else if (!strcasecmp(api, "qt_opengl3")) {
return 3;
} else if (!strcasecmp(api, "qt_vulkan")) {
return 4;
} else if (!strcasecmp(api, "vnc")) {
return 5;
}
return 0;
}
char *
plat_vidapi_name(int api)
{
char *name = "default";
switch (api) {
case 0:
name = "qt_software";
break;
case 1:
name = "qt_opengl";
break;
case 2:
name = "qt_opengles";
break;
case 3:
name = "qt_opengl3";
break;
case 4:
name = "qt_vulkan";
break;
case 5:
name = "vnc";
break;
default:
fatal("Unknown renderer: %i\n", api);
break;
}
return name;
}
``` | /content/code_sandbox/src/qt/qt.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 531 |
```c
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include "x11_util.h"
void set_wm_class(unsigned long window, char *res_name) {
Display* display = XOpenDisplay(NULL);
if (display == NULL) {
return;
}
XClassHint hint;
XGetClassHint(display, window, &hint);
hint.res_name = res_name;
XSetClassHint(display, window, &hint);
// During testing, I've had to issue XGetClassHint after XSetClassHint
// to get the window manager to recognize the change.
XGetClassHint(display, window, &hint);
}
``` | /content/code_sandbox/src/qt/x11_util.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 150 |
```c++
#include <cstdint>
extern "C" {
void
plat_midi_play_msg(uint8_t *msg)
{
}
void
plat_midi_play_sysex(uint8_t *sysex, unsigned int len)
{
}
void
plat_midi_input_init(void)
{
}
void
plat_midi_input_close(void)
{
}
int
plat_midi_write(uint8_t val)
{
return 0;
}
void
plat_midi_init()
{
}
void
plat_midi_close()
{
}
int
plat_midi_get_num_devs()
{
return 0;
}
int
plat_midi_in_get_num_devs(void)
{
return 0;
}
void
plat_midi_get_dev_name(int num, char *s)
{
s[0] = ' ';
s[1] = 0;
}
void
plat_midi_in_get_dev_name(int num, char *s)
{
s[0] = ' ';
s[1] = 0;
}
}
``` | /content/code_sandbox/src/qt/qt_midi.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 210 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Definitions for xkbcommon-x11 keyboard input module.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
void xkbcommon_x11_init();
``` | /content/code_sandbox/src/qt/xkbcommon_x11_keyboard.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 111 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Common storage devices module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
*
*/
#include "qt_harddrive_common.hpp"
#include <cstdint>
extern "C" {
#include <86box/hdd.h>
#include <86box/scsi.h>
#include <86box/cdrom.h>
}
#include <QAbstractItemModel>
#include <QStandardItemModel>
void
Harddrives::populateBuses(QAbstractItemModel *model)
{
model->removeRows(0, model->rowCount());
model->insertRows(0, 6);
model->setData(model->index(0, 0), "MFM/RLL");
model->setData(model->index(1, 0), "XTA");
model->setData(model->index(2, 0), "ESDI");
model->setData(model->index(3, 0), "IDE");
model->setData(model->index(4, 0), "ATAPI");
model->setData(model->index(5, 0), "SCSI");
model->setData(model->index(0, 0), HDD_BUS_MFM, Qt::UserRole);
model->setData(model->index(1, 0), HDD_BUS_XTA, Qt::UserRole);
model->setData(model->index(2, 0), HDD_BUS_ESDI, Qt::UserRole);
model->setData(model->index(3, 0), HDD_BUS_IDE, Qt::UserRole);
model->setData(model->index(4, 0), HDD_BUS_ATAPI, Qt::UserRole);
model->setData(model->index(5, 0), HDD_BUS_SCSI, Qt::UserRole);
}
void
Harddrives::populateRemovableBuses(QAbstractItemModel *model)
{
model->removeRows(0, model->rowCount());
#if 0
model->insertRows(0, 4);
#else
model->insertRows(0, 3);
#endif
model->setData(model->index(0, 0), QObject::tr("Disabled"));
model->setData(model->index(1, 0), QObject::tr("ATAPI"));
model->setData(model->index(2, 0), QObject::tr("SCSI"));
#if 0
model->setData(model->index(3, 0), QObject::tr("Mitsumi"));
#endif
model->setData(model->index(0, 0), HDD_BUS_DISABLED, Qt::UserRole);
model->setData(model->index(1, 0), HDD_BUS_ATAPI, Qt::UserRole);
model->setData(model->index(2, 0), HDD_BUS_SCSI, Qt::UserRole);
#if 0
model->setData(model->index(3, 0), CDROM_BUS_MITSUMI, Qt::UserRole);
#endif
}
void
Harddrives::populateSpeeds(QAbstractItemModel *model, int bus)
{
int num_preset;
switch (bus) {
case HDD_BUS_ESDI:
case HDD_BUS_IDE:
case HDD_BUS_ATAPI:
case HDD_BUS_SCSI:
num_preset = hdd_preset_get_num();
break;
default:
num_preset = 1;
}
model->removeRows(0, model->rowCount());
model->insertRows(0, num_preset);
for (int i = 0; i < num_preset; i++) {
model->setData(model->index(i, 0), QObject::tr(hdd_preset_getname(i)));
model->setData(model->index(i, 0), i, Qt::UserRole);
}
}
void
Harddrives::populateBusChannels(QAbstractItemModel *model, int bus, SettingsBusTracking *sbt)
{
model->removeRows(0, model->rowCount());
int busRows = 0;
int shifter = 1;
int orer = 1;
int subChannelWidth = 1;
QList<int> busesToCheck;
QList<int> channelsInUse;
switch (bus) {
case HDD_BUS_MFM:
busRows = 2;
busesToCheck.append(HDD_BUS_MFM);
break;
case HDD_BUS_XTA:
busRows = 2;
busesToCheck.append(HDD_BUS_XTA);
break;
case HDD_BUS_ESDI:
busRows = 2;
busesToCheck.append(HDD_BUS_ESDI);
break;
case HDD_BUS_IDE:
busRows = 8;
busesToCheck.append(HDD_BUS_ATAPI);
busesToCheck.append(HDD_BUS_IDE);
break;
case HDD_BUS_ATAPI:
busRows = 8;
busesToCheck.append(HDD_BUS_IDE);
busesToCheck.append(HDD_BUS_ATAPI);
break;
case HDD_BUS_SCSI:
shifter = 4;
orer = 15;
busRows = /*64*/ SCSI_BUS_MAX * SCSI_ID_MAX;
subChannelWidth = 2;
busesToCheck.append(HDD_BUS_SCSI);
break;
default:
break;
}
if(sbt != nullptr && !busesToCheck.empty()) {
for (auto const &checkBus : busesToCheck) {
channelsInUse.append(sbt->busChannelsInUse(checkBus));
}
}
model->insertRows(0, busRows);
for (int i = 0; i < busRows; ++i) {
auto idx = model->index(i, 0);
model->setData(idx, QString("%1:%2").arg(i >> shifter).arg(i & orer, subChannelWidth, 10, QChar('0')));
model->setData(idx, ((i >> shifter) << shifter) | (i & orer), Qt::UserRole);
const auto *channelModel = qobject_cast<QStandardItemModel*>(model);
auto *channelItem = channelModel->item(i);
if(channelItem) {
channelItem->setEnabled(!channelsInUse.contains(i));
}
}
}
QString
Harddrives::BusChannelName(uint8_t bus, uint8_t channel)
{
QString busName;
switch (bus) {
case HDD_BUS_DISABLED:
busName = QString(QObject::tr("Disabled"));
break;
case HDD_BUS_MFM:
busName = QString("MFM/RLL (%1:%2)").arg(channel >> 1).arg(channel & 1);
break;
case HDD_BUS_XTA:
busName = QString("XTA (%1:%2)").arg(channel >> 1).arg(channel & 1);
break;
case HDD_BUS_ESDI:
busName = QString("ESDI (%1:%2)").arg(channel >> 1).arg(channel & 1);
break;
case HDD_BUS_IDE:
busName = QString("IDE (%1:%2)").arg(channel >> 1).arg(channel & 1);
break;
case HDD_BUS_ATAPI:
busName = QString("ATAPI (%1:%2)").arg(channel >> 1).arg(channel & 1);
break;
case HDD_BUS_SCSI:
busName = QString("SCSI (%1:%2)").arg(channel >> 4).arg(channel & 15, 2, 10, QChar('0'));
break;
case CDROM_BUS_MITSUMI:
busName = QString("Mitsumi");
break;
}
return busName;
}
``` | /content/code_sandbox/src/qt/qt_harddrive_common.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,695 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* xkbcommon keyboard input module.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
extern "C" {
#include <xkbcommon/xkbcommon.h>
};
#include <unordered_map>
#include <QtDebug>
#include "evdev_keyboard.hpp"
#define IS_DEC_DIGIT(c) (((c) >= '0') && ((c) <= '9'))
#define IS_HEX_DIGIT(c) (IS_DEC_DIGIT(c) || (((c) >= 'A') && ((c) <= 'F')) || (((c) >= 'a') && ((c) <= 'f')))
static std::unordered_map<std::string, uint16_t> xkb_keycodes = {
{"ESC", 0x01},
{"AE01", 0x02},
{"AE02", 0x03},
{"AE03", 0x04},
{"AE04", 0x05},
{"AE05", 0x06},
{"AE06", 0x07},
{"AE07", 0x08},
{"AE08", 0x09},
{"AE09", 0x0a},
{"AE10", 0x0b},
{"AE11", 0x0c},
{"AE12", 0x0d},
{"BKSP", 0x0e},
{"TAB", 0x0f},
{"AD01", 0x10},
{"AD02", 0x11},
{"AD03", 0x12},
{"AD04", 0x13},
{"AD05", 0x14},
{"AD06", 0x15},
{"AD07", 0x16},
{"AD08", 0x17},
{"AD09", 0x18},
{"AD10", 0x19},
{"AD11", 0x1a},
{"AD12", 0x1b},
{"RTRN", 0x1c},
{"LNFD", 0x1c}, /* linefeed => Enter */
{"LCTL", 0x1d},
{"CTRL", 0x1d},
{"AC01", 0x1e},
{"AC02", 0x1f},
{"AC03", 0x20},
{"AC04", 0x21},
{"AC05", 0x22},
{"AC06", 0x23},
{"AC07", 0x24},
{"AC08", 0x25},
{"AC09", 0x26},
{"AC10", 0x27},
{"AC11", 0x28},
{"TLDE", 0x29},
{"AE00", 0x29}, /* alias of TLDE on keycodes/xfree86 (i.e. X11 forwarding) */
{"LFSH", 0x2a},
{"BKSL", 0x2b},
{"AC12", 0x2b},
{"AB01", 0x2c},
{"AB02", 0x2d},
{"AB03", 0x2e},
{"AB04", 0x2f},
{"AB05", 0x30},
{"AB06", 0x31},
{"AB07", 0x32},
{"AB08", 0x33},
{"AB09", 0x34},
{"AB10", 0x35},
{"RTSH", 0x36},
{"KPMU", 0x37},
{"LALT", 0x38},
{"ALT", 0x38},
{"SPCE", 0x39},
{"CAPS", 0x3a},
{"FK01", 0x3b},
{"FK02", 0x3c},
{"FK03", 0x3d},
{"FK04", 0x3e},
{"FK05", 0x3f},
{"FK06", 0x40},
{"FK07", 0x41},
{"FK08", 0x42},
{"FK09", 0x43},
{"FK10", 0x44},
{"NMLK", 0x45},
{"SCLK", 0x46},
{"FK14", 0x46}, /* F14 => Scroll Lock (for Apple keyboards) */
{"KP7", 0x47},
{"KP8", 0x48},
{"KP9", 0x49},
{"KPSU", 0x4a},
{"KP4", 0x4b},
{"KP5", 0x4c},
{"KP6", 0x4d},
{"KPAD", 0x4e},
{"KP1", 0x4f},
{"KP2", 0x50},
{"KP3", 0x51},
{"KP0", 0x52},
{"KPDL", 0x53},
{"LSGT", 0x56},
{"FK11", 0x57},
{"FK12", 0x58},
{"FK16", 0x5d}, /* F16 => F13 */
{"FK17", 0x5e}, /* F17 => F14 */
{"FK18", 0x5f}, /* F18 => F15 */
/* Japanese keys. */
{"JPCM", 0x5c}, /* Num, */
{"KPDC", 0x5c},
{"HKTG", 0x70}, /* hiragana-katakana toggle */
{"AB11", 0x73}, /* \_ and Brazilian /? */
{"HZTG", 0x76}, /* hankaku-zenkaku toggle */
{"HIRA", 0x77},
{"KATA", 0x78},
{"HENK", 0x79},
{"KANA", 0x79}, /* kana => henkan (for Apple keyboards) */
{"MUHE", 0x7b},
{"EISU", 0x7b}, /* eisu => muhenkan (for Apple keyboards) */
{"AE13", 0x7d}, /* \| */
{"KPPT", 0x7e}, /* Brazilian Num. */
{"I06", 0x7e}, /* alias of KPPT on keycodes/xfree86 (i.e. X11 forwarding) */
/* Korean keys. */
{"HJCV", 0xf1}, /* hancha toggle */
{"HNGL", 0xf2}, /* latin toggle */
{"KPEN", 0x11c},
{"RCTL", 0x11d},
{"KPDV", 0x135},
{"PRSC", 0x137},
{"SYRQ", 0x137},
{"FK13", 0x137}, /* F13 => SysRq (for Apple keyboards) */
{"RALT", 0x138},
{"ALGR", 0x138},
{"LVL3", 0x138}, /* observed on TigerVNC with AltGr-enabled layout */
{"PAUS", 0x145},
{"FK15", 0x145}, /* F15 => Pause (for Apple keyboards) */
{"BRK", 0x145},
{"HOME", 0x147},
{"UP", 0x148},
{"PGUP", 0x149},
{"LEFT", 0x14b},
{"RGHT", 0x14d},
{"END", 0x14f},
{"DOWN", 0x150},
{"PGDN", 0x151},
{"INS", 0x152},
{"DELE", 0x153},
{"LWIN", 0x15b},
{"WIN", 0x15b},
{"LMTA", 0x15b},
{"META", 0x15b},
{"RWIN", 0x15c},
{"RMTA", 0x15c},
{"MENU", 0x15d},
{"COMP", 0x15d}, /* Compose as Menu */
/* Multimedia keys. Same notes as evdev_keyboard apply here. */
{"KPEQ", 0x59}, /* Num= */
{"FRNT", 0x101}, /* # Logitech Task Select */
{"UNDO", 0x108}, /* # */
{"PAST", 0x10a}, /* # Paste */
{"FIND", 0x112}, /* # Logitech */
{"CUT", 0x117}, /* # */
{"COPY", 0x118}, /* # */
{"MUTE", 0x120},
{"VOL-", 0x12e},
{"VOL+", 0x130},
{"HELP", 0x13b},
{"OPEN", 0x13f},
{"POWR", 0x15e},
{"STOP", 0x168},
};
struct xkb_keymap *xkbcommon_keymap = nullptr;
void
xkbcommon_init(struct xkb_keymap *keymap)
{
if (keymap)
xkbcommon_keymap = keymap;
}
void
xkbcommon_close()
{
xkbcommon_keymap = nullptr;
}
uint16_t
xkbcommon_translate(uint32_t keycode)
{
const char *key_name = xkb_keymap_key_get_name(xkbcommon_keymap, keycode);
/* If XKB doesn't know the key name for this keycode, assume an unnamed Ixxx key.
This is useful for older XKB versions with an incomplete evdev keycode map. */
auto key_name_s = key_name ? std::string(key_name) : QString("I%1").arg(keycode).toStdString();
auto ret = xkb_keycodes[key_name_s];
/* Observed with multimedia keys on Windows VcXsrv. */
if (!ret && (key_name_s.length() == 3) && (key_name_s[0] == 'I') && IS_HEX_DIGIT(key_name_s[1]) && IS_HEX_DIGIT(key_name_s[2]))
ret = 0x100 | stoi(key_name_s.substr(1), nullptr, 16);
/* Translate unnamed evdev-specific keycodes. */
if (!ret && (key_name_s.length() >= 2) && (key_name_s[0] == 'I') && IS_DEC_DIGIT(key_name_s[1]))
ret = evdev_translate(stoi(key_name_s.substr(1)) - 8);
if (!ret)
qWarning() << "XKB Keyboard: Unknown key" << QString::number(keycode, 16) << QString::fromStdString(key_name_s);
#if 0
else
qInfo() << "XKB Keyboard: Key" << QString::number(keycode, 16) << QString::fromStdString(key_name_s) << "scancode" << QString::number(ret, 16);
#endif
return ret;
}
``` | /content/code_sandbox/src/qt/xkbcommon_keyboard.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,534 |
```c++
#ifndef QT_SETTINGSDISPLAY_HPP
#define QT_SETTINGSDISPLAY_HPP
#include <QWidget>
#define VIDEOCARD_MAX 2
namespace Ui {
class SettingsDisplay;
}
class SettingsDisplay : public QWidget {
Q_OBJECT
public:
explicit SettingsDisplay(QWidget *parent = nullptr);
~SettingsDisplay();
void save();
public slots:
void onCurrentMachineChanged(int machineId);
private slots:
void on_pushButtonConfigureSecondary_clicked();
private slots:
void on_comboBoxVideoSecondary_currentIndexChanged(int index);
private slots:
void on_checkBoxVoodoo_stateChanged(int state);
void on_checkBoxXga_stateChanged(int state);
void on_comboBoxVideo_currentIndexChanged(int index);
void on_pushButtonConfigureVoodoo_clicked();
void on_pushButtonConfigureXga_clicked();
void on_pushButtonConfigure_clicked();
private:
Ui::SettingsDisplay *ui;
int machineId = 0;
int videoCard[VIDEOCARD_MAX] = { 0, 0 };
};
#endif // QT_SETTINGSDISPLAY_HPP
``` | /content/code_sandbox/src/qt/qt_settingsdisplay.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 218 |
```c++
#ifndef QT_SETTINGSMACHINE_HPP
#define QT_SETTINGSMACHINE_HPP
#include <QWidget>
namespace Ui {
class SettingsMachine;
}
class SettingsMachine : public QWidget {
Q_OBJECT
public:
explicit SettingsMachine(QWidget *parent = nullptr);
~SettingsMachine();
void save();
signals:
void currentMachineChanged(int machineId);
private slots:
void on_pushButtonConfigure_clicked();
private slots:
void on_comboBoxFPU_currentIndexChanged(int index);
private slots:
void on_comboBoxSpeed_currentIndexChanged(int index);
private slots:
void on_comboBoxCPU_currentIndexChanged(int index);
private slots:
void on_comboBoxMachine_currentIndexChanged(int index);
private slots:
void on_comboBoxMachineType_currentIndexChanged(int index);
void on_checkBoxFPUSoftfloat_stateChanged(int state);
private:
Ui::SettingsMachine *ui;
};
#endif // QT_SETTINGSMACHINE_HPP
``` | /content/code_sandbox/src/qt/qt_settingsmachine.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 185 |
```c++
#ifndef QT_MACHINESTATUS_HPP
#define QT_MACHINESTATUS_HPP
#include <QWidget>
#include <QLabel>
#include <QMouseEvent>
#include <QMimeData>
#include <memory>
class QStatusBar;
class ClickableLabel : public QLabel {
Q_OBJECT;
public:
explicit ClickableLabel(QWidget *parent = nullptr)
: QLabel(parent)
{
}
~ClickableLabel() {};
signals:
void clicked(QPoint);
void doubleClicked(QPoint);
void dropped(QString);
protected:
void mousePressEvent(QMouseEvent *event) override { emit clicked(event->globalPos()); }
void mouseDoubleClickEvent(QMouseEvent *event) override { emit doubleClicked(event->globalPos()); }
void dragEnterEvent(QDragEnterEvent *event) override
{
if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
event->setDropAction(Qt::CopyAction);
event->acceptProposedAction();
} else
event->ignore();
}
void dragMoveEvent(QDragMoveEvent *event) override
{
if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) {
event->setDropAction(Qt::CopyAction);
event->acceptProposedAction();
} else
event->ignore();
}
void dropEvent(QDropEvent *event) override
{
if (event->dropAction() == Qt::CopyAction) {
emit dropped(event->mimeData()->urls()[0].toLocalFile());
} else
event->ignore();
}
};
class MachineStatus : public QObject {
Q_OBJECT
public:
explicit MachineStatus(QObject *parent = nullptr);
~MachineStatus();
static bool hasCassette();
static bool hasIDE();
static bool hasSCSI();
static void iterateFDD(const std::function<void(int i)> &cb);
static void iterateCDROM(const std::function<void(int i)> &cb);
static void iterateZIP(const std::function<void(int i)> &cb);
static void iterateMO(const std::function<void(int i)> &cb);
static void iterateNIC(const std::function<void(int i)> &cb);
QString getMessage();
void clearActivity();
public slots:
void refresh(QStatusBar *sbar);
void message(const QString &msg);
void updateTip(int tag);
void refreshIcons();
private:
struct States;
std::unique_ptr<States> d;
QTimer *refreshTimer;
};
#endif // QT_MACHINESTATUS_HPP
``` | /content/code_sandbox/src/qt/qt_machinestatus.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 548 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Common storage devices module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
*
*/
#include "qt_models_common.hpp"
#include <QAbstractItemModel>
int
Models::AddEntry(QAbstractItemModel *model, const QString &displayRole, int userRole)
{
int row = model->rowCount();
model->insertRow(row);
auto idx = model->index(row, 0);
model->setData(idx, displayRole, Qt::DisplayRole);
model->setData(idx, userRole, Qt::UserRole);
return row;
}
``` | /content/code_sandbox/src/qt/qt_models_common.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 200 |
```c++
#ifndef QT_SOUNDGAIN_HPP
#define QT_SOUNDGAIN_HPP
#include <QDialog>
namespace Ui {
class SoundGain;
}
class SoundGain : public QDialog {
Q_OBJECT
public:
explicit SoundGain(QWidget *parent = nullptr);
~SoundGain();
private slots:
void on_verticalSlider_valueChanged(int value);
void on_SoundGain_rejected();
private:
Ui::SoundGain *ui;
int sound_gain_orig;
};
#endif // QT_SOUNDGAIN_HPP
``` | /content/code_sandbox/src/qt/qt_soundgain.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 104 |
```c++
#ifndef QT_MCADEVICELIST_HPP
#define QT_MCADEVICELIST_HPP
#include <QDialog>
namespace Ui {
class MCADeviceList;
}
class MCADeviceList : public QDialog {
Q_OBJECT
public:
explicit MCADeviceList(QWidget *parent = nullptr);
~MCADeviceList();
private:
Ui::MCADeviceList *ui;
};
#endif // QT_MCADEVICELIST_HPP
``` | /content/code_sandbox/src/qt/qt_mcadevicelist.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 91 |
```c++
#ifndef QT_MAINWINDOW_HPP
#define QT_MAINWINDOW_HPP
#include <QMainWindow>
#include <QLabel>
#include <QEvent>
#include <QFocusEvent>
#include <memory>
#include <array>
#include <atomic>
class MediaMenu;
class RendererStack;
namespace Ui {
class MainWindow;
}
class MachineStatus;
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void showMessage(int flags, const QString &header, const QString &message);
void getTitle(wchar_t *title);
void blitToWidget(int x, int y, int w, int h, int monitor_index);
QSize getRenderWidgetSize();
void setSendKeyboardInput(bool enabled);
void checkFullscreenHotkey();
std::array<std::unique_ptr<RendererStack>, 8> renderers;
signals:
void paint(const QImage &image);
void resizeContents(int w, int h);
void resizeContentsMonitor(int w, int h, int monitor_index);
void statusBarMessage(const QString &msg);
void updateStatusBarPanes();
void updateStatusBarActivity(int tag, bool active);
void updateStatusBarEmpty(int tag, bool empty);
void updateStatusBarTip(int tag);
void updateMenuResizeOptions();
void updateWindowRememberOption();
void initRendererMonitor(int monitor_index);
void destroyRendererMonitor(int monitor_index);
void initRendererMonitorForNonQtThread(int monitor_index);
void destroyRendererMonitorForNonQtThread(int monitor_index);
void hardResetCompleted();
void setTitle(const QString &title);
void setFullscreen(bool state);
void setMouseCapture(bool state);
void showMessageForNonQtThread(int flags, const QString &header, const QString &message, std::atomic_bool* done);
void getTitleForNonQtThread(wchar_t *title);
public slots:
void showSettings();
void hardReset();
void togglePause();
void initRendererMonitorSlot(int monitor_index);
void destroyRendererMonitorSlot(int monitor_index);
void updateUiPauseState();
private slots:
void on_actionFullscreen_triggered();
void on_actionSettings_triggered();
void on_actionExit_triggered();
void on_actionAuto_pause_triggered();
void on_actionPause_triggered();
void on_actionCtrl_Alt_Del_triggered();
void on_actionCtrl_Alt_Esc_triggered();
void on_actionHard_Reset_triggered();
void on_actionRight_CTRL_is_left_ALT_triggered();
static void on_actionKeyboard_requires_capture_triggered();
void on_actionResizable_window_triggered(bool checked);
void on_actionInverted_VGA_monitor_triggered();
void on_action0_5x_triggered();
void on_action1x_triggered();
void on_action1_5x_triggered();
void on_action2x_triggered();
void on_action3x_triggered();
void on_action4x_triggered();
void on_action5x_triggered();
void on_action6x_triggered();
void on_action7x_triggered();
void on_action8x_triggered();
void on_actionLinear_triggered();
void on_actionNearest_triggered();
void on_actionFullScreen_int_triggered();
void on_actionFullScreen_int43_triggered();
void on_actionFullScreen_keepRatio_triggered();
void on_actionFullScreen_43_triggered();
void on_actionFullScreen_stretch_triggered();
void on_actionWhite_monitor_triggered();
void on_actionGreen_monitor_triggered();
void on_actionAmber_monitor_triggered();
void on_actionRGB_Grayscale_triggered();
void on_actionRGB_Color_triggered();
void on_actionAverage_triggered();
void on_actionBT709_HDTV_triggered();
void on_actionBT601_NTSC_PAL_triggered();
void on_actionDocumentation_triggered();
void on_actionAbout_86Box_triggered();
void on_actionAbout_Qt_triggered();
void on_actionForce_4_3_display_ratio_triggered();
void on_actionChange_contrast_for_monochrome_display_triggered();
void on_actionCGA_PCjr_Tandy_EGA_S_VGA_overscan_triggered();
void on_actionRemember_size_and_position_triggered();
void on_actionSpecify_dimensions_triggered();
void on_actionHiDPI_scaling_triggered();
void on_actionHide_status_bar_triggered();
void on_actionHide_tool_bar_triggered();
void on_actionUpdate_status_bar_icons_triggered();
void on_actionTake_screenshot_triggered();
void on_actionSound_gain_triggered();
void on_actionPreferences_triggered();
void on_actionEnable_Discord_integration_triggered(bool checked);
void on_actionRenderer_options_triggered();
void refreshMediaMenu();
void showMessage_(int flags, const QString &header, const QString &message, std::atomic_bool* done = nullptr);
void getTitle_(wchar_t *title);
void on_actionMCA_devices_triggered();
protected:
void keyPressEvent(QKeyEvent *event) override;
void keyReleaseEvent(QKeyEvent *event) override;
void focusInEvent(QFocusEvent *event) override;
void focusOutEvent(QFocusEvent *event) override;
bool eventFilter(QObject *receiver, QEvent *event) override;
void showEvent(QShowEvent *event) override;
void closeEvent(QCloseEvent *event) override;
void changeEvent(QEvent *event) override;
private slots:
void on_actionPen_triggered();
private slots:
void on_actionCursor_Puck_triggered();
void on_actionACPI_Shutdown_triggered();
private slots:
void on_actionShow_non_primary_monitors_triggered();
void on_actionOpen_screenshots_folder_triggered();
void on_actionApply_fullscreen_stretch_mode_when_maximized_triggered(bool checked);
private:
Ui::MainWindow *ui;
std::unique_ptr<MachineStatus> status;
std::shared_ptr<MediaMenu> mm;
void processKeyboardInput(bool down, uint32_t keycode);
#ifdef Q_OS_MACOS
uint32_t last_modifiers = 0;
void processMacKeyboardInput(bool down, const QKeyEvent *event);
#endif
/* If main window should send keyboard input */
bool send_keyboard_input = true;
bool shownonce = false;
bool resizableonce = false;
bool vnc_enabled = false;
/* Full screen ON and OFF signals */
bool fs_on_signal = false;
bool fs_off_signal = false;
friend class SpecifyDimensions;
friend class ProgSettings;
friend class RendererCommon;
friend class RendererStack; // For UI variable access by non-primary renderer windows.
};
#endif // QT_MAINWINDOW_HPP
``` | /content/code_sandbox/src/qt/qt_mainwindow.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,355 |
```c++
#ifndef QT_SETTINGSPORTS_HPP
#define QT_SETTINGSPORTS_HPP
#include <QWidget>
namespace Ui {
class SettingsPorts;
}
class SettingsPorts : public QWidget {
Q_OBJECT
public:
explicit SettingsPorts(QWidget *parent = nullptr);
~SettingsPorts();
void save();
#if 0
private slots:
void on_checkBoxSerialPassThru7_clicked(bool checked);
private slots:
void on_checkBoxSerialPassThru6_clicked(bool checked);
private slots:
void on_checkBoxSerialPassThru5_clicked(bool checked);
#endif
private slots:
void on_checkBoxSerialPassThru4_clicked(bool checked);
private slots:
void on_checkBoxSerialPassThru3_clicked(bool checked);
private slots:
void on_checkBoxSerialPassThru2_clicked(bool checked);
private slots:
void on_checkBoxSerialPassThru1_clicked(bool checked);
private slots:
void on_pushButtonSerialPassThru7_clicked();
private slots:
void on_pushButtonSerialPassThru6_clicked();
private slots:
void on_pushButtonSerialPassThru5_clicked();
private slots:
void on_pushButtonSerialPassThru4_clicked();
private slots:
void on_pushButtonSerialPassThru3_clicked();
private slots:
void on_pushButtonSerialPassThru2_clicked();
private slots:
void on_pushButtonSerialPassThru1_clicked();
private slots:
void on_checkBoxParallel4_stateChanged(int arg1);
void on_checkBoxParallel3_stateChanged(int arg1);
void on_checkBoxParallel2_stateChanged(int arg1);
void on_checkBoxParallel1_stateChanged(int arg1);
private:
Ui::SettingsPorts *ui;
};
#endif // QT_SETTINGSPORTS_HPP
``` | /content/code_sandbox/src/qt/qt_settingsports.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 356 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Common UI functions.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
*
*/
#include <cstdint>
#include <QDebug>
#include <QThread>
#include <QMessageBox>
#include <QStatusBar>
#include "qt_mainwindow.hpp"
#include "qt_machinestatus.hpp"
MainWindow *main_window = nullptr;
static QString sb_text;
static QString sb_buguitext;
static QString sb_mt32lcdtext;
extern "C" {
#include "86box/86box.h"
#include <86box/plat.h>
#include <86box/ui.h>
#include <86box/mouse.h>
#include <86box/timer.h>
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/fdd.h>
#include <86box/hdc.h>
#include <86box/scsi.h>
#include <86box/scsi_device.h>
#include <86box/cartridge.h>
#include <86box/cassette.h>
#include <86box/cdrom.h>
#include <86box/zip.h>
#include <86box/mo.h>
#include <86box/hdd.h>
#include <86box/thread.h>
#include <86box/network.h>
#include <86box/machine_status.h>
void
plat_delay_ms(uint32_t count)
{
QThread::msleep(count);
}
wchar_t *
ui_window_title(wchar_t *str)
{
if (str == nullptr) {
static wchar_t title[512] = { 0 };
main_window->getTitle(title);
str = title;
} else
emit main_window->setTitle(QString::fromWCharArray(str));
return str;
}
void
ui_hard_reset_completed()
{
emit main_window->hardResetCompleted();
}
extern "C" void
qt_blit(int x, int y, int w, int h, int monitor_index)
{
main_window->blitToWidget(x, y, w, h, monitor_index);
}
extern "C" int vid_resize;
void
plat_resize_request(int w, int h, int monitor_index)
{
if (video_fullscreen || is_quit)
return;
if (vid_resize & 2) {
plat_resize(fixed_size_x, fixed_size_y, monitor_index);
} else {
plat_resize(w, h, monitor_index);
}
}
void
plat_resize(int w, int h, int monitor_index)
{
if (monitor_index >= 1)
main_window->resizeContentsMonitor(w, h, monitor_index);
else
main_window->resizeContents(w, h);
}
void
plat_mouse_capture(int on)
{
if (!kbd_req_capture && (mouse_type == MOUSE_TYPE_NONE) && !machine_has_mouse())
return;
main_window->setMouseCapture(on > 0 ? true : false);
}
int
ui_msgbox_header(int flags, void *header, void *message)
{
const auto hdr = (flags & MBX_ANSI) ? QString(static_cast<char *>(header)) :
QString::fromWCharArray(static_cast<const wchar_t *>(header));
const auto msg = (flags & MBX_ANSI) ? QString(static_cast<char *>(message)) :
QString::fromWCharArray(static_cast<const wchar_t *>(message));
// any error in early init
if (main_window == nullptr) {
QMessageBox msgBox(QMessageBox::Icon::Critical, hdr, msg);
msgBox.setTextFormat(Qt::TextFormat::RichText);
msgBox.exec();
} else {
// else scope it to main_window
main_window->showMessage(flags, hdr, msg);
}
return 0;
}
void
ui_init_monitor(int monitor_index)
{
if (QThread::currentThread() == main_window->thread()) {
emit main_window->initRendererMonitor(monitor_index);
} else
emit main_window->initRendererMonitorForNonQtThread(monitor_index);
}
void
ui_deinit_monitor(int monitor_index)
{
if (QThread::currentThread() == main_window->thread()) {
emit main_window->destroyRendererMonitor(monitor_index);
} else
emit main_window->destroyRendererMonitorForNonQtThread(monitor_index);
}
int
ui_msgbox(int flags, void *message)
{
return ui_msgbox_header(flags, nullptr, message);
}
void
ui_sb_update_text()
{
emit main_window->statusBarMessage(!sb_mt32lcdtext.isEmpty() ? sb_mt32lcdtext : sb_text.isEmpty() ? sb_buguitext
: sb_text);
}
void
ui_sb_mt32lcd(char *str)
{
sb_mt32lcdtext = QString(str);
ui_sb_update_text();
}
void
ui_sb_set_text_w(wchar_t *wstr)
{
sb_text = QString::fromWCharArray(wstr);
ui_sb_update_text();
}
void
ui_sb_set_text(char *str)
{
sb_text = str;
ui_sb_update_text();
}
void
ui_sb_update_tip(int arg)
{
main_window->updateStatusBarTip(arg);
}
void
ui_sb_update_panes()
{
main_window->updateStatusBarPanes();
}
void
ui_sb_bugui(char *str)
{
sb_buguitext = str;
ui_sb_update_text();
}
void
ui_sb_set_ready(int ready)
{
if (ready == 0) {
ui_sb_bugui(nullptr);
ui_sb_set_text(nullptr);
}
}
void
ui_sb_update_icon_state(int tag, int state)
{
const auto temp = static_cast<unsigned int>(tag);
const int category = static_cast<int>(temp & 0xfffffff0);
const int item = tag & 0xf;
switch (category) {
default:
break;
case SB_CASSETTE:
machine_status.cassette.empty = state > 0 ? true : false;
break;
case SB_CARTRIDGE:
machine_status.cartridge[item].empty = state > 0 ? true : false;
break;
case SB_FLOPPY:
machine_status.fdd[item].empty = state > 0 ? true : false;
break;
case SB_CDROM:
machine_status.cdrom[item].empty = state > 0 ? true : false;
break;
case SB_ZIP:
machine_status.zip[item].empty = state > 0 ? true : false;
break;
case SB_MO:
machine_status.mo[item].empty = state > 0 ? true : false;
break;
case SB_HDD:
break;
case SB_NETWORK:
machine_status.net[item].empty = state > 0 ? true : false;
break;
case SB_SOUND:
case SB_TEXT:
break;
}
}
void
ui_sb_update_icon(int tag, int active)
{
const auto temp = static_cast<unsigned int>(tag);
const int category = static_cast<int>(temp & 0xfffffff0);
const int item = tag & 0xf;
switch (category) {
default:
case SB_CASSETTE:
case SB_CARTRIDGE:
break;
case SB_FLOPPY:
machine_status.fdd[item].active = active > 0 ? true : false;
break;
case SB_CDROM:
machine_status.cdrom[item].active = active > 0 ? true : false;
break;
case SB_ZIP:
machine_status.zip[item].active = active > 0 ? true : false;
break;
case SB_MO:
machine_status.mo[item].active = active > 0 ? true : false;
break;
case SB_HDD:
machine_status.hdd[item].active = active > 0 ? true : false;
break;
case SB_NETWORK:
machine_status.net[item].active = active > 0 ? true : false;
break;
case SB_SOUND:
case SB_TEXT:
break;
}
}
}
``` | /content/code_sandbox/src/qt/qt_ui.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,768 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Win32 CD-ROM support via IOCTL.
*
*
*
* Authors: TheCollector1995, <mariogplayer@gmail.com>,
* Miran Grca, <mgrca8@gmail.com>
*
*/
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/scsi_device.h>
#include <86box/cdrom.h>
#include <86box/plat_unused.h>
#include <86box/plat_cdrom.h>
/* The addresses sent from the guest are absolute, ie. a LBA of 0 corresponds to a MSF of 00:00:00. Otherwise, the counter displayed by the guest is wrong:
there is a seeming 2 seconds in which audio plays but counter does not move, while a data track before audio jumps to 2 seconds before the actual start
of the audio while audio still plays. With an absolute conversion, the counter is fine. */
#define MSFtoLBA(m, s, f) ((((m * 60) + s) * 75) + f)
static int toc_valid = 0;
#ifdef ENABLE_DUMMY_CDROM_IOCTL_LOG
int dummy_cdrom_ioctl_do_log = ENABLE_DUMMY_CDROM_IOCTL_LOG;
void
dummy_cdrom_ioctl_log(const char *fmt, ...)
{
va_list ap;
if (dummy_cdrom_ioctl_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define dummy_cdrom_ioctl_log(fmt, ...)
#endif
static int
plat_cdrom_open(void)
{
return 0;
}
static int
plat_cdrom_load(void)
{
return 0;
}
static void
plat_cdrom_read_toc(void)
{
if (!toc_valid)
toc_valid = 1;
}
int
plat_cdrom_is_track_audio(uint32_t sector)
{
plat_cdrom_read_toc();
const int ret = 0;
dummy_cdrom_ioctl_log("plat_cdrom_is_track_audio(%08X): %i\n", sector, ret);
return ret;
}
int
plat_cdrom_is_track_pre(uint32_t sector)
{
plat_cdrom_read_toc();
const int ret = 0;
dummy_cdrom_ioctl_log("plat_cdrom_is_track_audio(%08X): %i\n", sector, ret);
return ret;
}
uint32_t
plat_cdrom_get_track_start(uint32_t sector, uint8_t *attr, uint8_t *track)
{
plat_cdrom_read_toc();
return 0x00000000;
}
uint32_t
plat_cdrom_get_last_block(void)
{
plat_cdrom_read_toc();
return 0x00000000;
}
int
plat_cdrom_ext_medium_changed(void)
{
int ret = 0;
dummy_cdrom_ioctl_log("plat_cdrom_ext_medium_changed(): %i\n", ret);
return ret;
}
void
plat_cdrom_get_audio_tracks(int *st_track, int *end, TMSF *lead_out)
{
plat_cdrom_read_toc();
*st_track = 1;
*end = 1;
lead_out->min = 0;
lead_out->sec = 0;
lead_out->fr = 2;
dummy_cdrom_ioctl_log("plat_cdrom_get_audio_tracks(): %02i, %02i, %02i:%02i:%02i\n",
*st_track, *end, lead_out->min, lead_out->sec, lead_out->fr);
}
/* This replaces both Info and EndInfo, they are specified by a variable. */
int
plat_cdrom_get_audio_track_info(UNUSED(int end), int track, int *track_num, TMSF *start, uint8_t *attr)
{
plat_cdrom_read_toc();
if ((track < 1) || (track == 0xaa)) {
dummy_cdrom_ioctl_log("plat_cdrom_get_audio_track_info(%02i)\n", track);
return 0;
}
start->min = 0;
start->sec = 0;
start->fr = 2;
*track_num = 1;
*attr = 0x14;
dummy_cdrom_ioctl_log("plat_cdrom_get_audio_track_info(%02i): %02i:%02i:%02i, %02i, %02X\n",
track, start->min, start->sec, start->fr, *track_num, *attr);
return 1;
}
/* TODO: See if track start is adjusted by 150 or not. */
int
plat_cdrom_get_audio_sub(UNUSED(uint32_t sector), uint8_t *attr, uint8_t *track, uint8_t *index, TMSF *rel_pos, TMSF *abs_pos)
{
*track = 1;
*attr = 0x14;
*index = 1;
rel_pos->min = 0;
rel_pos->sec = 0;
rel_pos->fr = 0;
abs_pos->min = 0;
abs_pos->sec = 0;
abs_pos->fr = 2;
dummy_cdrom_ioctl_log("plat_cdrom_get_audio_sub(): %02i, %02X, %02i, %02i:%02i:%02i, %02i:%02i:%02i\n",
*track, *attr, *index, rel_pos->min, rel_pos->sec, rel_pos->fr, abs_pos->min, abs_pos->sec, abs_pos->fr);
return 1;
}
int
plat_cdrom_get_sector_size(UNUSED(uint32_t sector))
{
dummy_cdrom_ioctl_log("BytesPerSector=2048\n");
return 2048;
}
int
plat_cdrom_read_sector(uint8_t *buffer, int raw, uint32_t sector)
{
plat_cdrom_open();
if (raw) {
dummy_cdrom_ioctl_log("Raw\n");
/* Raw */
} else {
dummy_cdrom_ioctl_log("Cooked\n");
/* Cooked */
}
plat_cdrom_close();
dummy_cdrom_ioctl_log("ReadSector status=%d, sector=%d, size=%" PRId64 ".\n", status, sector, (long long) size);
return 0;
}
void
plat_cdrom_eject(void)
{
plat_cdrom_open();
plat_cdrom_close();
}
void
plat_cdrom_close(void)
{
}
int
plat_cdrom_set_drive(const char *drv)
{
plat_cdrom_close();
toc_valid = 0;
plat_cdrom_load();
return 1;
}
``` | /content/code_sandbox/src/qt/dummy_cdrom_ioctl.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,545 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Display settings UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
*
*/
#include "qt_settingsdisplay.hpp"
#include "ui_qt_settingsdisplay.h"
#include <QDebug>
extern "C" {
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/machine.h>
#include <86box/video.h>
#include <86box/vid_xga_device.h>
}
#include "qt_deviceconfig.hpp"
#include "qt_models_common.hpp"
SettingsDisplay::SettingsDisplay(QWidget *parent)
: QWidget(parent)
, ui(new Ui::SettingsDisplay)
{
ui->setupUi(this);
for (uint8_t i = 0; i < GFXCARD_MAX; i ++)
videoCard[i] = gfxcard[i];
onCurrentMachineChanged(machine);
}
SettingsDisplay::~SettingsDisplay()
{
delete ui;
}
void
SettingsDisplay::save()
{
gfxcard[0] = ui->comboBoxVideo->currentData().toInt();
// TODO
for (uint8_t i = 1; i < GFXCARD_MAX; i ++)
gfxcard[i] = ui->comboBoxVideoSecondary->currentData().toInt();
voodoo_enabled = ui->checkBoxVoodoo->isChecked() ? 1 : 0;
ibm8514_standalone_enabled = ui->checkBox8514->isChecked() ? 1 : 0;
xga_standalone_enabled = ui->checkBoxXga->isChecked() ? 1 : 0;
}
void
SettingsDisplay::onCurrentMachineChanged(int machineId)
{
// win_settings_video_proc, WM_INITDIALOG
this->machineId = machineId;
auto curVideoCard = videoCard[0];
auto *model = ui->comboBoxVideo->model();
auto removeRows = model->rowCount();
int c = 0;
int selectedRow = 0;
while (true) {
/* Skip "internal" if machine doesn't have it. */
if ((c == 1) && (machine_has_flags(machineId, MACHINE_VIDEO) == 0)) {
c++;
continue;
}
const device_t *video_dev = video_card_getdevice(c);
QString name = DeviceConfig::DeviceName(video_dev, video_get_internal_name(c), 1);
if (name.isEmpty()) {
break;
}
if (video_card_available(c) && device_is_valid(video_dev, machineId)) {
int row = Models::AddEntry(model, name, c);
if (c == curVideoCard) {
selectedRow = row - removeRows;
}
}
c++;
}
model->removeRows(0, removeRows);
if (machine_has_flags(machineId, MACHINE_VIDEO_ONLY) > 0) {
ui->comboBoxVideo->setEnabled(false);
ui->comboBoxVideoSecondary->setEnabled(false);
ui->pushButtonConfigureSecondary->setEnabled(false);
selectedRow = 1;
} else {
ui->comboBoxVideo->setEnabled(true);
ui->comboBoxVideoSecondary->setEnabled(true);
ui->pushButtonConfigureSecondary->setEnabled(true);
}
ui->comboBoxVideo->setCurrentIndex(selectedRow);
// TODO
for (uint8_t i = 1; i < GFXCARD_MAX; i ++)
if (gfxcard[i] == 0)
ui->pushButtonConfigureSecondary->setEnabled(false);
}
void
SettingsDisplay::on_pushButtonConfigure_clicked()
{
int videoCard = ui->comboBoxVideo->currentData().toInt();
auto *device = video_card_getdevice(videoCard);
if (videoCard == VID_INTERNAL)
device = machine_get_vid_device(machineId);
DeviceConfig::ConfigureDevice(device, 0, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsDisplay::on_pushButtonConfigureVoodoo_clicked()
{
DeviceConfig::ConfigureDevice(&voodoo_device, 0, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsDisplay::on_pushButtonConfigureXga_clicked()
{
if (machine_has_bus(machineId, MACHINE_BUS_MCA) > 0) {
DeviceConfig::ConfigureDevice(&xga_device, 0, qobject_cast<Settings *>(Settings::settings));
} else {
DeviceConfig::ConfigureDevice(&xga_isa_device, 0, qobject_cast<Settings *>(Settings::settings));
}
}
void
SettingsDisplay::on_comboBoxVideo_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
static QRegularExpression voodooRegex("3dfx|voodoo|banshee", QRegularExpression::CaseInsensitiveOption);
auto curVideoCard_2 = videoCard[1];
videoCard[0] = ui->comboBoxVideo->currentData().toInt();
if (videoCard[0] == VID_INTERNAL)
ui->pushButtonConfigure->setEnabled(machine_has_flags(machineId, MACHINE_VIDEO) &&
device_has_config(machine_get_vid_device(machineId)));
else
ui->pushButtonConfigure->setEnabled(video_card_has_config(videoCard[0]) > 0);
bool machineHasPci = machine_has_bus(machineId, MACHINE_BUS_PCI) > 0;
ui->pushButtonConfigureVoodoo->setEnabled(machineHasPci && ui->checkBoxVoodoo->isChecked());
bool machineHasIsa16 = machine_has_bus(machineId, MACHINE_BUS_ISA16) > 0;
bool machineHasMca = machine_has_bus(machineId, MACHINE_BUS_MCA) > 0;
bool videoCardHas8514 = ((videoCard[0] == VID_INTERNAL) ? machine_has_flags(machineId, MACHINE_VIDEO_8514A) : (video_card_get_flags(videoCard[0]) == VIDEO_FLAG_TYPE_8514));
bool videoCardHasXga = ((videoCard[0] == VID_INTERNAL) ? machine_has_flags(machineId, MACHINE_VIDEO_XGA) : (video_card_get_flags(videoCard[0]) == VIDEO_FLAG_TYPE_XGA));
bool machineSupports8514 = ((machineHasIsa16 || machineHasMca) && !videoCardHas8514);
bool machineSupportsXga = (((machineHasIsa16 && device_available(&xga_isa_device)) || (machineHasMca && device_available(&xga_device))) && !videoCardHasXga);
ui->checkBox8514->setEnabled(machineSupports8514);
ui->checkBox8514->setChecked(ibm8514_standalone_enabled && machineSupports8514);
ui->checkBoxXga->setEnabled(machineSupportsXga);
ui->checkBoxXga->setChecked(xga_standalone_enabled && machineSupportsXga);
ui->pushButtonConfigureXga->setEnabled(ui->checkBoxXga->isEnabled() && ui->checkBoxXga->isChecked());
int c = 2;
ui->comboBoxVideoSecondary->clear();
ui->comboBoxVideoSecondary->addItem(QObject::tr("None"), 0);
ui->comboBoxVideoSecondary->setCurrentIndex(0);
// TODO: Implement support for selecting non-MDA secondary cards properly when MDA cards are the primary ones.
if (video_card_get_flags(videoCard[0]) == VIDEO_FLAG_TYPE_MDA) {
ui->comboBoxVideoSecondary->setCurrentIndex(0);
return;
}
while (true) {
const device_t *video_dev = video_card_getdevice(c);
QString name = DeviceConfig::DeviceName(video_dev, video_get_internal_name(c), 1);
if (name.isEmpty()) {
break;
}
int primaryFlags = video_card_get_flags(videoCard[0]);
int secondaryFlags = video_card_get_flags(c);
if (video_card_available(c)
&& device_is_valid(video_dev, machineId)
&& !((secondaryFlags == primaryFlags) && (secondaryFlags != VIDEO_FLAG_TYPE_SPECIAL))
&& !(((primaryFlags == VIDEO_FLAG_TYPE_8514) || (primaryFlags == VIDEO_FLAG_TYPE_XGA)) && (secondaryFlags != VIDEO_FLAG_TYPE_MDA) && (secondaryFlags != VIDEO_FLAG_TYPE_SPECIAL))
&& !((primaryFlags != VIDEO_FLAG_TYPE_MDA) && (primaryFlags != VIDEO_FLAG_TYPE_SPECIAL) && ((secondaryFlags == VIDEO_FLAG_TYPE_8514) || (secondaryFlags == VIDEO_FLAG_TYPE_XGA)))) {
ui->comboBoxVideoSecondary->addItem(name, c);
if (c == curVideoCard_2)
ui->comboBoxVideoSecondary->setCurrentIndex(ui->comboBoxVideoSecondary->count() - 1);
}
c++;
}
if ((videoCard[1] == 0) || (machine_has_flags(machineId, MACHINE_VIDEO_ONLY) > 0)) {
ui->comboBoxVideoSecondary->setCurrentIndex(0);
ui->pushButtonConfigureSecondary->setEnabled(false);
}
// Is the currently selected video card a voodoo?
if (ui->comboBoxVideo->currentText().contains(voodooRegex)) {
// Get the name of the video card currently in use
const device_t *video_dev = video_card_getdevice(gfxcard[0]);
const QString currentVideoName = DeviceConfig::DeviceName(video_dev, video_get_internal_name(gfxcard[0]), 1);
// Is it a voodoo?
const bool currentCardIsVoodoo = currentVideoName.contains(voodooRegex);
// Don't uncheck if
// * Current card is voodoo
// * Add-on voodoo was manually overridden in config
if (ui->checkBoxVoodoo->isChecked() && !currentCardIsVoodoo) {
// Otherwise, uncheck the add-on voodoo when a main voodoo is selected
ui->checkBoxVoodoo->setCheckState(Qt::Unchecked);
}
ui->checkBoxVoodoo->setDisabled(true);
} else {
ui->checkBoxVoodoo->setEnabled(machineHasPci);
if (machineHasPci) {
ui->checkBoxVoodoo->setChecked(voodoo_enabled);
}
}
}
void
SettingsDisplay::on_checkBoxVoodoo_stateChanged(int state)
{
ui->pushButtonConfigureVoodoo->setEnabled(state == Qt::Checked);
}
void
SettingsDisplay::on_checkBoxXga_stateChanged(int state)
{
ui->pushButtonConfigureXga->setEnabled(state == Qt::Checked);
}
void
SettingsDisplay::on_comboBoxVideoSecondary_currentIndexChanged(int index)
{
if (index < 0) {
ui->pushButtonConfigureSecondary->setEnabled(false);
return;
}
videoCard[1] = ui->comboBoxVideoSecondary->currentData().toInt();
ui->pushButtonConfigureSecondary->setEnabled(index != 0 && video_card_has_config(videoCard[1]) > 0);
}
void
SettingsDisplay::on_pushButtonConfigureSecondary_clicked()
{
auto *device = video_card_getdevice(ui->comboBoxVideoSecondary->currentData().toInt());
DeviceConfig::ConfigureDevice(device, 0, qobject_cast<Settings *>(Settings::settings));
}
``` | /content/code_sandbox/src/qt/qt_settingsdisplay.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,410 |
```c++
static std::array<uint32_t, 127> cocoa_keycodes = { /* key names in parentheses are not declared by Apple headers */
0x1e, /* ANSI_A */
0x1f, /* ANSI_S */
0x20, /* ANSI_D */
0x21, /* ANSI_F */
0x23, /* ANSI_H */
0x22, /* ANSI_G */
0x2c, /* ANSI_Z */
0x2d, /* ANSI_X */
0x2e, /* ANSI_C */
0x2f, /* ANSI_V */
0x56, /* ISO_Section */
0x30, /* ANSI_B */
0x10, /* ANSI_Q */
0x11, /* ANSI_W */
0x12, /* ANSI_E */
0x13, /* ANSI_R */
0x15, /* ANSI_Y */
0x14, /* ANSI_T */
0x02, /* ANSI_1 */
0x03, /* ANSI_2 */
0x04, /* ANSI_3 */
0x05, /* ANSI_4 */
0x07, /* ANSI_6 */
0x06, /* ANSI_5 */
0x0d, /* ANSI_Equal */
0x0a, /* ANSI_9 */
0x08, /* ANSI_7 */
0x0c, /* ANSI_Minus */
0x09, /* ANSI_8 */
0x0b, /* ANSI_0 */
0x1b, /* ANSI_RightBracket */
0x18, /* ANSI_O */
0x16, /* ANSI_U */
0x1a, /* ANSI_LeftBracket */
0x17, /* ANSI_I */
0x19, /* ANSI_P */
0x1c, /* Return */
0x26, /* ANSI_L */
0x24, /* ANSI_J */
0x28, /* ANSI_Quote */
0x25, /* ANSI_K */
0x27, /* ANSI_Semicolon */
0x2b, /* ANSI_Backslash */
0x33, /* ANSI_Comma */
0x35, /* ANSI_Slash */
0x31, /* ANSI_N */
0x32, /* ANSI_M */
0x34, /* ANSI_Period */
0x0f, /* Tab */
0x39, /* Space */
0x29, /* ANSI_Grave */
0x0e, /* Delete => Backspace */
0x11c, /* (ANSI_KeypadEnter) */
0x01, /* Escape */
0x15c, /* (RightCommand) => Right Windows */
0x15b, /* (Left)Command => Left Windows */
0x2a, /* Shift */
0x3a, /* CapsLock */
0x38, /* Option */
0x1d, /* Control */
0x36, /* RightShift */
0x138, /* RightOption */
0x11d, /* RightControl */
0x15c, /* Function */
0x5e, /* F17 => F14 */
0x53, /* ANSI_KeypadDecimal */
0,
0x37, /* ANSI_KeypadMultiply */
0,
0x4e, /* ANSI_KeypadPlus */
0,
0x45, /* ANSI_KeypadClear => Num Lock (location equivalent) */
0x130, /* VolumeUp */
0x12e, /* VolumeDown */
0x120, /* Mute */
0x135, /* ANSI_KeypadDivide */
0x11c, /* ANSI_KeypadEnter */
0,
0x4a, /* ANSI_KeypadMinus */
0x5f, /* F18 => F15 */
0, /* F19 */
0x59, /* ANSI_KeypadEquals */
0x52, /* ANSI_Keypad0 */
0x4f, /* ANSI_Keypad1 */
0x50, /* ANSI_Keypad2 */
0x51, /* ANSI_Keypad3 */
0x4b, /* ANSI_Keypad4 */
0x4c, /* ANSI_Keypad5 */
0x4d, /* ANSI_Keypad6 */
0x47, /* ANSI_Keypad7 */
0, /* F20 */
0x48, /* ANSI_Keypad8 */
0x49, /* ANSI_Keypad9 */
0x7d, /* JIS_Yen */
0x73, /* JIS_Underscore */
0x5c, /* JIS_KeypadComma */
0x3f, /* F5 */
0x40, /* F6 */
0x41, /* F7 */
0x3d, /* F3 */
0x42, /* F8 */
0x43, /* F9 */
0x7b, /* JIS_Eisu => muhenkan (location equivalent) */
0x57, /* F11 */
0x79, /* JIS_Kana => henkan (location equivalent) */
0x137, /* F13 => SysRq (location equivalent) */
0x5d, /* F16 => F13 */
0x46, /* F14 => Scroll Lock (location equivalent) */
0,
0x44, /* F10 */
0x15d, /* (Menu) */
0x58, /* F12 */
0,
0x145, /* F15 => Pause (location equivalent) */
0x152, /* Help => Insert (location equivalent) */
0x147, /* Home */
0x149, /* PageUp */
0x153, /* ForwardDelete */
0x3e, /* F4 */
0x14f, /* End */
0x3c, /* F2 */
0x151, /* PageDown */
0x3b, /* F1 */
0x14b, /* LeftArrow */
0x14d, /* RightArrow */
0x150, /* DownArrow */
0x148, /* UpArrow */
};
// path_to_url
qint32 NSEventModifierFlagCommand = 1 << 20;
qint32 nvk_Delete = 0x75;
qint32 nvk_Insert = 0x72;
``` | /content/code_sandbox/src/qt/cocoa_keyboard.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,609 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* File field widget.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
*
*/
#include "qt_filefield.hpp"
#include "ui_qt_filefield.h"
#include <QFileDialog>
FileField::FileField(QWidget *parent)
: QWidget(parent)
, ui(new Ui::FileField)
{
ui->setupUi(this);
connect(ui->label, &QLineEdit::editingFinished, this, [this]() {
fileName_ = ui->label->text();
emit fileSelected(ui->label->text(), true);
});
connect(ui->label, &QLineEdit::textChanged, this, [this]() {
fileName_ = ui->label->text();
emit fileTextEntered(ui->label->text(), true);
});
this->setFixedWidth(this->sizeHint().width() + ui->pushButton->sizeHint().width());
}
FileField::~FileField()
{
delete ui;
}
void
FileField::setFileName(const QString &fileName)
{
fileName_ = fileName;
ui->label->setText(fileName);
}
void
FileField::on_pushButton_clicked()
{
QString fileName;
if (createFile_) {
fileName = QFileDialog::getSaveFileName(this, QString(), QString(), filter_, &selectedFilter_);
} else {
fileName = QFileDialog::getOpenFileName(this, QString(), QString(), filter_, &selectedFilter_);
}
if (!fileName.isNull()) {
fileName_ = fileName;
ui->label->setText(fileName);
emit fileSelected(fileName);
}
}
``` | /content/code_sandbox/src/qt/qt_filefield.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 413 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Linux/FreeBSD libevdev mouse input module.
*
*
*
* Authors: Cacodemon345
*
*/
#include "evdev_mouse.hpp"
#include <libevdev/libevdev.h>
#include <unistd.h>
#include <fcntl.h>
#include <vector>
#include <atomic>
#include <string>
#include <tuple>
#include <QThread>
extern "C" {
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/mouse.h>
#include <poll.h>
}
static std::vector<std::pair<int, libevdev *>> evdev_mice;
static std::atomic<bool> stopped = false;
static QThread *evdev_thread;
void
evdev_thread_func()
{
struct pollfd *pfds = (struct pollfd *) calloc(evdev_mice.size(), sizeof(struct pollfd));
for (unsigned int i = 0; i < evdev_mice.size(); i++) {
pfds[i].fd = libevdev_get_fd(evdev_mice[i].second);
pfds[i].events = POLLIN;
}
while (!stopped) {
poll(pfds, evdev_mice.size(), 500);
for (unsigned int i = 0; i < evdev_mice.size(); i++) {
struct input_event ev;
if (pfds[i].revents & POLLIN) {
while (libevdev_next_event(evdev_mice[i].second, LIBEVDEV_READ_FLAG_NORMAL, &ev) == 0) {
if (evdev_mice.size() && (ev.type == EV_REL) && mouse_capture) {
if (ev.code == REL_X)
mouse_scale_x(ev.value);
if (ev.code == REL_Y)
mouse_scale_y(ev.value);
}
}
}
}
}
for (unsigned int i = 0; i < evdev_mice.size(); i++) {
libevdev_free(evdev_mice[i].second);
evdev_mice[i].second = nullptr;
close(evdev_mice[i].first);
}
free(pfds);
evdev_mice.clear();
}
void
evdev_stop()
{
if (evdev_thread) {
stopped = true;
evdev_thread->wait();
evdev_thread = nullptr;
}
}
void
evdev_init()
{
if (evdev_thread)
return;
for (int i = 0; i < 256; i++) {
std::string evdev_device_path = "/dev/input/event" + std::to_string(i);
int fd = open(evdev_device_path.c_str(), O_NONBLOCK | O_RDONLY);
if (fd != -1) {
libevdev *input_struct = nullptr;
int rc = libevdev_new_from_fd(fd, &input_struct);
if (rc <= -1) {
close(fd);
continue;
} else {
if (!libevdev_has_event_type(input_struct, EV_REL) || !libevdev_has_event_code(input_struct, EV_KEY, BTN_LEFT)) {
libevdev_free(input_struct);
close(fd);
continue;
}
evdev_mice.push_back(std::make_pair(fd, input_struct));
}
} else if (errno == ENOENT)
break;
}
if (evdev_mice.size() != 0) {
evdev_thread = QThread::create(evdev_thread_func);
evdev_thread->start();
atexit(evdev_stop);
}
}
``` | /content/code_sandbox/src/qt/evdev_mouse.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 833 |
```c++
#pragma once
#include <memory>
#include <QObject>
#include <QMap>
#include "qt_mediahistorymanager.hpp"
extern "C" {
#include <86box/86box.h>
}
class QMenu;
class MediaMenu : public QObject {
Q_OBJECT
public:
MediaMenu(QWidget *parent);
void refresh(QMenu *parentMenu);
// because some 86box C-only code needs to call zip and
// mo eject directly
static std::shared_ptr<MediaMenu> ptr;
void cassetteNewImage();
void cassetteSelectImage(bool wp);
void cassetteMount(const QString &filename, bool wp);
void cassetteEject();
void cassetteUpdateMenu();
void cartridgeSelectImage(int i);
void cartridgeMount(int i, const QString &filename);
void cartridgeEject(int i);
void cartridgeUpdateMenu(int i);
void floppyNewImage(int i);
void floppySelectImage(int i, bool wp);
void floppyMount(int i, const QString &filename, bool wp);
void floppyEject(int i);
void floppyMenuSelect(int index, int slot);
void floppyExportTo86f(int i);
void floppyUpdateMenu(int i);
void cdromMute(int i);
void cdromMount(int i, int dir, const QString &arg);
void cdromMount(int i, const QString &filename);
void cdromEject(int i);
void cdromReload(int index, int slot);
void updateImageHistory(int index, int slot, ui::MediaType type);
void clearImageHistory();
void cdromUpdateMenu(int i);
void zipNewImage(int i);
void zipSelectImage(int i, bool wp);
void zipMount(int i, const QString &filename, bool wp);
void zipEject(int i);
void zipReload(int i);
void zipUpdateMenu(int i);
void moNewImage(int i);
void moSelectImage(int i, bool wp);
void moMount(int i, const QString &filename, bool wp);
void moEject(int i);
void moReload(int i);
void moUpdateMenu(int i);
void nicConnect(int i);
void nicDisconnect(int i);
void nicUpdateMenu(int i);
public slots:
void cdromUpdateUi(int i);
signals:
void onCdromUpdateUi(int i);
private:
QWidget *parentWidget = nullptr;
QMenu *cassetteMenu = nullptr;
QMap<int, QMenu *> cartridgeMenus;
QMap<int, QMenu *> floppyMenus;
QMap<int, QMenu *> cdromMenus;
QMap<int, QMenu *> zipMenus;
QMap<int, QMenu *> moMenus;
QMap<int, QMenu *> netMenus;
QString getMediaOpenDirectory();
ui::MediaHistoryManager mhm;
const QByteArray driveLetters = QByteArrayLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
int cassetteRecordPos;
int cassettePlayPos;
int cassetteRewindPos;
int cassetteFastFwdPos;
int cassetteEjectPos;
int cartridgeEjectPos;
int floppyExportPos;
int floppyEjectPos;
int cdromMutePos;
int cdromReloadPos;
int cdromImagePos;
int cdromDirPos;
int cdromImageHistoryPos[MAX_PREV_IMAGES];
int floppyImageHistoryPos[MAX_PREV_IMAGES];
int zipEjectPos;
int zipReloadPos;
int moEjectPos;
int moReloadPos;
int netDisconnPos;
friend class MachineStatus;
};
``` | /content/code_sandbox/src/qt/qt_mediamenu.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 758 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Hard disk dialog code.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
*
*/
#include "qt_harddiskdialog.hpp"
#include "ui_qt_harddiskdialog.h"
extern "C" {
#include <86box/86box.h>
#include <86box/hdd.h>
#include "../disk/minivhd/minivhd.h"
}
#include <thread>
#include <QMessageBox>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFileDialog>
#include <QProgressDialog>
#include <QPushButton>
#include <QStringBuilder>
#include <QStringList>
#include "qt_harddrive_common.hpp"
#include "qt_settings_bus_tracking.hpp"
#include "qt_models_common.hpp"
#include "qt_util.hpp"
HarddiskDialog::HarddiskDialog(bool existing, QWidget *parent)
: QDialog(parent)
, ui(new Ui::HarddiskDialog)
{
ui->setupUi(this);
auto *model = ui->comboBoxFormat->model();
model->insertRows(0, 6);
model->setData(model->index(0, 0), tr("Raw image (.img)"));
model->setData(model->index(1, 0), tr("HDI image (.hdi)"));
model->setData(model->index(2, 0), tr("HDX image (.hdx)"));
model->setData(model->index(3, 0), tr("Fixed-size VHD (.vhd)"));
model->setData(model->index(4, 0), tr("Dynamic-size VHD (.vhd)"));
model->setData(model->index(5, 0), tr("Differencing VHD (.vhd)"));
model = ui->comboBoxBlockSize->model();
model->insertRows(0, 2);
model->setData(model->index(0, 0), tr("Large blocks (2 MB)"));
model->setData(model->index(1, 0), tr("Small blocks (512 KB)"));
ui->comboBoxBlockSize->hide();
ui->labelBlockSize->hide();
Harddrives::populateBuses(ui->comboBoxBus->model());
ui->comboBoxBus->setCurrentIndex(3);
model = ui->comboBoxType->model();
for (int i = 0; i < 127; i++) {
uint64_t size = ((uint64_t) hdd_table[i][0]) * hdd_table[i][1] * hdd_table[i][2];
uint32_t size_mb = size >> 11LL;
// QString text = QString("%1 MiB (CHS: %2, %3, %4)").arg(size_mb).arg(hdd_table[i][0]).arg(hdd_table[i][1]).arg(hdd_table[i][2]);
QString text = QString::asprintf(tr("%u MB (CHS: %i, %i, %i)").toUtf8().constData(), size_mb, (hdd_table[i][0]), (hdd_table[i][1]), (hdd_table[i][2]));
Models::AddEntry(model, text, i);
}
Models::AddEntry(model, tr("Custom..."), 127);
Models::AddEntry(model, tr("Custom (large)..."), 128);
ui->lineEditSize->setValidator(new QIntValidator());
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
filters = QStringList({ tr("Raw image") % util::DlgFilter({ "img" }, true),
tr("HDI image") % util::DlgFilter({ "hdi" }, true),
tr("HDX image") % util::DlgFilter({ "hdx" }, true),
tr("Fixed-size VHD") % util::DlgFilter({ "vhd" }, true),
tr("Dynamic-size VHD") % util::DlgFilter({ "vhd" }, true),
tr("Differencing VHD") % util::DlgFilter({ "vhd" }, true) });
if (existing) {
ui->fileField->setFilter(tr("Hard disk images") % util::DlgFilter({ "hd?", "im?", "vhd" }) % tr("All files") % util::DlgFilter({ "*" }, true));
setWindowTitle(tr("Add Existing Hard Disk"));
ui->lineEditCylinders->setEnabled(false);
ui->lineEditHeads->setEnabled(false);
ui->lineEditSectors->setEnabled(false);
ui->lineEditSize->setEnabled(false);
ui->comboBoxType->setEnabled(false);
ui->comboBoxFormat->hide();
ui->labelFormat->hide();
connect(ui->fileField, &FileField::fileSelected, this, &HarddiskDialog::onExistingFileSelected);
} else {
ui->fileField->setFilter(filters.join(";;"));
setWindowTitle(tr("Add New Hard Disk"));
ui->fileField->setCreateFile(true);
// Enable the OK button as long as the filename length is non-zero
connect(ui->fileField, &FileField::fileTextEntered, this, [this] {
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled((this->fileName().length() > 0));
});
connect(ui->fileField, &FileField::fileSelected, this, [this] {
int filter = filters.indexOf(ui->fileField->selectedFilter());
if (filter > -1)
ui->comboBoxFormat->setCurrentIndex(filter);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
});
// Set the default format to Dynamic-size VHD. Do it last after everything is set up
// so the currentIndexChanged signal can do what is needed
ui->comboBoxFormat->setCurrentIndex(DEFAULT_DISK_FORMAT);
ui->fileField->setselectedFilter(filters.value(DEFAULT_DISK_FORMAT));
}
}
HarddiskDialog::~HarddiskDialog()
{
delete ui;
}
uint8_t
HarddiskDialog::bus() const
{
return static_cast<uint8_t>(ui->comboBoxBus->currentData().toUInt());
}
uint8_t
HarddiskDialog::channel() const
{
return static_cast<uint8_t>(ui->comboBoxChannel->currentData().toUInt());
}
QString
HarddiskDialog::fileName() const
{
return ui->fileField->fileName();
}
uint32_t
HarddiskDialog::speed() const
{
return static_cast<uint32_t>(ui->comboBoxSpeed->currentData().toUInt());
}
void
HarddiskDialog::on_comboBoxFormat_currentIndexChanged(int index)
{
bool enabled;
if (index == 5) { /* They switched to a diff VHD; disable the geometry fields. */
enabled = false;
ui->lineEditCylinders->setText(tr("(N/A)"));
ui->lineEditHeads->setText(tr("(N/A)"));
ui->lineEditSectors->setText(tr("(N/A)"));
ui->lineEditSize->setText(tr("(N/A)"));
} else {
enabled = true;
ui->lineEditCylinders->setText(QString::number(cylinders_));
ui->lineEditHeads->setText(QString::number(heads_));
ui->lineEditSectors->setText(QString::number(sectors_));
recalcSize();
}
ui->lineEditCylinders->setEnabled(enabled);
ui->lineEditHeads->setEnabled(enabled);
ui->lineEditSectors->setEnabled(enabled);
ui->lineEditSize->setEnabled(enabled);
ui->comboBoxType->setEnabled(enabled);
if (index < 4) {
ui->comboBoxBlockSize->hide();
ui->labelBlockSize->hide();
} else {
ui->comboBoxBlockSize->show();
ui->labelBlockSize->show();
}
ui->fileField->setselectedFilter(filters.value(index));
}
/* If the disk geometry requested in the 86Box GUI is not compatible with the internal VHD geometry,
* we adjust it to the next-largest size that is compatible. On average, this will be a difference
* of about 21 MB, and should only be necessary for VHDs larger than 31.5 GB, so should never be more
* than a tenth of a percent change in size.
*/
static void
adjust_86box_geometry_for_vhd(MVHDGeom *_86box_geometry, MVHDGeom *vhd_geometry)
{
if (_86box_geometry->cyl <= 65535) {
vhd_geometry->cyl = _86box_geometry->cyl;
vhd_geometry->heads = _86box_geometry->heads;
vhd_geometry->spt = _86box_geometry->spt;
return;
}
int desired_sectors = _86box_geometry->cyl * _86box_geometry->heads * _86box_geometry->spt;
if (desired_sectors > 267321600)
desired_sectors = 267321600;
int remainder = desired_sectors % 85680; /* 8560 is the LCM of 1008 (63*16) and 4080 (255*16) */
if (remainder > 0)
desired_sectors += (85680 - remainder);
_86box_geometry->cyl = desired_sectors / (16 * 63);
_86box_geometry->heads = 16;
_86box_geometry->spt = 63;
vhd_geometry->cyl = desired_sectors / (16 * 255);
vhd_geometry->heads = 16;
vhd_geometry->spt = 255;
}
static HarddiskDialog *callbackPtr = nullptr;
static MVHDGeom
create_drive_vhd_fixed(const QString &fileName, HarddiskDialog *p, uint16_t cyl, uint8_t heads, uint8_t spt)
{
MVHDGeom _86box_geometry = { .cyl = cyl, .heads = heads, .spt = spt };
MVHDGeom vhd_geometry;
adjust_86box_geometry_for_vhd(&_86box_geometry, &vhd_geometry);
int vhd_error = 0;
QByteArray filenameBytes = fileName.toUtf8();
callbackPtr = p;
MVHDMeta *vhd = mvhd_create_fixed(filenameBytes.data(), vhd_geometry, &vhd_error, [](uint32_t current_sector, uint32_t total_sectors) {
callbackPtr->fileProgress((current_sector * 100) / total_sectors);
});
callbackPtr = nullptr;
if (vhd == NULL) {
_86box_geometry.cyl = 0;
_86box_geometry.heads = 0;
_86box_geometry.spt = 0;
} else {
mvhd_close(vhd);
}
return _86box_geometry;
}
static MVHDGeom
create_drive_vhd_dynamic(const QString &fileName, uint16_t cyl, uint8_t heads, uint8_t spt, int blocksize)
{
MVHDGeom _86box_geometry = { .cyl = cyl, .heads = heads, .spt = spt };
MVHDGeom vhd_geometry;
adjust_86box_geometry_for_vhd(&_86box_geometry, &vhd_geometry);
int vhd_error = 0;
QByteArray filenameBytes = fileName.toUtf8();
MVHDCreationOptions options;
options.block_size_in_sectors = blocksize;
options.path = filenameBytes.data();
options.size_in_bytes = 0;
options.geometry = vhd_geometry;
options.type = MVHD_TYPE_DYNAMIC;
MVHDMeta *vhd = mvhd_create_ex(options, &vhd_error);
if (vhd == NULL) {
_86box_geometry.cyl = 0;
_86box_geometry.heads = 0;
_86box_geometry.spt = 0;
} else {
mvhd_close(vhd);
}
return _86box_geometry;
}
static MVHDGeom
create_drive_vhd_diff(const QString &fileName, const QString &parentFileName, int blocksize)
{
int vhd_error = 0;
QByteArray filenameBytes = fileName.toUtf8();
QByteArray parentFilenameBytes = parentFileName.toUtf8();
MVHDCreationOptions options;
options.block_size_in_sectors = blocksize;
options.path = filenameBytes.data();
options.parent_path = parentFilenameBytes.data();
options.type = MVHD_TYPE_DIFF;
MVHDMeta *vhd = mvhd_create_ex(options, &vhd_error);
MVHDGeom vhd_geometry;
if (vhd == NULL) {
vhd_geometry.cyl = 0;
vhd_geometry.heads = 0;
vhd_geometry.spt = 0;
} else {
vhd_geometry = mvhd_get_geometry(vhd);
if (vhd_geometry.spt > 63) {
vhd_geometry.cyl = mvhd_calc_size_sectors(&vhd_geometry) / (16 * 63);
vhd_geometry.heads = 16;
vhd_geometry.spt = 63;
}
mvhd_close(vhd);
}
return vhd_geometry;
}
void
HarddiskDialog::onCreateNewFile()
{
for (auto &curObject : children()) {
if (qobject_cast<QWidget *>(curObject))
qobject_cast<QWidget *>(curObject)->setDisabled(true);
}
ui->progressBar->setEnabled(true);
setResult(QDialog::Rejected);
uint32_t sector_size = 512;
quint64 size = (static_cast<uint64_t>(cylinders_) * static_cast<uint64_t>(heads_) * static_cast<uint64_t>(sectors_) * static_cast<uint64_t>(sector_size));
if (size > 0x1FFFFFFE00LL) {
QMessageBox::critical(this, tr("Disk image too large"), tr("Disk images cannot be larger than 127 GB."));
return;
}
int img_format = ui->comboBoxFormat->currentIndex();
uint32_t zero = 0;
uint32_t base = 0x1000;
auto fileName = ui->fileField->fileName();
QString expectedSuffix;
switch (img_format) {
case IMG_FMT_HDI:
expectedSuffix = "hdi";
break;
case IMG_FMT_HDX:
expectedSuffix = "hdx";
break;
case IMG_FMT_VHD_FIXED:
case IMG_FMT_VHD_DYNAMIC:
case IMG_FMT_VHD_DIFF:
expectedSuffix = "vhd";
break;
}
if (!expectedSuffix.isEmpty()) {
QFileInfo fileInfo(fileName);
if (fileInfo.suffix().compare(expectedSuffix, Qt::CaseInsensitive) != 0) {
fileName = QString("%1.%2").arg(fileName, expectedSuffix);
ui->fileField->setFileName(fileName);
}
}
QFileInfo fi(fileName);
fileName = (fi.isRelative() && !fi.filePath().isEmpty()) ? usr_path + fi.filePath() : fi.filePath();
ui->fileField->setFileName(fileName);
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox::critical(this, tr("Unable to write file"), tr("Make sure the file is being saved to a writable directory."));
return;
}
if (img_format == IMG_FMT_HDI) { /* HDI file */
QDataStream stream(&file);
stream.setByteOrder(QDataStream::LittleEndian);
if (size >= 0x100000000LL) {
QMessageBox::critical(this, tr("Disk image too large"), tr("HDI disk images cannot be larger than 4 GB."));
return;
}
uint32_t s = static_cast<uint32_t>(size);
stream << zero; /* 00000000: Zero/unknown */
stream << zero; /* 00000004: Zero/unknown */
stream << base; /* 00000008: Offset at which data starts */
stream << s; /* 0000000C: Full size of the data (32-bit) */
stream << sector_size; /* 00000010: Sector size in bytes */
stream << sectors_; /* 00000014: Sectors per cylinder */
stream << heads_; /* 00000018: Heads per cylinder */
stream << cylinders_; /* 0000001C: Cylinders */
for (int i = 0; i < 0x3f8; i++) {
stream << zero;
}
} else if (img_format == IMG_FMT_HDX) { /* HDX file */
QDataStream stream(&file);
stream.setByteOrder(QDataStream::LittleEndian);
quint64 signature = 0xD778A82044445459;
stream << signature; /* 00000000: Signature */
stream << size; /* 00000008: Full size of the data (64-bit) */
stream << sector_size; /* 00000010: Sector size in bytes */
stream << sectors_; /* 00000014: Sectors per cylinder */
stream << heads_; /* 00000018: Heads per cylinder */
stream << cylinders_; /* 0000001C: Cylinders */
stream << zero; /* 00000020: [Translation] Sectors per cylinder */
stream << zero; /* 00000004: [Translation] Heads per cylinder */
} else if (img_format >= IMG_FMT_VHD_FIXED) { /* VHD file */
file.close();
MVHDGeom _86box_geometry {};
int block_size = ui->comboBoxBlockSize->currentIndex() == 0 ? MVHD_BLOCK_LARGE : MVHD_BLOCK_SMALL;
switch (img_format) {
case IMG_FMT_VHD_FIXED:
{
connect(this, &HarddiskDialog::fileProgress, this, [this](int value) { ui->progressBar->setValue(value); QApplication::processEvents(); });
ui->progressBar->setVisible(true);
[&_86box_geometry, fileName, this] {
_86box_geometry = create_drive_vhd_fixed(fileName, this, cylinders_, heads_, sectors_);
}();
}
break;
case IMG_FMT_VHD_DYNAMIC:
_86box_geometry = create_drive_vhd_dynamic(fileName, cylinders_, heads_, sectors_, block_size);
break;
case IMG_FMT_VHD_DIFF:
QString vhdParent = QFileDialog::getOpenFileName(
this,
tr("Select the parent VHD"),
QString(),
tr("VHD files") % util::DlgFilter({ "vhd" }) % tr("All files") % util::DlgFilter({ "*" }, true));
if (vhdParent.isEmpty()) {
return;
}
_86box_geometry = create_drive_vhd_diff(fileName, vhdParent, block_size);
break;
}
if (_86box_geometry.cyl == 0 && _86box_geometry.heads == 0 && _86box_geometry.spt == 0) {
QMessageBox::critical(this, tr("Unable to write file"), tr("Make sure the file is being saved to a writable directory."));
return;
} else if (img_format != IMG_FMT_VHD_DIFF) {
QMessageBox::information(this, tr("Disk image created"), tr("Remember to partition and format the newly-created drive."));
}
ui->lineEditCylinders->setText(QString::number(_86box_geometry.cyl));
ui->lineEditHeads->setText(QString::number(_86box_geometry.heads));
ui->lineEditSectors->setText(QString::number(_86box_geometry.spt));
cylinders_ = _86box_geometry.cyl;
heads_ = _86box_geometry.heads;
sectors_ = _86box_geometry.spt;
setResult(QDialog::Accepted);
return;
}
// formats 0, 1 and 2
connect(this, &HarddiskDialog::fileProgress, this, [this](int value) { ui->progressBar->setValue(value); QApplication::processEvents(); });
ui->progressBar->setVisible(true);
[size, &file, this] {
QDataStream stream(&file);
stream.setByteOrder(QDataStream::LittleEndian);
QByteArray buf(1048576, 0);
uint64_t mibBlocks = size >> 20;
uint64_t restBlock = size & 0xfffff;
if (restBlock) {
stream.writeRawData(buf.data(), restBlock);
}
if (mibBlocks) {
for (uint64_t i = 0; i < mibBlocks; ++i) {
stream.writeRawData(buf.data(), buf.size());
emit fileProgress(static_cast<int>((i * 100) / mibBlocks));
}
}
emit fileProgress(100);
}();
QMessageBox::information(this, tr("Disk image created"), tr("Remember to partition and format the newly-created drive."));
setResult(QDialog::Accepted);
}
static void
adjust_vhd_geometry_for_86box(MVHDGeom *vhd_geometry)
{
if (vhd_geometry->spt <= 63)
return;
int desired_sectors = vhd_geometry->cyl * vhd_geometry->heads * vhd_geometry->spt;
if (desired_sectors > 267321600)
desired_sectors = 267321600;
int remainder = desired_sectors % 85680; /* 8560 is the LCM of 1008 (63*16) and 4080 (255*16) */
if (remainder > 0)
desired_sectors -= remainder;
vhd_geometry->cyl = desired_sectors / (16 * 63);
vhd_geometry->heads = 16;
vhd_geometry->spt = 63;
}
void
HarddiskDialog::recalcSelection()
{
int selection = 127;
for (int i = 0; i < 127; i++) {
if ((cylinders_ == hdd_table[i][0]) && (heads_ == hdd_table[i][1]) && (sectors_ == hdd_table[i][2]))
selection = i;
}
if ((selection == 127) && (heads_ == 16) && (sectors_ == 63)) {
selection = 128;
}
ui->comboBoxType->setCurrentIndex(selection);
}
void
HarddiskDialog::onExistingFileSelected(const QString &fileName, bool precheck)
{
// TODO : Over to non-existing file selected
#if 0
if (!(existing & 1)) {
fp = _wfopen(wopenfilestring, L"rb");
if (fp != NULL) {
fclose(fp);
if (settings_msgbox_ex(MBX_QUESTION_YN, L"Disk image file already exists", L"The selected file will be overwritten. Are you sure you want to use it?", L"Overwrite", L"Don't overwrite", NULL) != 0) / * yes * /
return false;
}
}
fp = _wfopen(wopenfilestring, (existing & 1) ? L"rb" : L"wb");
if (fp == NULL) {
hdd_add_file_open_error:
fclose(fp);
settings_msgbox_header(MBX_ERROR, (existing & 1) ? L"Make sure the file exists and is readable." : L"Make sure the file is being saved to a writable directory.", (existing & 1) ? L"Unable to read file" : L"Unable to write file");
return true;
}
#endif
uint64_t size = 0;
uint32_t sector_size = 0;
uint32_t sectors = 0;
uint32_t heads = 0;
uint32_t cylinders = 0;
int vhd_error = 0;
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
// No message box during precheck (performed when the file input loses focus and this function is called)
// If precheck is false, the file has been chosen from a file dialog and the alert should display.
if(!precheck) {
QMessageBox::critical(this, tr("Unable to read file"), tr("Make sure the file exists and is readable."));
}
return;
}
QByteArray fileNameUtf8 = fileName.toUtf8();
QFileInfo fi(file);
if (image_is_hdi(fileNameUtf8.data()) || image_is_hdx(fileNameUtf8.data(), 1)) {
file.seek(0x10);
QDataStream stream(&file);
stream.setByteOrder(QDataStream::LittleEndian);
stream >> sector_size;
if (sector_size != 512) {
QMessageBox::critical(this, tr("Unsupported disk image"), tr("HDI or HDX images with a sector size other than 512 are not supported."));
return;
}
sectors = heads = cylinders = 0;
stream >> sectors;
stream >> heads;
stream >> cylinders;
} else if (image_is_vhd(fileNameUtf8.data(), 1)) {
MVHDMeta *vhd = mvhd_open(fileNameUtf8.data(), 0, &vhd_error);
if (vhd == nullptr) {
QMessageBox::critical(this, tr("Unable to read file"), tr("Make sure the file exists and is readable."));
return;
} else if (vhd_error == MVHD_ERR_TIMESTAMP) {
QMessageBox::StandardButton btn = QMessageBox::warning(this, tr("Parent and child disk timestamps do not match"), tr("This could mean that the parent image was modified after the differencing image was created.\n\nIt can also happen if the image files were moved or copied, or by a bug in the program that created this disk.\n\nDo you want to fix the timestamps?"), QMessageBox::Yes | QMessageBox::No);
if (btn == QMessageBox::Yes) {
int ts_res = mvhd_diff_update_par_timestamp(vhd, &vhd_error);
if (ts_res != 0) {
QMessageBox::critical(this, tr("Error"), tr("Could not fix VHD timestamp"));
mvhd_close(vhd);
return;
}
} else {
mvhd_close(vhd);
return;
}
}
MVHDGeom vhd_geom = mvhd_get_geometry(vhd);
adjust_vhd_geometry_for_86box(&vhd_geom);
cylinders = vhd_geom.cyl;
heads = vhd_geom.heads;
sectors = vhd_geom.spt;
size = static_cast<uint64_t>(cylinders * heads * sectors * 512);
mvhd_close(vhd);
} else {
size = file.size();
if (((size % 17) == 0) && (size <= 142606336)) {
sectors = 17;
if (size <= 26738688)
heads = 4;
else if (((size % 3072) == 0) && (size <= 53477376))
heads = 6;
else {
uint32_t i;
for (i = 5; i < 16; i++) {
if (((size % (i << 9)) == 0) && (size <= ((i * 17) << 19)))
break;
if (i == 5)
i++;
}
heads = i;
}
} else {
sectors = 63;
heads = 16;
}
cylinders = ((size >> 9) / heads) / sectors;
}
if ((sectors > max_sectors) || (heads > max_heads) || (cylinders > max_cylinders)) {
QMessageBox::critical(this, tr("Unable to read file"), tr("Make sure the file exists and is readable."));
return;
}
heads_ = heads;
sectors_ = sectors;
cylinders_ = cylinders;
ui->lineEditCylinders->setText(QString::number(cylinders));
ui->lineEditHeads->setText(QString::number(heads));
ui->lineEditSectors->setText(QString::number(sectors));
recalcSize();
recalcSelection();
ui->lineEditCylinders->setEnabled(true);
ui->lineEditHeads->setEnabled(true);
ui->lineEditSectors->setEnabled(true);
ui->lineEditSize->setEnabled(true);
ui->comboBoxType->setEnabled(true);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
}
void
HarddiskDialog::recalcSize()
{
if (disallowSizeModifications)
return;
uint64_t size = (static_cast<uint64_t>(cylinders_) * static_cast<uint64_t>(heads_) * static_cast<uint64_t>(sectors_)) << 9;
ui->lineEditSize->setText(QString::number(size >> 20));
}
bool
HarddiskDialog::checkAndAdjustSectors()
{
if (sectors_ > max_sectors) {
sectors_ = max_sectors;
ui->lineEditSectors->setText(QString::number(max_sectors));
recalcSize();
recalcSelection();
return false;
}
return true;
}
bool
HarddiskDialog::checkAndAdjustHeads()
{
if (heads_ > max_heads) {
heads_ = max_heads;
ui->lineEditHeads->setText(QString::number(max_heads));
recalcSize();
recalcSelection();
return false;
}
return true;
}
bool
HarddiskDialog::checkAndAdjustCylinders()
{
if (cylinders_ > max_cylinders) {
cylinders_ = max_cylinders;
ui->lineEditCylinders->setText(QString::number(max_cylinders));
recalcSize();
recalcSelection();
return false;
}
return true;
}
void
HarddiskDialog::on_comboBoxBus_currentIndexChanged(int index)
{
int chanIdx = 0;
if (index < 0) {
return;
}
switch (ui->comboBoxBus->currentData().toInt()) {
case HDD_BUS_DISABLED:
default:
max_sectors = max_heads = max_cylinders = 0;
break;
case HDD_BUS_MFM:
max_sectors = 26; /* 17 for MFM, 26 for RLL. */
max_heads = 15;
max_cylinders = 2047;
break;
case HDD_BUS_XTA:
max_sectors = 63;
max_heads = 16;
max_cylinders = 1023;
break;
case HDD_BUS_ESDI:
max_sectors = 99; /* ESDI drives usually had 32 to 43 sectors per track. */
max_heads = 16;
max_cylinders = 266305;
break;
case HDD_BUS_IDE:
max_sectors = 255;
max_heads = 255;
max_cylinders = 266305;
break;
case HDD_BUS_ATAPI:
case HDD_BUS_SCSI:
max_sectors = 255;
max_heads = 255;
max_cylinders = 266305;
break;
}
checkAndAdjustCylinders();
checkAndAdjustHeads();
checkAndAdjustSectors();
if (ui->lineEditCylinders->validator() != nullptr) {
delete ui->lineEditCylinders->validator();
}
if (ui->lineEditHeads->validator() != nullptr) {
delete ui->lineEditHeads->validator();
}
if (ui->lineEditSectors->validator() != nullptr) {
delete ui->lineEditSectors->validator();
}
ui->lineEditCylinders->setValidator(new QIntValidator(1, max_cylinders, this));
ui->lineEditHeads->setValidator(new QIntValidator(1, max_heads, this));
ui->lineEditSectors->setValidator(new QIntValidator(1, max_sectors, this));
Harddrives::populateBusChannels(ui->comboBoxChannel->model(), ui->comboBoxBus->currentData().toInt(), Harddrives::busTrackClass);
Harddrives::populateSpeeds(ui->comboBoxSpeed->model(), ui->comboBoxBus->currentData().toInt());
switch (ui->comboBoxBus->currentData().toInt()) {
case HDD_BUS_MFM:
chanIdx = (Harddrives::busTrackClass->next_free_mfm_channel());
break;
case HDD_BUS_XTA:
chanIdx = (Harddrives::busTrackClass->next_free_xta_channel());
break;
case HDD_BUS_ESDI:
chanIdx = (Harddrives::busTrackClass->next_free_esdi_channel());
break;
case HDD_BUS_ATAPI:
case HDD_BUS_IDE:
chanIdx = (Harddrives::busTrackClass->next_free_ide_channel());
break;
case HDD_BUS_SCSI:
chanIdx = (Harddrives::busTrackClass->next_free_scsi_id());
break;
}
if (chanIdx == 0xFF)
chanIdx = 0;
ui->comboBoxChannel->setCurrentIndex(chanIdx);
}
void
HarddiskDialog::on_lineEditSize_textEdited(const QString &text)
{
disallowSizeModifications = true;
uint32_t size = text.toUInt();
/* This is needed to ensure VHD standard compliance. */
hdd_image_calc_chs(&cylinders_, &heads_, §ors_, size);
ui->lineEditCylinders->setText(QString::number(cylinders_));
ui->lineEditHeads->setText(QString::number(heads_));
ui->lineEditSectors->setText(QString::number(sectors_));
recalcSelection();
checkAndAdjustCylinders();
checkAndAdjustHeads();
checkAndAdjustSectors();
disallowSizeModifications = false;
}
void
HarddiskDialog::on_lineEditCylinders_textEdited(const QString &text)
{
cylinders_ = text.toUInt();
if (checkAndAdjustCylinders()) {
recalcSize();
recalcSelection();
}
}
void
HarddiskDialog::on_lineEditHeads_textEdited(const QString &text)
{
heads_ = text.toUInt();
if (checkAndAdjustHeads()) {
recalcSize();
recalcSelection();
}
}
void
HarddiskDialog::on_lineEditSectors_textEdited(const QString &text)
{
sectors_ = text.toUInt();
if (checkAndAdjustSectors()) {
recalcSize();
recalcSelection();
}
}
void
HarddiskDialog::on_comboBoxType_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
if ((index != 127) && (index != 128)) {
cylinders_ = hdd_table[index][0];
heads_ = hdd_table[index][1];
sectors_ = hdd_table[index][2];
ui->lineEditCylinders->setText(QString::number(cylinders_));
ui->lineEditHeads->setText(QString::number(heads_));
ui->lineEditSectors->setText(QString::number(sectors_));
recalcSize();
} else if (index == 128) {
heads_ = 16;
sectors_ = 63;
ui->lineEditHeads->setText(QString::number(heads_));
ui->lineEditSectors->setText(QString::number(sectors_));
recalcSize();
}
checkAndAdjustCylinders();
checkAndAdjustHeads();
checkAndAdjustSectors();
}
void
HarddiskDialog::accept()
{
if (ui->fileField->createFile())
onCreateNewFile();
else
setResult(QDialog::Accepted);
QDialog::done(result());
}
``` | /content/code_sandbox/src/qt/qt_harddiskdialog.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 7,817 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Software renderer module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
* Teemu Korhonen
*
*/
#include "qt_softwarerenderer.hpp"
#include <QApplication>
#include <QPainter>
extern "C" {
#include <86box/86box.h>
#include <86box/video.h>
}
SoftwareRenderer::SoftwareRenderer(QWidget *parent)
#ifdef __HAIKU__
: QWidget(parent)
#else
: QRasterWindow(parent->windowHandle())
#endif
{
RendererCommon::parentWidget = parent;
images[0] = std::make_unique<QImage>(QSize(2048, 2048), QImage::Format_RGB32);
images[1] = std::make_unique<QImage>(QSize(2048, 2048), QImage::Format_RGB32);
buf_usage = std::vector<std::atomic_flag>(2);
buf_usage[0].clear();
buf_usage[1].clear();
#ifdef __HAIKU__
this->setMouseTracking(true);
#endif
}
void
SoftwareRenderer::paintEvent(QPaintEvent *event)
{
(void) event;
onPaint(this);
}
void
SoftwareRenderer::onBlit(int buf_idx, int x, int y, int w, int h)
{
/* TODO: should look into deleteLater() */
auto tval = this;
void *nuldata = 0;
if (memcmp(&tval, &nuldata, sizeof(void *)) == 0)
return;
auto origSource = source;
cur_image = buf_idx;
buf_usage[(buf_idx + 1) % 2].clear();
source.setRect(x, y, w, h);
if (source != origSource)
onResize(this->width(), this->height());
update();
}
void
SoftwareRenderer::resizeEvent(QResizeEvent *event)
{
onResize(width(), height());
#ifdef __HAIKU__
QWidget::resizeEvent(event);
#else
QRasterWindow::resizeEvent(event);
#endif
}
bool
SoftwareRenderer::event(QEvent *event)
{
bool res = false;
if (!eventDelegate(event, res))
#ifdef __HAIKU__
return QWidget::event(event);
#else
return QRasterWindow::event(event);
#endif
return res;
}
void
SoftwareRenderer::onPaint(QPaintDevice *device)
{
if (cur_image == -1)
return;
QPainter painter(device);
painter.setRenderHint(QPainter::SmoothPixmapTransform, video_filter_method > 0 ? true : false);
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
painter.fillRect(0, 0, device->width(), device->height(), QColorConstants::Black);
#else
painter.fillRect(0, 0, device->width(), device->height(), Qt::black);
#endif
painter.setCompositionMode(QPainter::CompositionMode_Plus);
painter.drawImage(destination, *images[cur_image], source);
}
std::vector<std::tuple<uint8_t *, std::atomic_flag *>>
SoftwareRenderer::getBuffers()
{
std::vector<std::tuple<uint8_t *, std::atomic_flag *>> buffers;
buffers.push_back(std::make_tuple(images[0]->bits(), &buf_usage[0]));
buffers.push_back(std::make_tuple(images[1]->bits(), &buf_usage[1]));
return buffers;
}
``` | /content/code_sandbox/src/qt/qt_softwarerenderer.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 816 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Common platform functions.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
* Teemu Korhonen
*
*/
#include <cstdio>
#include <mutex>
#include <thread>
#include <memory>
#include <algorithm>
#include <map>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTemporaryFile>
#include <QStandardPaths>
#include <QCoreApplication>
#include <QDateTime>
#include <QLocalSocket>
#include <QTimer>
#include <QProcess>
#include <QRegularExpression>
#include <QLibrary>
#include <QElapsedTimer>
#include <QScreen>
#include "qt_rendererstack.hpp"
#include "qt_mainwindow.hpp"
#include "qt_progsettings.hpp"
#include "qt_util.hpp"
#ifdef Q_OS_UNIX
# include <pthread.h>
# include <sys/mman.h>
#endif
#if 0
static QByteArray buf;
#endif
extern QElapsedTimer elapsed_timer;
extern MainWindow *main_window;
QElapsedTimer elapsed_timer;
static std::atomic_int blitmx_contention = 0;
static std::recursive_mutex blitmx;
class CharPointer {
public:
CharPointer(char *buf, int size)
: b(buf)
, s(size)
{
}
CharPointer &operator=(const QByteArray &ba)
{
if (s > 0) {
strncpy(b, ba.data(), s - 1);
b[s] = 0;
} else {
// if we haven't been told the length of b, just assume enough
// because we didn't get it from emulator code
strcpy(b, ba.data());
b[ba.size()] = 0;
}
return *this;
}
private:
char *b;
int s;
};
extern "C" {
#ifdef Q_OS_WINDOWS
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <windows.h>
# include <86box/win.h>
#else
# include <strings.h>
#endif
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/gameport.h>
#include <86box/timer.h>
#include <86box/nvr.h>
#include <86box/path.h>
#include <86box/plat_dynld.h>
#include <86box/mem.h>
#include <86box/rom.h>
#include <86box/config.h>
#include <86box/ui.h>
#ifdef DISCORD
# include <86box/discord.h>
#endif
#include "../cpu/cpu.h"
#include <86box/plat.h>
volatile int cpu_thread_run = 1;
int mouse_capture = 0;
int fixed_size_x = 640;
int fixed_size_y = 480;
int rctrl_is_lalt = 0;
int update_icons = 1;
int kbd_req_capture = 0;
int hide_status_bar = 0;
int hide_tool_bar = 0;
uint32_t lang_id = 0x0409, lang_sys = 0x0409; // Multilangual UI variables, for now all set to LCID of en-US
int
stricmp(const char *s1, const char *s2)
{
#ifdef Q_OS_WINDOWS
return _stricmp(s1, s2);
#else
return strcasecmp(s1, s2);
#endif
}
int
strnicmp(const char *s1, const char *s2, size_t n)
{
#ifdef Q_OS_WINDOWS
return _strnicmp(s1, s2, n);
#else
return strncasecmp(s1, s2, n);
#endif
}
void
do_start(void)
{
}
void
do_stop(void)
{
cpu_thread_run = 0;
#if 0
main_window->close();
#endif
}
void
plat_get_exe_name(char *s, int size)
{
QByteArray exepath_temp = QCoreApplication::applicationDirPath().toLocal8Bit();
memcpy(s, exepath_temp.data(), std::min((qsizetype) exepath_temp.size(), (qsizetype) size));
path_slash(s);
}
uint32_t
plat_get_ticks(void)
{
return elapsed_timer.elapsed();
}
uint64_t
plat_timer_read(void)
{
return elapsed_timer.elapsed();
}
FILE *
plat_fopen(const char *path, const char *mode)
{
#if defined(Q_OS_MACOS) or defined(Q_OS_LINUX)
QFileInfo fi(path);
QString filename = (fi.isRelative() && !fi.filePath().isEmpty()) ? usr_path + fi.filePath() : fi.filePath();
return fopen(filename.toUtf8().constData(), mode);
#else
return fopen(QString::fromUtf8(path).toLocal8Bit(), mode);
#endif
}
FILE *
plat_fopen64(const char *path, const char *mode)
{
#if defined(Q_OS_MACOS) or defined(Q_OS_LINUX)
QFileInfo fi(path);
QString filename = (fi.isRelative() && !fi.filePath().isEmpty()) ? usr_path + fi.filePath() : fi.filePath();
return fopen(filename.toUtf8().constData(), mode);
#else
return fopen(QString::fromUtf8(path).toLocal8Bit(), mode);
#endif
}
int
plat_dir_create(char *path)
{
return QDir().mkdir(path) ? 0 : -1;
}
int
plat_dir_check(char *path)
{
QFileInfo fi(path);
return fi.isDir() ? 1 : 0;
}
int
plat_getcwd(char *bufp, int max)
{
#ifdef __APPLE__
/* Working directory for .app bundles is undefined. */
strncpy(bufp, exe_path, max);
#else
CharPointer(bufp, max) = QDir::currentPath().toUtf8();
#endif
return 0;
}
void
path_get_dirname(char *dest, const char *path)
{
QFileInfo fi(path);
CharPointer(dest, -1) = fi.dir().path().toUtf8();
}
char *
path_get_extension(char *s)
{
auto len = strlen(s);
auto idx = QByteArray::fromRawData(s, len).lastIndexOf('.');
if (idx >= 0) {
return s + idx + 1;
}
return s + len;
}
char *
path_get_filename(char *s)
{
#ifdef Q_OS_WINDOWS
int c = strlen(s) - 1;
while (c > 0) {
if (s[c] == '/' || s[c] == '\\')
return (&s[c + 1]);
c--;
}
return s;
#else
auto idx = QByteArray::fromRawData(s, strlen(s)).lastIndexOf(QDir::separator().toLatin1());
if (idx >= 0) {
return s + idx + 1;
}
return s;
#endif
}
int
path_abs(char *path)
{
#ifdef Q_OS_WINDOWS
if ((path[1] == ':') || (path[0] == '\\') || (path[0] == '/') || (strstr(path, "ioctl://") == path))
return 1;
return 0;
#else
return path[0] == '/';
#endif
}
void
path_normalize(char *path)
{
#ifdef Q_OS_WINDOWS
if (strstr(path, "ioctl://") != path) {
while (*path++ != 0) {
if (*path == '\\')
*path = '/';
}
} else
path[8] = path[9] = path[11] = '\\';
#endif
}
void
path_slash(char *path)
{
auto len = strlen(path);
auto separator = '/';
if (path[len - 1] != separator) {
path[len] = separator;
path[len + 1] = 0;
}
path_normalize(path);
}
const char *
path_get_slash(char *path)
{
return QString(path).endsWith("/") ? "" : "/";
}
void
path_append_filename(char *dest, const char *s1, const char *s2)
{
strcpy(dest, s1);
path_slash(dest);
strcat(dest, s2);
}
void
plat_tempfile(char *bufp, char *prefix, char *suffix)
{
QString name;
if (prefix != nullptr) {
name.append(QString("%1-").arg(prefix));
}
name.append(QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss-zzz"));
if (suffix)
name.append(suffix);
strcpy(bufp, name.toUtf8().data());
}
void
plat_remove(char *path)
{
QFile(path).remove();
}
void *
plat_mmap(size_t size, uint8_t executable)
{
#if defined Q_OS_WINDOWS
return VirtualAlloc(NULL, size, MEM_COMMIT, executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE);
#elif defined Q_OS_UNIX
# if defined Q_OS_DARWIN && defined MAP_JIT
void *ret = mmap(0, size, PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0), MAP_ANON | MAP_PRIVATE | (executable ? MAP_JIT : 0), -1, 0);
# else
void *ret = mmap(0, size, PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0), MAP_ANON | MAP_PRIVATE, -1, 0);
# endif
return (ret == MAP_FAILED) ? nullptr : ret;
#endif
}
void
plat_munmap(void *ptr, size_t size)
{
#if defined Q_OS_WINDOWS
VirtualFree(ptr, 0, MEM_RELEASE);
#else
munmap(ptr, size);
#endif
}
void
plat_pause(int p)
{
static wchar_t oldtitle[512];
wchar_t title[1024];
wchar_t paused_msg[512];
if ((!!p) == dopause) {
#ifdef Q_OS_WINDOWS
if (source_hwnd)
PostMessage((HWND) (uintptr_t) source_hwnd, WM_SENDSTATUS, (WPARAM) !!p, (LPARAM) (HWND) main_window->winId());
#endif
return;
}
if ((p == 0) && (time_sync & TIME_SYNC_ENABLED))
nvr_time_sync();
do_pause(p);
if (p) {
if (mouse_capture)
plat_mouse_capture(0);
wcsncpy(oldtitle, ui_window_title(NULL), sizeof_w(oldtitle) - 1);
wcscpy(title, oldtitle);
paused_msg[QObject::tr(" - PAUSED").toWCharArray(paused_msg)] = 0;
wcscat(title, paused_msg);
ui_window_title(title);
} else {
ui_window_title(oldtitle);
}
#ifdef DISCORD
discord_update_activity(dopause);
#endif
QTimer::singleShot(0, main_window, &MainWindow::updateUiPauseState);
#ifdef Q_OS_WINDOWS
if (source_hwnd)
PostMessage((HWND) (uintptr_t) source_hwnd, WM_SENDSTATUS, (WPARAM) !!p, (LPARAM) (HWND) main_window->winId());
#endif
}
void
plat_power_off(void)
{
plat_mouse_capture(0);
confirm_exit_cmdl = 0;
nvr_save();
config_save();
/* Deduct a sufficiently large number of cycles that no instructions will
run before the main thread is terminated */
cycles -= 99999999;
cpu_thread_run = 0;
QTimer::singleShot(0, (const QWidget *) main_window, &QMainWindow::close);
}
extern "C++" {
QMap<uint32_t, QPair<QString, QString>> ProgSettings::lcid_langcode = {
{ 0x0403, { "ca-ES", "Catalan (Spain)" } },
{ 0x0804, { "zh-CN", "Chinese (Simplified)" } },
{ 0x0404, { "zh-TW", "Chinese (Traditional)" } },
{ 0x041A, { "hr-HR", "Croatian (Croatia)" } },
{ 0x0405, { "cs-CZ", "Czech (Czech Republic)" } },
{ 0x0407, { "de-DE", "German (Germany)" } },
{ 0x0809, { "en-GB", "English (United Kingdom)" }},
{ 0x0409, { "en-US", "English (United States)" } },
{ 0x040B, { "fi-FI", "Finnish (Finland)" } },
{ 0x040C, { "fr-FR", "French (France)" } },
{ 0x040E, { "hu-HU", "Hungarian (Hungary)" } },
{ 0x0410, { "it-IT", "Italian (Italy)" } },
{ 0x0411, { "ja-JP", "Japanese (Japan)" } },
{ 0x0412, { "ko-KR", "Korean (Korea)" } },
{ 0x0415, { "pl-PL", "Polish (Poland)" } },
{ 0x0416, { "pt-BR", "Portuguese (Brazil)" } },
{ 0x0816, { "pt-PT", "Portuguese (Portugal)" } },
{ 0x0419, { "ru-RU", "Russian (Russia)" } },
{ 0x041B, { "sk-SK", "Slovak (Slovakia)" } },
{ 0x0424, { "sl-SI", "Slovenian (Slovenia)" } },
{ 0x0C0A, { "es-ES", "Spanish (Spain, Modern Sort)" } },
{ 0x041F, { "tr-TR", "Turkish (Turkey)" } },
{ 0x0422, { "uk-UA", "Ukrainian (Ukraine)" } },
{ 0x042A, { "vi-VN", "Vietnamese (Vietnam)" } },
{ 0xFFFF, { "system", "(System Default)" } },
};
}
/* Sets up the program language before initialization. */
uint32_t
plat_language_code(char *langcode)
{
for (auto &curKey : ProgSettings::lcid_langcode.keys()) {
if (ProgSettings::lcid_langcode[curKey].first == langcode) {
return curKey;
}
}
return 0xFFFF;
}
/* Converts back the language code to LCID */
void
plat_language_code_r(uint32_t lcid, char *outbuf, int len)
{
if (!ProgSettings::lcid_langcode.contains(lcid)) {
qstrncpy(outbuf, "system", len);
return;
}
qstrncpy(outbuf, ProgSettings::lcid_langcode[lcid].first.toUtf8().constData(), len);
return;
}
#ifndef Q_OS_WINDOWS
void *
dynld_module(const char *name, dllimp_t *table)
{
QString libraryName = name;
QFileInfo fi(libraryName);
QStringList removeSuffixes = { "dll", "dylib", "so" };
if (removeSuffixes.contains(fi.suffix())) {
libraryName = fi.completeBaseName();
}
auto lib = std::unique_ptr<QLibrary>(new QLibrary(libraryName));
if (lib->load()) {
for (auto imp = table; imp->name != nullptr; imp++) {
auto ptr = lib->resolve(imp->name);
if (ptr == nullptr) {
return nullptr;
}
auto imp_ptr = reinterpret_cast<void **>(imp->func);
*imp_ptr = reinterpret_cast<void *>(ptr);
}
} else {
return nullptr;
}
return lib.release();
}
void
dynld_close(void *handle)
{
delete reinterpret_cast<QLibrary *>(handle);
}
#endif
void
startblit()
{
blitmx_contention++;
if (blitmx.try_lock()) {
return;
}
blitmx.lock();
}
void
endblit()
{
blitmx_contention--;
blitmx.unlock();
if (blitmx_contention > 0) {
// a deadlock has been observed on linux when toggling via video_toggle_option
// because the mutex is typically unfair on linux
// => sleep if there's contention
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
}
#ifdef Q_OS_WINDOWS
size_t
mbstoc16s(uint16_t dst[], const char src[], int len)
{
if (src == NULL)
return 0;
if (len < 0)
return 0;
size_t ret = MultiByteToWideChar(CP_UTF8, 0, src, -1, reinterpret_cast<LPWSTR>(dst), dst == NULL ? 0 : len);
if (!ret) {
return -1;
}
return ret;
}
size_t
c16stombs(char dst[], const uint16_t src[], int len)
{
if (src == NULL)
return 0;
if (len < 0)
return 0;
size_t ret = WideCharToMultiByte(CP_UTF8, 0, reinterpret_cast<LPCWCH>(src), -1, dst, dst == NULL ? 0 : len, NULL, NULL);
if (!ret) {
return -1;
}
return ret;
}
#endif
#ifdef _WIN32
# if defined(__amd64__) || defined(_M_X64) || defined(__aarch64__) || defined(_M_ARM64)
# define LIB_NAME_GS "gsdll64.dll"
# define LIB_NAME_GPCL "gpcl6dll64.dll"
# else
# define LIB_NAME_GS "gsdll32.dll"
# define LIB_NAME_GPCL "gpcl6dll32.dll"
# endif
# define LIB_NAME_PCAP "Npcap"
# define MOUSE_CAPTURE_KEYSEQ "F8+F12"
#else
# define LIB_NAME_GS "libgs"
# define LIB_NAME_GPCL "libgpcl6"
# define LIB_NAME_PCAP "libpcap"
# define MOUSE_CAPTURE_KEYSEQ "Ctrl+End"
#endif
QMap<int, std::wstring> ProgSettings::translatedstrings;
void
ProgSettings::reloadStrings()
{
translatedstrings.clear();
translatedstrings[STRING_MOUSE_CAPTURE] = QCoreApplication::translate("", "Click to capture mouse").toStdWString();
translatedstrings[STRING_MOUSE_RELEASE] = QCoreApplication::translate("", "Press %1 to release mouse").arg(QCoreApplication::translate("", MOUSE_CAPTURE_KEYSEQ)).toStdWString();
translatedstrings[STRING_MOUSE_RELEASE_MMB] = QCoreApplication::translate("", "Press %1 or middle button to release mouse").arg(QCoreApplication::translate("", MOUSE_CAPTURE_KEYSEQ)).toStdWString();
translatedstrings[STRING_INVALID_CONFIG] = QCoreApplication::translate("", "Invalid configuration").toStdWString();
translatedstrings[STRING_NO_ST506_ESDI_CDROM] = QCoreApplication::translate("", "MFM/RLL or ESDI CD-ROM drives never existed").toStdWString();
translatedstrings[STRING_PCAP_ERROR_NO_DEVICES] = QCoreApplication::translate("", "No PCap devices found").toStdWString();
translatedstrings[STRING_PCAP_ERROR_INVALID_DEVICE] = QCoreApplication::translate("", "Invalid PCap device").toStdWString();
translatedstrings[STRING_PCAP_ERROR_DESC] = QCoreApplication::translate("", "Make sure %1 is installed and that you are on a %1-compatible network connection.").arg(LIB_NAME_PCAP).toStdWString();
translatedstrings[STRING_GHOSTSCRIPT_ERROR_TITLE] = QCoreApplication::translate("", "Unable to initialize Ghostscript").toStdWString();
translatedstrings[STRING_GHOSTSCRIPT_ERROR_DESC] = QCoreApplication::translate("", "%1 is required for automatic conversion of PostScript files to PDF.\n\nAny documents sent to the generic PostScript printer will be saved as PostScript (.ps) files.").arg(LIB_NAME_GS).toStdWString();
translatedstrings[STRING_GHOSTPCL_ERROR_TITLE] = QCoreApplication::translate("", "Unable to initialize GhostPCL").toStdWString();
translatedstrings[STRING_GHOSTPCL_ERROR_DESC] = QCoreApplication::translate("", "%1 is required for automatic conversion of PCL files to PDF.\n\nAny documents sent to the generic PCL printer will be saved as Printer Command Language (.pcl) files.").arg(LIB_NAME_GPCL).toStdWString();
translatedstrings[STRING_HW_NOT_AVAILABLE_MACHINE] = QCoreApplication::translate("", "Machine \"%hs\" is not available due to missing ROMs in the roms/machines directory. Switching to an available machine.").toStdWString();
translatedstrings[STRING_HW_NOT_AVAILABLE_VIDEO] = QCoreApplication::translate("", "Video card \"%hs\" is not available due to missing ROMs in the roms/video directory. Switching to an available video card.").toStdWString();
translatedstrings[STRING_HW_NOT_AVAILABLE_VIDEO2] = QCoreApplication::translate("", "Video card #2 \"%hs\" is not available due to missing ROMs in the roms/video directory. Disabling the second video card.").toStdWString();
translatedstrings[STRING_HW_NOT_AVAILABLE_TITLE] = QCoreApplication::translate("", "Hardware not available").toStdWString();
translatedstrings[STRING_MONITOR_SLEEP] = QCoreApplication::translate("", "Monitor in sleep mode").toStdWString();
translatedstrings[STRING_NET_ERROR] = QCoreApplication::translate("", "Failed to initialize network driver").toStdWString();
translatedstrings[STRING_NET_ERROR_DESC] = QCoreApplication::translate("", "The network configuration will be switched to the null driver").toStdWString();
}
wchar_t *
plat_get_string(int i)
{
if (ProgSettings::translatedstrings.empty())
ProgSettings::reloadStrings();
return ProgSettings::translatedstrings[i].data();
}
int
plat_chdir(char *path)
{
return QDir::setCurrent(QString(path)) ? 0 : -1;
}
void
plat_get_global_config_dir(char *outbuf, const uint8_t len)
{
const auto dir = QDir(QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation)[0]);
if (!dir.exists()) {
if (!dir.mkpath(".")) {
qWarning("Failed to create global configuration directory %s", dir.absolutePath().toUtf8().constData());
}
}
strncpy(outbuf, dir.canonicalPath().toUtf8().constData(), len);
}
void
plat_get_global_data_dir(char *outbuf, const uint8_t len)
{
const auto dir = QDir(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)[0]);
if (!dir.exists()) {
if (!dir.mkpath(".")) {
qWarning("Failed to create global data directory %s", dir.absolutePath().toUtf8().constData());
}
}
strncpy(outbuf, dir.canonicalPath().toUtf8().constData(), len);
}
void
plat_get_temp_dir(char *outbuf, const uint8_t len)
{
const auto dir = QDir(QStandardPaths::standardLocations(QStandardPaths::TempLocation)[0]);
strncpy(outbuf, dir.canonicalPath().toUtf8().constData(), len);
}
void
plat_init_rom_paths(void)
{
auto paths = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
#ifdef _WIN32
// HACK: The standard locations returned for GenericDataLocation include
// the EXE path and a `data` directory within it as the last two entries.
// Remove the entries as we don't need them.
paths.removeLast();
paths.removeLast();
#endif
for (auto &path : paths) {
#ifdef __APPLE__
rom_add_path(QDir(path).filePath("net.86Box.86Box/roms").toUtf8().constData());
rom_add_path(QDir(path).filePath("86Box/roms").toUtf8().constData());
#else
rom_add_path(QDir(path).filePath("86Box/roms").toUtf8().constData());
#endif
}
}
void
plat_get_cpu_string(char *outbuf, uint8_t len) {
auto cpu_string = QString("Unknown");
/* Write the default string now in case we have to exit early from an error */
qstrncpy(outbuf, cpu_string.toUtf8().constData(), len);
#if defined(Q_OS_MACOS)
auto *process = new QProcess(nullptr);
QStringList arguments;
QString program = "/usr/sbin/sysctl";
arguments << "machdep.cpu.brand_string";
process->start(program, arguments);
if (!process->waitForStarted()) {
return;
}
if (!process->waitForFinished()) {
return;
}
QByteArray result = process->readAll();
auto command_result = QString(result).split(": ").last().trimmed();
if(!command_result.isEmpty()) {
cpu_string = command_result;
}
#elif defined(Q_OS_WINDOWS)
const LPCSTR keyName = "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0";
const LPCSTR valueName = "ProcessorNameString";
unsigned char buf[32768];
DWORD bufSize;
HKEY hKey;
bufSize = 32768;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, keyName, 0, 1, &hKey) == ERROR_SUCCESS) {
if (RegQueryValueExA(hKey, valueName, NULL, NULL, buf, &bufSize) == ERROR_SUCCESS) {
cpu_string = reinterpret_cast<const char*>(buf);
}
RegCloseKey(hKey);
}
#elif defined(Q_OS_LINUX)
auto cpuinfo = QString("/proc/cpuinfo");
auto cpuinfo_fi = QFileInfo(cpuinfo);
if(!cpuinfo_fi.isReadable()) {
return;
}
QFile file(cpuinfo);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream textStream(&file);
while(true) {
QString line = textStream.readLine();
if (line.isNull()) {
break;
}
if(QRegularExpression("model name.*:").match(line).hasMatch()) {
auto list = line.split(": ");
if(!list.last().isEmpty()) {
cpu_string = list.last();
break;
}
}
}
}
#endif
qstrncpy(outbuf, cpu_string.toUtf8().constData(), len);
}
void
plat_set_thread_name(void *thread, const char *name)
{
#ifdef Q_OS_WINDOWS
/* SetThreadDescription was added in 14393. Revisit if we ever start requiring 10. */
static void *kernel32_handle = NULL;
static HRESULT(WINAPI *pSetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription) = NULL;
static dllimp_t kernel32_imports[] = {
// clang-format off
{ "SetThreadDescription", &pSetThreadDescription },
{ NULL, NULL }
// clang-format on
};
if (!kernel32_handle) {
kernel32_handle = dynld_module("kernel32.dll", kernel32_imports);
if (!kernel32_handle) {
kernel32_handle = kernel32_imports; /* store dummy pointer to avoid trying again */
pSetThreadDescription = NULL;
}
}
if (pSetThreadDescription) {
size_t len = strlen(name) + 1;
wchar_t wname[len + 1];
mbstowcs(wname, name, len);
pSetThreadDescription(thread ? (HANDLE) thread : GetCurrentThread(), wname);
}
#else
# ifdef Q_OS_DARWIN
if (thread) /* Apple pthread can only set self's name */
return;
char truncated[64];
# else
char truncated[16];
# endif
strncpy(truncated, name, sizeof(truncated) - 1);
# ifdef Q_OS_DARWIN
pthread_setname_np(truncated);
# else
pthread_setname_np(thread ? *((pthread_t *) thread) : pthread_self(), truncated);
# endif
#endif
}
``` | /content/code_sandbox/src/qt/qt_platform.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 6,262 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* evdev keyboard input module.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
#include <unordered_map>
#include <QtDebug>
static std::unordered_map<uint32_t, uint16_t> evdev_keycodes = {
{184, 0x46}, /* F14 => Scroll Lock (for Apple keyboards) */
{86, 0x56}, /* 102ND */
{87, 0x57}, /* F11 */
{88, 0x58}, /* F12 */
{186, 0x5d}, /* F16 => F13 */
{187, 0x5e}, /* F17 => F14 */
{188, 0x5f}, /* F18 => F15 */
/* Japanese keys. */
{95, 0x5c}, /* KPJPCOMMA */
{93, 0x70}, /* KATAKANAHIRAGANA */
{89, 0x73}, /* RO */
{85, 0x76}, /* ZENKAKUHANKAKU */
{91, 0x77}, /* HIRAGANA */
{90, 0x78}, /* KATAKANA */
{92, 0x79}, /* HENKAN */
{94, 0x7b}, /* MUHENKAN */
{124, 0x7d}, /* YEN */
{121, 0x7e}, /* KPCOMMA */
/* Korean keys. */
{123, 0xf1}, /* HANJA */
{122, 0xf2}, /* HANGUL */
{96, 0x11c}, /* KPENTER */
{97, 0x11d}, /* RIGHTCTRL */
{98, 0x135}, /* KPSLASH */
{99, 0x137}, /* SYSRQ */
{183, 0x137}, /* F13 => SysRq (for Apple keyboards) */
{100, 0x138}, /* RIGHTALT */
{119, 0x145}, /* PAUSE */
{411, 0x145}, /* BREAK */
{185, 0x145}, /* F15 => Pause (for Apple keyboards) */
{102, 0x147}, /* HOME */
{103, 0x148}, /* UP */
{104, 0x149}, /* PAGEUP */
{105, 0x14b}, /* LEFT */
{106, 0x14d}, /* RIGHT */
{107, 0x14f}, /* END */
{108, 0x150}, /* DOWN */
{109, 0x151}, /* PAGEDOWN */
{110, 0x152}, /* INSERT */
{111, 0x153}, /* DELETE */
{125, 0x15b}, /* LEFTMETA */
{126, 0x15c}, /* RIGHTMETA */
{127, 0x15d}, /* COMPOSE => Menu */
/* Multimedia keys. Guideline is to try and follow the Microsoft standard, then
fill in remaining scancodes with OEM-specific keys for redundancy sake. Keys
marked with # are not translated into evdev codes by the standard atkbd driver. */
{634, 0x54}, /* SELECTIVE_SCREENSHOT# => Alt+SysRq */
{117, 0x59}, /* KPEQUAL */
{418, 0x6a}, /* ZOOMIN# => Logitech */
{420, 0x6b}, /* ZOOMRESET# => Logitech */
{223, 0x6d}, /* CANCEL# => Logitech */
{132, 0x101}, /* # Logitech Task Select */
{148, 0x102}, /* PROG1# => Samsung */
{149, 0x103}, /* PROG2# => Samsung */
{419, 0x104}, /* ZOOMOUT# => Logitech */
{144, 0x105}, /* FILE# => Messenger/Files */
{216, 0x105}, /* CHAT# => Messenger/Files */
{430, 0x105}, /* MESSENGER# */
{182, 0x107}, /* REDO# */
{131, 0x108}, /* UNDO# */
{135, 0x10a}, /* PASTE# */
{177, 0x10b}, /* SCROLLUP# => normal speed */
{165, 0x110}, /* PREVIOUSSONG */
{136, 0x112}, /* FIND# => Logitech */
{421, 0x113}, /* WORDPROCESSOR# => Word */
{423, 0x114}, /* SPREADSHEET# => Excel */
{397, 0x115}, /* CALENDAR# */
{433, 0x116}, /* LOGOFF# */
{137, 0x117}, /* CUT# */
{133, 0x118}, /* COPY# */
{163, 0x119}, /* NEXTSONG */
{154, 0x11e}, /* CYCLEWINDOWS => Application Right (no left counterpart) */
{113, 0x120}, /* MUTE */
{140, 0x121}, /* CALC */
{164, 0x122}, /* PLAYPAUSE */
{432, 0x123}, /* SPELLCHECK# */
{166, 0x124}, /* STOPCD */
{139, 0x126}, /* MENU# => Shortcut/Menu/Help for a few OEMs */
{114, 0x12e}, /* VOL- */
{160, 0x12f}, /* CLOSECD# => Logitech Eject */
{161, 0x12f}, /* EJECTCD# => Logitech */
{162, 0x12f}, /* EJECTCLOSECD# => Logitech */
{115, 0x130}, /* VOL+ */
{150, 0x132}, /* WWW# */
{172, 0x132}, /* HOMEPAGE */
{138, 0x13b}, /* HELP# */
{213, 0x13c}, /* SOUND# => My Music/Office Home */
{360, 0x13c}, /* VENDOR# => My Music/Office Home */
{204, 0x13d}, /* DASHBOARD# => Task Pane */
{181, 0x13e}, /* NEW# */
{134, 0x13f}, /* OPEN# */
{206, 0x140}, /* CLOSE# */
{232, 0x141}, /* REPLY# */
{233, 0x142}, /* FORWARDMAIL# */
{231, 0x143}, /* SEND# */
{151, 0x144}, /* MSDOS# */
{112, 0x14c}, /* MACRO */
{179, 0x14c}, /* KPLEFTPAREN# */
{118, 0x14e}, /* KPPLUSMINUS */
{235, 0x155}, /* DOCUMENTS# => Logitech */
{234, 0x157}, /* SAVE# */
{210, 0x158}, /* PRINT# */
{116, 0x15e}, /* POWER */
{142, 0x15f}, /* SLEEP */
{143, 0x163}, /* WAKEUP */
{180, 0x164}, /* KPRIGHTPAREN# */
{212, 0x164}, /* CAMERA# => My Pictures */
{217, 0x165}, /* SEARCH */
{156, 0x166}, /* BOOKMARKS => Favorites */
{364, 0x166}, /* FAVORITES# */
{173, 0x167}, /* REFRESH */
{128, 0x168}, /* STOP */
{159, 0x169}, /* FORWARD */
{158, 0x16a}, /* BACK */
{157, 0x16b}, /* COMPUTER */
{155, 0x16c}, /* MAIL */
{215, 0x16c}, /* EMAIL# */
{226, 0x16d}, /* MEDIA */
{167, 0x178}, /* RECORD# => Logitech */
{152, 0x17a}, /* COFFEE/SCREENLOCK# */
{178, 0x18b}, /* SCROLLDOWN# => normal speed */
};
uint16_t
evdev_translate(uint32_t keycode)
{
/* "for 1-83 (0x01-0x53) scancode equals keycode" */
auto ret = (keycode <= 0x53) ? keycode : evdev_keycodes[keycode];
if (!ret)
qWarning() << "Evdev Keyboard: Unknown key" << keycode;
#if 0
else
qInfo() << "Evdev Keyboard: Key" << keycode << "scancode" << QString::number(ret, 16);
#endif
return ret;
}
``` | /content/code_sandbox/src/qt/evdev_keyboard.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,112 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Sound gain dialog UI module.
*
*
*
* Authors: Cacodemon345
*
*/
#include "qt_soundgain.hpp"
#include "ui_qt_soundgain.h"
extern "C" {
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/sound.h>
}
SoundGain::SoundGain(QWidget *parent)
: QDialog(parent)
, ui(new Ui::SoundGain)
{
ui->setupUi(this);
ui->verticalSlider->setValue(sound_gain);
sound_gain_orig = sound_gain;
}
SoundGain::~SoundGain()
{
delete ui;
}
void
SoundGain::on_verticalSlider_valueChanged(int value)
{
sound_gain = value;
}
void
SoundGain::on_SoundGain_rejected()
{
sound_gain = sound_gain_orig;
}
``` | /content/code_sandbox/src/qt/qt_soundgain.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 245 |
```c++
#include "qt_vulkanwindowrenderer.hpp"
#include <QMessageBox>
#include <QWindow>
#if QT_CONFIG(vulkan)
# include <QVulkanWindowRenderer>
# include <QVulkanDeviceFunctions>
# include <array>
# include <stdexcept>
# include "qt_mainwindow.hpp"
# include "qt_vulkanrenderer.hpp"
extern "C" {
# include <86box/86box.h>
# include <86box/video.h>
}
# if 0
extern MainWindow* main_window;
/*
#version 450
layout(location = 0) out vec2 v_texcoord;
mat4 mvp = mat4(
vec4(1.0, 0, 0, 0),
vec4(0, 1.0, 0, 0),
vec4(0, 0, 1.0, 0),
vec4(0, 0, 0, 1.0)
);
// Y coordinate in Vulkan viewport space is flipped as compared to OpenGL.
vec4 vertCoords[4] = vec4[](
vec4(-1.0, -1.0, 0, 1),
vec4(1.0, -1.0, 0, 1),
vec4(-1.0, 1.0, 0, 1),
vec4(1.0, 1.0, 0, 1)
);
layout(push_constant) uniform texCoordBuf {
vec2 texCoords[4];
} texCoordUniform;
out gl_PerVertex { vec4 gl_Position; };
void main()
{
v_texcoord = texCoordUniform.texCoords[gl_VertexIndex];
gl_Position = mvp * vertCoords[gl_VertexIndex];
}
*/
// Compiled with glslangValidator -V
static const uint8_t vertShaderCode[] = {
0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x00, 0x08, 0x00,
0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,
0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00,
0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30,
0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
0x1f, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00,
0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0xc2, 0x01, 0x00, 0x00,
0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x6d, 0x76, 0x70, 0x00, 0x05, 0x00, 0x05, 0x00, 0x16, 0x00, 0x00, 0x00,
0x76, 0x65, 0x72, 0x74, 0x43, 0x6f, 0x6f, 0x72, 0x64, 0x73, 0x00, 0x00,
0x05, 0x00, 0x05, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x76, 0x5f, 0x74, 0x65,
0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
0x21, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6f, 0x72, 0x64,
0x42, 0x75, 0x66, 0x00, 0x06, 0x00, 0x06, 0x00, 0x21, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6f, 0x72, 0x64,
0x73, 0x00, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00, 0x23, 0x00, 0x00, 0x00,
0x74, 0x65, 0x78, 0x43, 0x6f, 0x6f, 0x72, 0x64, 0x55, 0x6e, 0x69, 0x66,
0x6f, 0x72, 0x6d, 0x00, 0x05, 0x00, 0x06, 0x00, 0x27, 0x00, 0x00, 0x00,
0x67, 0x6c, 0x5f, 0x56, 0x65, 0x72, 0x74, 0x65, 0x78, 0x49, 0x6e, 0x64,
0x65, 0x78, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00, 0x2c, 0x00, 0x00, 0x00,
0x67, 0x6c, 0x5f, 0x50, 0x65, 0x72, 0x56, 0x65, 0x72, 0x74, 0x65, 0x78,
0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x2c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74,
0x69, 0x6f, 0x6e, 0x00, 0x05, 0x00, 0x03, 0x00, 0x2e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x1f, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x20, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x48, 0x00, 0x05, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00,
0x21, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x27, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00,
0x48, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00,
0x2c, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00,
0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x18, 0x00, 0x04, 0x00,
0x08, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f,
0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x07, 0x00,
0x07, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x2c, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x07, 0x00,
0x08, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00,
0x0e, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x15, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00,
0x13, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x04, 0x00,
0x14, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x15, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x15, 0x00, 0x00, 0x00,
0x16, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xbf,
0x2c, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x17, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00,
0x19, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x07, 0x00,
0x07, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x2c, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x07, 0x00, 0x14, 0x00, 0x00, 0x00,
0x1c, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00,
0x1a, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00,
0x1d, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x1d, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x1e, 0x00, 0x00, 0x00,
0x1f, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x04, 0x00,
0x20, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x03, 0x00, 0x21, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x22, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
0x21, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x22, 0x00, 0x00, 0x00,
0x23, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00,
0x24, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x2b, 0x00, 0x04, 0x00, 0x24, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x26, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x26, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x29, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
0x1d, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x2c, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x2d, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x2d, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x31, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x35, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00,
0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x16, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x24, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x29, 0x00, 0x00, 0x00,
0x2a, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00,
0x28, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x1d, 0x00, 0x00, 0x00,
0x2b, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0x1f, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x08, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x24, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x31, 0x00, 0x00, 0x00,
0x32, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00,
0x32, 0x00, 0x00, 0x00, 0x91, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00,
0x34, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00,
0x41, 0x00, 0x05, 0x00, 0x35, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00,
0x2e, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0x36, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00,
0x38, 0x00, 0x01, 0x00
};
/*
#version 440
layout(location = 0) in vec2 v_texcoord;
layout(location = 0) out vec4 fragColor;
layout(binding = 1) uniform sampler2D tex;
void main()
{
fragColor = texture(tex, v_texcoord);
}
*/
static const uint8_t fragShaderCode[]
{
0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x00, 0x08, 0x00,
0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,
0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00,
0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30,
0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x07, 0x00, 0x04, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
0x09, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00,
0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00,
0x02, 0x00, 0x00, 0x00, 0xb8, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00,
0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x66, 0x72, 0x61, 0x67,
0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x00, 0x05, 0x00, 0x05, 0x00,
0x11, 0x00, 0x00, 0x00, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f,
0x72, 0x64, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x11, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00,
0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x19, 0x00, 0x09, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x17, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x10, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x3f, 0x15, 0x00, 0x04, 0x00, 0x15, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00,
0x15, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x17, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00,
0x11, 0x00, 0x00, 0x00, 0x57, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00,
0x13, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x09, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x41, 0x00, 0x05, 0x00, 0x17, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x09, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0x18, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00,
0x38, 0x00, 0x01, 0x00
};
class VulkanRendererEmu : public QVulkanWindowRenderer
{
VulkanWindowRenderer* m_window{nullptr};
QVulkanDeviceFunctions* m_devFuncs{nullptr};
VmaAllocator allocator{nullptr};
VmaAllocation allocation{nullptr};
VkImage image{nullptr};
VkImageView imageView{nullptr};
VkPipeline pipeline{nullptr};
VkPipelineLayout pipelineLayout{nullptr};
VkDescriptorSetLayout descLayout{nullptr};
VkDescriptorPool descPool{nullptr};
VkDescriptorSet descSet{nullptr};
VkSampler sampler{nullptr}, nearestSampler{nullptr};
bool imageLayoutTransitioned{false};
int cur_video_filter_method = -1;
private:
void updateOptions() {
VkResult res;
if (cur_video_filter_method == video_filter_method) return;
if (!descPool) {
VkDescriptorPoolSize descSize{};
descSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descSize.descriptorCount = 2;
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = 1;
poolInfo.pPoolSizes = &descSize;
poolInfo.maxSets = 2;
if ((res = m_devFuncs->vkCreateDescriptorPool(m_window->device(), &poolInfo, nullptr, &descPool)) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create descriptor pool. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descLayout;
if ((res = m_devFuncs->vkAllocateDescriptorSets(m_window->device(), &allocInfo, &descSet)) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create descriptor set. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}}
VkDescriptorImageInfo imageDescInfo{};
imageDescInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageDescInfo.imageView = imageView;
imageDescInfo.sampler = video_filter_method == 0 ? nearestSampler : sampler;
VkWriteDescriptorSet descWrite{};
descWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descWrite.dstSet = descSet;
descWrite.dstBinding = 1;
descWrite.dstArrayElement = 0;
descWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descWrite.descriptorCount = 1;
descWrite.pImageInfo = &imageDescInfo;
m_devFuncs->vkUpdateDescriptorSets(m_window->device(), 1, &descWrite, 0, nullptr);
cur_video_filter_method = video_filter_method;
}
public:
void* mappedPtr = nullptr;
uint32_t imagePitch{2048 * 4};
VulkanRendererEmu(VulkanWindowRenderer *w) : m_window(w), m_devFuncs(nullptr) { }
void initResources() override
{
VmaAllocatorCreateInfo info{};
info.instance = m_window->vulkanInstance()->vkInstance();
info.device = m_window->device();
info.physicalDevice = m_window->physicalDevice();
VmaVulkanFunctions funcs{};
funcs.vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)m_window->vulkanInstance()->getInstanceProcAddr("vkGetInstanceProcAddr");
funcs.vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)m_window->vulkanInstance()->getInstanceProcAddr("vkGetDeviceProcAddr");
info.pVulkanFunctions = &funcs;
if (vmaCreateAllocator(&info, &allocator) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create Vulkan allocator. Switch to another renderer");
return;
}
m_devFuncs = m_window->vulkanInstance()->deviceFunctions(m_window->device());
VkResult res;
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.format = VK_FORMAT_B8G8R8A8_UNORM;
imageInfo.extent.width = imageInfo.extent.height = 2048;
imageInfo.extent.depth = imageInfo.arrayLayers = imageInfo.mipLevels = 1;
imageInfo.tiling = VK_IMAGE_TILING_LINEAR;
imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
VmaAllocationInfo allocatedInfo{};
VmaAllocationCreateInfo allocInfo{};
allocInfo.pUserData = allocInfo.pool = nullptr;
allocInfo.requiredFlags = allocInfo.preferredFlags = 0;
allocInfo.usage = VmaMemoryUsage::VMA_MEMORY_USAGE_AUTO;
allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
VMA_ALLOCATION_CREATE_MAPPED_BIT;
if ((res = vmaCreateImage(allocator, &imageInfo, &allocInfo, &image, &allocation, &allocatedInfo)) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create Vulkan image. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
};
VkImageViewCreateInfo imageViewInfo{};
imageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
imageViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
imageViewInfo.format = VK_FORMAT_B8G8R8A8_UNORM;
imageViewInfo.image = image;
imageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageViewInfo.subresourceRange.baseMipLevel = 0;
imageViewInfo.subresourceRange.levelCount = 1;
imageViewInfo.subresourceRange.baseArrayLayer = 0;
imageViewInfo.subresourceRange.layerCount = 1;
imageViewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
imageViewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
imageViewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
imageViewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
if ((res = m_devFuncs->vkCreateImageView(m_window->device(), &imageViewInfo, nullptr, &imageView)) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create Vulkan image view. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}
// Begin Pipeline creation.
{
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 0;
vertexInputInfo.pVertexBindingDescriptions = nullptr;
vertexInputInfo.vertexAttributeDescriptionCount = 0;
vertexInputInfo.pVertexAttributeDescriptions = nullptr;
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
inputAssembly.primitiveRestartEnable = VK_FALSE;
VkRect2D scissor{};
scissor.offset = {0, 0};
scissor.extent = {2048, 2048};
VkViewport viewport{};
viewport.x = m_window->destination.x();
viewport.y = m_window->destination.y();
viewport.width = (float)m_window->destination.width();
viewport.height = (float)m_window->destination.height();
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkPipelineViewportStateCreateInfo viewportState{};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
rasterizer.depthBiasConstantFactor = 0.0f;
rasterizer.depthBiasClamp = 0.0f;
rasterizer.depthBiasSlopeFactor = 0.0f;
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
multisampling.minSampleShading = 1.0f;
multisampling.pSampleMask = nullptr;
multisampling.alphaToCoverageEnable = VK_FALSE;
multisampling.alphaToOneEnable = VK_FALSE;
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachment.blendEnable = VK_TRUE;
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
VkPipelineColorBlendStateCreateInfo colorBlending{};
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment;
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
VkDynamicState dynState = VK_DYNAMIC_STATE_VIEWPORT;
VkPipelineDynamicStateCreateInfo dynamicState{};
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.dynamicStateCount = 1;
dynamicState.pDynamicStates = &dynState;
VkPushConstantRange range{};
range.offset = 0;
range.size = sizeof(float) * 8;
range.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
// Sampler binding start.
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.pImmutableSamplers = nullptr;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
if ((res = m_devFuncs->vkCreateDescriptorSetLayout(m_window->device(), &layoutInfo, nullptr, &descLayout))) {
QMessageBox::critical(main_window, "86Box", "Could not create descriptor set layout. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}
// Sampler binding end.
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descLayout;
pipelineLayoutInfo.pushConstantRangeCount = 1;
pipelineLayoutInfo.pPushConstantRanges = ⦥
if ((res = m_devFuncs->vkCreatePipelineLayout(m_window->device(), &pipelineLayoutInfo, nullptr, &pipelineLayout)) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create pipeline layout. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}
// Shader loading start.
VkShaderModuleCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = sizeof(vertShaderCode);
createInfo.pCode = (uint32_t*)vertShaderCode;
VkShaderModule vertModule{nullptr}, fragModule{nullptr};
if ((res = m_devFuncs->vkCreateShaderModule(m_window->device(), &createInfo, nullptr, &vertModule)) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create vertex shader. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}
createInfo.codeSize = sizeof(fragShaderCode);
createInfo.pCode = (uint32_t*)fragShaderCode;
if ((res = m_devFuncs->vkCreateShaderModule(m_window->device(), &createInfo, nullptr, &fragModule)) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create fragment shader. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}
VkPipelineShaderStageCreateInfo vertShaderStageInfo{};
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertModule;
vertShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo fragShaderStageInfo{vertShaderStageInfo};
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragModule;
VkPipelineShaderStageCreateInfo shaderStages[] = {vertShaderStageInfo, fragShaderStageInfo};
// Shader loading end.
VkPipelineDepthStencilStateCreateInfo depthInfo{};
depthInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depthInfo.pNext = nullptr;
depthInfo.depthTestEnable = VK_TRUE;
depthInfo.depthWriteEnable = VK_TRUE;
depthInfo.depthBoundsTestEnable = VK_FALSE;
depthInfo.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
depthInfo.stencilTestEnable = VK_FALSE;
depthInfo.maxDepthBounds = 1.0f;
VkGraphicsPipelineCreateInfo pipelineInfo{};
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages;
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pDepthStencilState = &depthInfo;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDynamicState = &dynamicState;
pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = m_window->defaultRenderPass();
pipelineInfo.subpass = 0;
if ((res = m_devFuncs->vkCreateGraphicsPipelines(m_window->device(), VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline)) != VK_SUCCESS) {
m_devFuncs->vkDestroyShaderModule(m_window->device(), vertModule, nullptr);
m_devFuncs->vkDestroyShaderModule(m_window->device(), fragModule, nullptr);
QMessageBox::critical(main_window, "86Box", "Could not create graphics pipeline. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}
m_devFuncs->vkDestroyShaderModule(m_window->device(), vertModule, nullptr);
m_devFuncs->vkDestroyShaderModule(m_window->device(), fragModule, nullptr);
}
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.anisotropyEnable = VK_FALSE;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = 0.0;
if ((res = m_devFuncs->vkCreateSampler(m_window->device(), &samplerInfo, nullptr, &sampler)) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create linear image sampler. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}
samplerInfo.magFilter = samplerInfo.minFilter = VK_FILTER_NEAREST;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
if ((res = m_devFuncs->vkCreateSampler(m_window->device(), &samplerInfo, nullptr, &nearestSampler)) != VK_SUCCESS) {
QMessageBox::critical(main_window, "86Box", "Could not create nearest image sampler. Switch to another renderer. " + Vulkan_GetResultString(res));
return;
}
updateOptions();
VkImageSubresource resource{};
resource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
resource.arrayLayer = 0;
resource.mipLevel = 0;
VkSubresourceLayout layout{};
m_devFuncs->vkGetImageSubresourceLayout(m_window->device(), image, &resource, &layout);
imagePitch = layout.rowPitch;
mappedPtr = (uint8_t*)allocatedInfo.pMappedData + layout.offset;
emit m_window->rendererInitialized();
}
void releaseResources() override
{
if (pipeline) m_devFuncs->vkDestroyPipeline(m_window->device(), pipeline, nullptr);
if (pipelineLayout) m_devFuncs->vkDestroyPipelineLayout(m_window->device(), pipelineLayout, nullptr);
if (descSet) m_devFuncs->vkDestroyDescriptorPool(m_window->device(), descPool, nullptr);
if (descLayout) m_devFuncs->vkDestroyDescriptorSetLayout(m_window->device(), descLayout, nullptr);
if (imageView) m_devFuncs->vkDestroyImageView(m_window->device(), imageView, nullptr);
if (image) vmaDestroyImage(allocator, image, allocation);
if (sampler) m_devFuncs->vkDestroySampler(m_window->device(), sampler, nullptr);
if (nearestSampler) m_devFuncs->vkDestroySampler(m_window->device(), nearestSampler, nullptr);
image = nullptr;
pipeline = nullptr;
pipelineLayout = nullptr;
imageView = nullptr;
descLayout = nullptr;
descPool = nullptr;
descSet = nullptr;
sampler = nullptr;
vmaDestroyAllocator(allocator);
allocator = nullptr;
}
QString Vulkan_GetResultString(VkResult result)
{
switch ((int)result) {
case VK_SUCCESS:
return "VK_SUCCESS";
case VK_NOT_READY:
return "VK_NOT_READY";
case VK_TIMEOUT:
return "VK_TIMEOUT";
case VK_EVENT_SET:
return "VK_EVENT_SET";
case VK_EVENT_RESET:
return "VK_EVENT_RESET";
case VK_INCOMPLETE:
return "VK_INCOMPLETE";
case VK_ERROR_OUT_OF_HOST_MEMORY:
return "VK_ERROR_OUT_OF_HOST_MEMORY";
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
case VK_ERROR_INITIALIZATION_FAILED:
return "VK_ERROR_INITIALIZATION_FAILED";
case VK_ERROR_DEVICE_LOST:
return "VK_ERROR_DEVICE_LOST";
case VK_ERROR_MEMORY_MAP_FAILED:
return "VK_ERROR_MEMORY_MAP_FAILED";
case VK_ERROR_LAYER_NOT_PRESENT:
return "VK_ERROR_LAYER_NOT_PRESENT";
case VK_ERROR_EXTENSION_NOT_PRESENT:
return "VK_ERROR_EXTENSION_NOT_PRESENT";
case VK_ERROR_FEATURE_NOT_PRESENT:
return "VK_ERROR_FEATURE_NOT_PRESENT";
case VK_ERROR_INCOMPATIBLE_DRIVER:
return "VK_ERROR_INCOMPATIBLE_DRIVER";
case VK_ERROR_TOO_MANY_OBJECTS:
return "VK_ERROR_TOO_MANY_OBJECTS";
case VK_ERROR_FORMAT_NOT_SUPPORTED:
return "VK_ERROR_FORMAT_NOT_SUPPORTED";
case VK_ERROR_FRAGMENTED_POOL:
return "VK_ERROR_FRAGMENTED_POOL";
case VK_ERROR_UNKNOWN:
return "VK_ERROR_UNKNOWN";
case VK_ERROR_OUT_OF_POOL_MEMORY:
return "VK_ERROR_OUT_OF_POOL_MEMORY";
case VK_ERROR_INVALID_EXTERNAL_HANDLE:
return "VK_ERROR_INVALID_EXTERNAL_HANDLE";
case VK_ERROR_FRAGMENTATION:
return "VK_ERROR_FRAGMENTATION";
case VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS:
return "VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS";
case VK_ERROR_SURFACE_LOST_KHR:
return "VK_ERROR_SURFACE_LOST_KHR";
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR:
return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR";
case VK_SUBOPTIMAL_KHR:
return "VK_SUBOPTIMAL_KHR";
case VK_ERROR_OUT_OF_DATE_KHR:
return "VK_ERROR_OUT_OF_DATE_KHR";
case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR:
return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR";
case VK_ERROR_VALIDATION_FAILED_EXT:
return "VK_ERROR_VALIDATION_FAILED_EXT";
case VK_ERROR_INVALID_SHADER_NV:
return "VK_ERROR_INVALID_SHADER_NV";
# if VK_HEADER_VERSION >= 135 && VK_HEADER_VERSION < 162
case VK_ERROR_INCOMPATIBLE_VERSION_KHR:
return "VK_ERROR_INCOMPATIBLE_VERSION_KHR";
# endif
case VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT:
return "VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT";
case VK_ERROR_NOT_PERMITTED_EXT:
return "VK_ERROR_NOT_PERMITTED_EXT";
case VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT:
return "VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT";
case VK_THREAD_IDLE_KHR:
return "VK_THREAD_IDLE_KHR";
case VK_THREAD_DONE_KHR:
return "VK_THREAD_DONE_KHR";
case VK_OPERATION_DEFERRED_KHR:
return "VK_OPERATION_DEFERRED_KHR";
case VK_OPERATION_NOT_DEFERRED_KHR:
return "VK_OPERATION_NOT_DEFERRED_KHR";
case VK_PIPELINE_COMPILE_REQUIRED_EXT:
return "VK_PIPELINE_COMPILE_REQUIRED_EXT";
default:
break;
}
if (result < 0) {
return "VK_ERROR_<Unknown>";
}
return "VK_<Unknown>";
}
void startNextFrame() override
{
m_devFuncs->vkDeviceWaitIdle(m_window->device());
VkClearValue values[2];
auto cmdBufs = m_window->currentCommandBuffer();
memset(values, 0, sizeof(values));
values[0].depthStencil = { 1, 0 };
values[1].depthStencil = { 1, 0 };
VkRenderPassBeginInfo info{};
VkSubpassDependency deps{};
info.pClearValues = values;
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
info.framebuffer = m_window->currentFramebuffer();
info.renderArea = VkRect2D{{0, 0}, {(uint32_t)m_window->swapChainImageSize().width(), (uint32_t)m_window->swapChainImageSize().height()}};
info.clearValueCount = 2;
info.renderPass = m_window->defaultRenderPass();
updateOptions();
if (!imageLayoutTransitioned) {
VkPipelineStageFlags srcflags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | VK_PIPELINE_STAGE_HOST_BIT, dstflags = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.image = image;
barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
m_devFuncs->vkCmdPipelineBarrier(cmdBufs, srcflags, dstflags, 0, 0, nullptr, 0, nullptr, 1, &barrier);
imageLayoutTransitioned = true;
}
vmaFlushAllocation(allocator, allocation, 0, VK_WHOLE_SIZE);
VkViewport viewport{};
viewport.x = m_window->destination.x();
viewport.y = m_window->destination.y();
viewport.width = (float)m_window->destination.width();
viewport.height = (float)m_window->destination.height();
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
m_devFuncs->vkCmdSetViewport(cmdBufs, 0, 1, &viewport);
m_devFuncs->vkCmdBeginRenderPass(m_window->currentCommandBuffer(), &info, VK_SUBPASS_CONTENTS_INLINE);
m_devFuncs->vkCmdBindPipeline(cmdBufs, VkPipelineBindPoint::VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
m_devFuncs->vkCmdBindDescriptorSets(cmdBufs, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descSet, 0, nullptr);
std::array<QVector2D, 4> texcoords;
auto source = m_window->source;
texcoords[0] = (QVector2D((float)source.x() / 2048.f, (float)(source.y()) / 2048.f));
texcoords[2] = (QVector2D((float)source.x() / 2048.f, (float)(source.y() + source.height()) / 2048.f));
texcoords[1] = (QVector2D((float)(source.x() + source.width()) / 2048.f, (float)(source.y()) / 2048.f));
texcoords[3] = (QVector2D((float)(source.x() + source.width()) / 2048.f, (float)(source.y() + source.height()) / 2048.f));
m_devFuncs->vkCmdPushConstants(cmdBufs, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(QVector2D) * 4, texcoords.data());
m_devFuncs->vkCmdDraw(cmdBufs, 4, 1, 0, 0);
m_devFuncs->vkCmdEndRenderPass(cmdBufs);
m_window->frameReady();
m_devFuncs->vkDeviceWaitIdle(m_window->device());
}
};
# endif
VulkanWindowRenderer::VulkanWindowRenderer(QWidget *parent)
: QVulkanWindow(parent->windowHandle())
{
parentWidget = parent;
instance.setApiVersion(QVersionNumber(1, 0));
instance.create();
setVulkanInstance(&instance);
setPhysicalDeviceIndex(0);
setPreferredColorFormats({ VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_A8B8G8R8_UNORM_PACK32 });
setFlags(Flag::PersistentResources);
buf_usage = std::vector<std::atomic_flag>(1);
buf_usage[0].clear();
}
QVulkanWindowRenderer *
VulkanWindowRenderer::createRenderer()
{
renderer = new VulkanRenderer2(this);
return renderer;
}
void
VulkanWindowRenderer::resizeEvent(QResizeEvent *event)
{
onResize(width(), height());
QVulkanWindow::resizeEvent(event);
}
bool
VulkanWindowRenderer::event(QEvent *event)
{
bool res = false;
if (!eventDelegate(event, res))
return QVulkanWindow::event(event);
return res;
}
void
VulkanWindowRenderer::onBlit(int buf_idx, int x, int y, int w, int h)
{
auto origSource = source;
source.setRect(x, y, w, h);
if (isExposed())
requestUpdate();
buf_usage[0].clear();
if (origSource != source)
onResize(this->width(), this->height());
}
uint32_t
VulkanWindowRenderer::getBytesPerRow()
{
return renderer->imagePitch;
}
std::vector<std::tuple<uint8_t *, std::atomic_flag *>>
VulkanWindowRenderer::getBuffers()
{
return std::vector { std::make_tuple((uint8_t *) renderer->mappedPtr, &this->buf_usage[0]) };
}
#endif
``` | /content/code_sandbox/src/qt/qt_vulkanwindowrenderer.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 17,772 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Header file for OpenGL renderer
*
*
*
* Authors: Teemu Korhonen
*
*/
#ifndef QT_OPENGLRENDERER_HPP
#define QT_OPENGLRENDERER_HPP
#if defined Q_OS_MACOS || __arm__
# define NO_BUFFER_STORAGE
#endif
#include <QOpenGLContext>
#include <QOpenGLExtraFunctions>
#include <QResizeEvent>
#include <QTimer>
#include <QWidget>
#include <QWindow>
#if !defined NO_BUFFER_STORAGE && !(QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
# include <QtOpenGLExtensions/QOpenGLExtensions>
#endif
#include <atomic>
#include <stdexcept>
#include <tuple>
#include <vector>
#include "qt_opengloptions.hpp"
#include "qt_renderercommon.hpp"
typedef void(QOPENGLF_APIENTRYP PFNGLBUFFERSTORAGEEXTPROC_LOCAL)(GLenum target, GLsizeiptr size, const void *data, GLbitfield flags);
class OpenGLRenderer : public QWindow, protected QOpenGLExtraFunctions, public RendererCommon {
Q_OBJECT
public:
QOpenGLContext *context;
OpenGLRenderer(QWidget *parent = nullptr);
~OpenGLRenderer();
std::vector<std::tuple<uint8_t *, std::atomic_flag *>> getBuffers() override;
void finalize() override final;
bool hasOptions() const override { return true; }
QDialog *getOptions(QWidget *parent) override;
void reloadOptions() override;
signals:
void initialized();
void errorInitializing();
public slots:
void onBlit(int buf_idx, int x, int y, int w, int h);
protected:
void exposeEvent(QExposeEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
bool event(QEvent *event) override;
private:
static constexpr int INIT_WIDTH = 640;
static constexpr int INIT_HEIGHT = 400;
static constexpr int ROW_LENGTH = 2048;
static constexpr int BUFFERPIXELS = 4194304;
static constexpr int BUFFERBYTES = 16777216; /* Pixel is 4 bytes. */
static constexpr int BUFFERCOUNT = 3; /* How many buffers to use for pixel transfer (2-3 is commonly recommended). */
QTimer *renderTimer;
OpenGLOptions *options;
QString glslVersion;
bool isInitialized = false;
bool isFinalized = false;
GLuint unpackBufferID = 0;
GLuint vertexArrayID = 0;
GLuint vertexBufferID = 0;
GLuint textureID = 0;
int frameCounter = 0;
OpenGLOptions::FilterType currentFilter;
void *unpackBuffer = nullptr;
void initialize();
void initializeExtensions();
void initializeBuffers();
void applyOptions();
void applyShader(const OpenGLShaderPass &shader);
bool notReady() const { return !isInitialized || isFinalized; }
/* GL_ARB_buffer_storage */
bool hasBufferStorage = false;
#ifndef NO_BUFFER_STORAGE
PFNGLBUFFERSTORAGEEXTPROC_LOCAL glBufferStorage = nullptr;
#endif
private slots:
void render();
void updateOptions(OpenGLOptions *newOptions);
};
class opengl_init_error : public std::runtime_error {
public:
opengl_init_error(const QString &what)
: std::runtime_error(what.toStdString())
{
}
};
#endif
``` | /content/code_sandbox/src/qt/qt_openglrenderer.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 799 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation POSIX OpenDir(3) and friends for Win32 API.
*
* Based on old original code @(#)dir_win32.c 1.2.0 2007/04/19
*
*
*
* Authors: Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <io.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/plat_dir.h>
#define SUFFIX "\\*"
#define FINDATA struct _finddata_t
#define FINDFIRST _findfirst
#define FINDNEXT _findnext
/* Open a directory. */
DIR *
opendir(const char *name)
{
DIR *p;
/* Create a new control structure. */
p = (DIR *) malloc(sizeof(DIR));
if (p == NULL)
return (NULL);
memset(p, 0x00, sizeof(DIR));
p->flags = (DIR_F_LOWER | DIR_F_SANE);
p->offset = 0;
p->sts = 0;
/* Create a work area. */
p->dta = (char *) malloc(sizeof(FINDATA));
if (p->dta == NULL) {
free(p);
return (NULL);
}
memset(p->dta, 0x00, sizeof(struct _finddata_t));
/* Add search filespec. */
strcpy(p->dir, name);
strcat(p->dir, SUFFIX);
/* Special case: flag if we are in the root directory. */
if (strlen(p->dir) == 3)
p->flags |= DIR_F_ISROOT;
/* Start the searching by doing a FindFirst. */
p->handle = FINDFIRST(p->dir, (FINDATA *) p->dta);
if (p->handle < 0L) {
free(p->dta);
free(p);
return (NULL);
}
/* All OK. */
return p;
}
/* Close an open directory. */
int
closedir(DIR *p)
{
if (p == NULL)
return 0;
_findclose(p->handle);
if (p->dta != NULL)
free(p->dta);
free(p);
return 0;
}
/*
* Read the next entry from a directory.
* Note that the DOS (FAT), Windows (FAT, FAT32) and Windows NTFS
* file systems do not have a root directory containing the UNIX-
* standard "." and ".." entries. Many applications do assume
* this anyway, so we simply fake these entries.
*/
struct dirent *
readdir(DIR *p)
{
FINDATA *ffp;
if (p == NULL || p->sts == 1)
return (NULL);
/* Format structure with current data. */
ffp = (FINDATA *) p->dta;
p->dent.d_ino = 1L;
p->dent.d_off = p->offset++;
switch (p->offset) {
case 1: /* . */
strncpy(p->dent.d_name, ".", MAXNAMLEN + 1);
p->dent.d_reclen = 1;
break;
case 2: /* .. */
strncpy(p->dent.d_name, "..", MAXNAMLEN + 1);
p->dent.d_reclen = 2;
break;
default: /* regular entry. */
strncpy(p->dent.d_name, ffp->name, MAXNAMLEN + 1);
p->dent.d_reclen = (char) strlen(p->dent.d_name);
}
/* Read next entry. */
p->sts = 0;
/* Fake the "." and ".." entries here.. */
if ((p->flags & DIR_F_ISROOT) && (p->offset <= 2))
return (&(p->dent));
/* Get the next entry if we did not fake the above. */
if (FINDNEXT(p->handle, ffp) < 0)
p->sts = 1;
return (&(p->dent));
}
/* Report current position within the directory. */
long
telldir(DIR *p)
{
return (p->offset);
}
void
seekdir(DIR *p, long newpos)
{
short pos;
/* First off, rewind to start of directory. */
p->handle = FINDFIRST(p->dir, (FINDATA *) p->dta);
if (p->handle < 0L) {
p->sts = 1;
return;
}
p->offset = 0;
p->sts = 0;
/* If we are rewinding, that's all... */
if (newpos == 0L)
return;
/* Nope.. read entries until we hit the right spot. */
pos = (short) newpos;
while (p->offset != pos) {
p->offset++;
if (FINDNEXT(p->handle, (FINDATA *) p->dta) < 0) {
p->sts = 1;
return;
}
}
}
``` | /content/code_sandbox/src/qt/win_opendir.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,207 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Definitions for platform specific serial to host passthrough
*
*
* Authors: Andreas J. Reichel <webmaster@6th-dimension.com>,
* Jasmine Iwanek <jasmine@iwanek.co.uk>
*
*/
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/log.h>
#include <86box/timer.h>
#include <86box/plat.h>
#include <86box/device.h>
#include <86box/serial_passthrough.h>
#include <86box/plat_serial_passthrough.h>
#include <86box/ui.h>
#include <windows.h>
#define LOG_PREFIX "serial_passthrough: "
void
plat_serpt_close(void *priv)
{
serial_passthrough_t *dev = (serial_passthrough_t *) priv;
#if 0
fclose(dev->master_fd);
#endif
FlushFileBuffers((HANDLE) dev->master_fd);
if (dev->mode == SERPT_MODE_VCON)
DisconnectNamedPipe((HANDLE) dev->master_fd);
if (dev->mode == SERPT_MODE_HOSTSER) {
SetCommState((HANDLE) dev->master_fd, (DCB *) dev->backend_priv);
free(dev->backend_priv);
}
CloseHandle((HANDLE) dev->master_fd);
}
static void
plat_serpt_write_vcon(serial_passthrough_t *dev, uint8_t data)
{
#if 0
fd_set wrfds;
int res;
#endif
/* We cannot use select here, this would block the hypervisor! */
#if 0
FD_ZERO(&wrfds);
FD_SET(ctx->master_fd, &wrfds);
res = select(ctx->master_fd + 1, NULL, &wrfds, NULL, NULL);
if (res <= 0)
return;
#endif
/* just write it out */
#if 0
fwrite(dev->master_fd, &data, 1);
#endif
DWORD bytesWritten = 0;
WriteFile((HANDLE) dev->master_fd, &data, 1, &bytesWritten, NULL);
}
void
plat_serpt_set_params(void *priv)
{
const serial_passthrough_t *dev = (serial_passthrough_t *) priv;
if (dev->mode == SERPT_MODE_HOSTSER) {
DCB serialattr = {};
GetCommState((HANDLE) dev->master_fd, &serialattr);
#define BAUDRATE_RANGE(baud_rate, min, max) \
if (baud_rate >= min && baud_rate < max) { \
serialattr.BaudRate = min; \
}
BAUDRATE_RANGE(dev->baudrate, 110, 300);
BAUDRATE_RANGE(dev->baudrate, 300, 600);
BAUDRATE_RANGE(dev->baudrate, 600, 1200);
BAUDRATE_RANGE(dev->baudrate, 1200, 2400);
BAUDRATE_RANGE(dev->baudrate, 2400, 4800);
BAUDRATE_RANGE(dev->baudrate, 4800, 9600);
BAUDRATE_RANGE(dev->baudrate, 9600, 14400);
BAUDRATE_RANGE(dev->baudrate, 14400, 19200);
BAUDRATE_RANGE(dev->baudrate, 19200, 38400);
BAUDRATE_RANGE(dev->baudrate, 38400, 57600);
BAUDRATE_RANGE(dev->baudrate, 57600, 115200);
BAUDRATE_RANGE(dev->baudrate, 115200, 0xFFFFFFFF);
serialattr.ByteSize = dev->data_bits;
serialattr.StopBits = (dev->serial->lcr & 0x04) ? TWOSTOPBITS : ONESTOPBIT;
if (!(dev->serial->lcr & 0x08)) {
serialattr.fParity = 0;
serialattr.Parity = NOPARITY;
} else {
serialattr.fParity = 1;
if (dev->serial->lcr & 0x20) {
serialattr.Parity = MARKPARITY + !!(dev->serial->lcr & 0x10);
} else {
serialattr.Parity = ODDPARITY + !!(dev->serial->lcr & 0x10);
}
}
SetCommState((HANDLE) dev->master_fd, &serialattr);
#undef BAUDRATE_RANGE
}
}
void
plat_serpt_write(void *priv, uint8_t data)
{
serial_passthrough_t *dev = (serial_passthrough_t *) priv;
switch (dev->mode) {
case SERPT_MODE_VCON:
case SERPT_MODE_HOSTSER:
plat_serpt_write_vcon(dev, data);
break;
default:
break;
}
}
uint8_t
plat_serpt_read_vcon(serial_passthrough_t *dev, uint8_t *data)
{
DWORD bytesRead = 0;
ReadFile((HANDLE) dev->master_fd, data, 1, &bytesRead, NULL);
return !!bytesRead;
}
int
plat_serpt_read(void *priv, uint8_t *data)
{
serial_passthrough_t *dev = (serial_passthrough_t *) priv;
int res = 0;
switch (dev->mode) {
case SERPT_MODE_VCON:
case SERPT_MODE_HOSTSER:
res = plat_serpt_read_vcon(dev, data);
break;
default:
break;
}
return res;
}
static int
open_pseudo_terminal(serial_passthrough_t *dev)
{
char ascii_pipe_name[1024] = { 0 };
strncpy(ascii_pipe_name, dev->named_pipe, sizeof(ascii_pipe_name));
ascii_pipe_name[1023] = '\0';
dev->master_fd = (intptr_t) CreateNamedPipeA(ascii_pipe_name, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT, 1, 65536, 65536, NMPWAIT_USE_DEFAULT_WAIT, NULL);
if (dev->master_fd == (intptr_t) INVALID_HANDLE_VALUE) {
wchar_t errorMsg[1024] = { 0 };
wchar_t finalMsg[1024] = { 0 };
DWORD error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), errorMsg, 1024, NULL);
swprintf(finalMsg, 1024, L"Named Pipe (server, named_pipe=\"%hs\", port=COM%d): %ls\n", ascii_pipe_name, dev->port + 1, errorMsg);
ui_msgbox(MBX_ERROR | MBX_FATAL, finalMsg);
return 0;
}
pclog("Named Pipe @ %s\n", ascii_pipe_name);
return 1;
}
static int
open_host_serial_port(serial_passthrough_t *dev)
{
COMMTIMEOUTS timeouts = {
.ReadIntervalTimeout = MAXDWORD,
.ReadTotalTimeoutConstant = 0,
.ReadTotalTimeoutMultiplier = 0,
.WriteTotalTimeoutMultiplier = 0,
.WriteTotalTimeoutConstant = 1000
};
DCB *serialattr = calloc(1, sizeof(DCB));
if (!serialattr)
return 0;
dev->master_fd = (intptr_t) CreateFileA(dev->host_serial_path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL);
if (dev->master_fd == (intptr_t) INVALID_HANDLE_VALUE) {
free(serialattr);
return 0;
}
if (!SetCommTimeouts((HANDLE) dev->master_fd, &timeouts)) {
pclog(LOG_PREFIX "error setting COM port timeouts.\n");
CloseHandle((HANDLE) dev->master_fd);
free(serialattr);
return 0;
}
GetCommState((HANDLE) dev->master_fd, serialattr);
dev->backend_priv = serialattr;
return 1;
}
int
plat_serpt_open_device(void *priv)
{
serial_passthrough_t *dev = (serial_passthrough_t *) priv;
switch (dev->mode) {
case SERPT_MODE_VCON:
if (open_pseudo_terminal(dev)) {
return 0;
}
break;
case SERPT_MODE_HOSTSER:
if (open_host_serial_port(dev)) {
return 0;
}
default:
break;
}
return 1;
}
``` | /content/code_sandbox/src/qt/win_serial_passthrough.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,963 |
```c++
#pragma once
#include <cstdint>
#include "qt_settings_bus_tracking.hpp"
class QString;
class QAbstractItemModel;
class SettingsBusTracking;
namespace Harddrives {
void populateBuses(QAbstractItemModel *model);
void populateRemovableBuses(QAbstractItemModel *model);
void populateBusChannels(QAbstractItemModel *model, int bus, SettingsBusTracking *sbt = nullptr);
void populateSpeeds(QAbstractItemModel *model, int bus);
QString BusChannelName(uint8_t bus, uint8_t channel);
inline SettingsBusTracking *busTrackClass = nullptr;
};
``` | /content/code_sandbox/src/qt/qt_harddrive_common.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 127 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* OpenGL renderer for Qt
*
*
*
* Authors: Teemu Korhonen
*
*/
#include <QCoreApplication>
#include <QMessageBox>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QStringBuilder>
#include <QSurfaceFormat>
#include <cmath>
#include "qt_opengloptionsdialog.hpp"
#include "qt_openglrenderer.hpp"
#ifndef GL_MAP_PERSISTENT_BIT
# define GL_MAP_PERSISTENT_BIT 0x0040
#endif
#ifndef GL_MAP_COHERENT_BIT
# define GL_MAP_COHERENT_BIT 0x0080
#endif
OpenGLRenderer::OpenGLRenderer(QWidget *parent)
: QWindow(parent->windowHandle())
, renderTimer(new QTimer(this))
, options(nullptr)
{
renderTimer->setTimerType(Qt::PreciseTimer);
/* TODO: need's more accuracy, maybe target 1ms earlier and spin yield */
connect(renderTimer, &QTimer::timeout, this, &OpenGLRenderer::render);
buf_usage = std::vector<std::atomic_flag>(BUFFERCOUNT);
for (auto &flag : buf_usage)
flag.clear();
setSurfaceType(QWindow::OpenGLSurface);
QSurfaceFormat format;
#ifdef Q_OS_MACOS
format.setVersion(4, 1);
#else
format.setVersion(3, 2);
#endif
format.setProfile(QSurfaceFormat::OpenGLContextProfile::CoreProfile);
if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES)
format.setRenderableType(QSurfaceFormat::OpenGLES);
setFormat(format);
parentWidget = parent;
source.setRect(0, 0, INIT_WIDTH, INIT_HEIGHT);
}
OpenGLRenderer::~OpenGLRenderer()
{
finalize();
}
void
OpenGLRenderer::exposeEvent(QExposeEvent *event)
{
Q_UNUSED(event);
if (!isInitialized)
initialize();
onResize(size().width(), size().height());
}
void
OpenGLRenderer::resizeEvent(QResizeEvent *event)
{
Q_UNUSED(event);
onResize(event->size().width(), event->size().height());
if (notReady())
return;
context->makeCurrent(this);
glViewport(
destination.x() * devicePixelRatio(),
destination.y() * devicePixelRatio(),
destination.width() * devicePixelRatio(),
destination.height() * devicePixelRatio());
}
bool
OpenGLRenderer::event(QEvent *event)
{
Q_UNUSED(event);
bool res = false;
if (!eventDelegate(event, res))
return QWindow::event(event);
return res;
}
void
OpenGLRenderer::initialize()
{
try {
context = new QOpenGLContext(this);
context->setFormat(format());
if (!context->create())
throw opengl_init_error(tr("Couldn't create OpenGL context."));
if (!context->makeCurrent(this))
throw opengl_init_error(tr("Couldn't switch to OpenGL context."));
auto version = context->format().version();
if (version.first < 3)
throw opengl_init_error(tr("OpenGL version 3.0 or greater is required. Current version is %1.%2").arg(version.first).arg(version.second));
initializeOpenGLFunctions();
/* Prepare the shader version string */
glslVersion = reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION));
glslVersion.truncate(4);
glslVersion.remove('.');
glslVersion.prepend("#version ");
if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES)
glslVersion.append(" es");
else if (context->format().profile() == QSurfaceFormat::CoreProfile)
glslVersion.append(" core");
initializeExtensions();
initializeBuffers();
/* Vertex, texture 2d coordinates and color (white) making a quad as triangle strip */
const GLfloat surface[] = {
-1.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f,
-1.f, -1.f, 0.f, 1.f, 1.f, 1.f, 1.f, 1.f,
1.f, -1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f
};
glGenVertexArrays(1, &vertexArrayID);
glBindVertexArray(vertexArrayID);
glGenBuffers(1, &vertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(surface), surface, GL_STATIC_DRAW);
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
const GLfloat border_color[] = { 0.f, 0.f, 0.f, 1.f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border_color);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexImage2D(GL_TEXTURE_2D, 0, QOpenGLTexture::RGBA8_UNorm, INIT_WIDTH, INIT_HEIGHT, 0, QOpenGLTexture::BGRA, QOpenGLTexture::UInt32_RGBA8_Rev, NULL);
reloadOptions();
glClearColor(0.f, 0.f, 0.f, 1.f);
glViewport(
destination.x() * devicePixelRatio(),
destination.y() * devicePixelRatio(),
destination.width() * devicePixelRatio(),
destination.height() * devicePixelRatio());
GLenum error = glGetError();
if (error != GL_NO_ERROR)
throw opengl_init_error(tr("OpenGL initialization failed. Error %1.").arg(error));
isInitialized = true;
emit initialized();
glClear(GL_COLOR_BUFFER_BIT);
context->swapBuffers(this);
} catch (const opengl_init_error &e) {
/* Mark all buffers as in use */
for (auto &flag : buf_usage)
flag.test_and_set();
QMessageBox::critical((QWidget *) qApp->findChild<QWindow *>(), tr("Error initializing OpenGL"), e.what() % tr("\nFalling back to software rendering."));
context->doneCurrent();
isFinalized = true;
isInitialized = true;
emit errorInitializing();
}
}
void
OpenGLRenderer::finalize()
{
if (isFinalized)
return;
renderTimer->stop();
context->makeCurrent(this);
if (hasBufferStorage)
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
glDeleteBuffers(1, &unpackBufferID);
glDeleteTextures(1, &textureID);
glDeleteBuffers(1, &vertexBufferID);
glDeleteVertexArrays(1, &vertexArrayID);
if (!hasBufferStorage && unpackBuffer)
free(unpackBuffer);
context->doneCurrent();
isFinalized = true;
}
QDialog *
OpenGLRenderer::getOptions(QWidget *parent)
{
auto dialog = new OpenGLOptionsDialog(parent, *options, [this]() { return new OpenGLOptions(this, false, glslVersion); });
connect(dialog, &OpenGLOptionsDialog::optionsChanged, this, &OpenGLRenderer::updateOptions);
return dialog;
}
void
OpenGLRenderer::initializeExtensions()
{
#ifndef NO_BUFFER_STORAGE
if (context->hasExtension("GL_ARB_buffer_storage") || context->hasExtension("GL_EXT_buffer_storage")) {
hasBufferStorage = true;
glBufferStorage = (PFNGLBUFFERSTORAGEEXTPROC_LOCAL) context->getProcAddress(context->hasExtension("GL_EXT_buffer_storage") ? "glBufferStorageEXT" : "glBufferStorage");
if (!glBufferStorage)
glBufferStorage = (PFNGLBUFFERSTORAGEEXTPROC_LOCAL) context->getProcAddress("glBufferStorage");
}
#endif
}
void
OpenGLRenderer::initializeBuffers()
{
glGenBuffers(1, &unpackBufferID);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, unpackBufferID);
if (hasBufferStorage) {
#ifndef NO_BUFFER_STORAGE
/* Create persistent buffer for pixel transfer. */
glBufferStorage(GL_PIXEL_UNPACK_BUFFER, BUFFERBYTES * BUFFERCOUNT, NULL, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
unpackBuffer = glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, BUFFERBYTES * BUFFERCOUNT, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
#endif
} else {
/* Fallback; create our own buffer. */
unpackBuffer = malloc(BUFFERBYTES * BUFFERCOUNT);
if (unpackBuffer == nullptr)
throw opengl_init_error(tr("Allocating memory for unpack buffer failed."));
glBufferData(GL_PIXEL_UNPACK_BUFFER, BUFFERBYTES * BUFFERCOUNT, NULL, GL_STREAM_DRAW);
}
}
void
OpenGLRenderer::applyOptions()
{
/* TODO: change detection in options */
if (options->framerate() > 0) {
int interval = (int) ceilf(1000.f / (float) options->framerate());
renderTimer->setInterval(std::chrono::milliseconds(interval));
}
if (options->renderBehavior() == OpenGLOptions::TargetFramerate)
renderTimer->start();
else
renderTimer->stop();
auto format = this->format();
int interval = options->vSync() ? 1 : 0;
if (format.swapInterval() != interval) {
format.setSwapInterval(interval);
setFormat(format);
context->setFormat(format);
}
GLint filter = options->filter() == OpenGLOptions::Linear ? GL_LINEAR : GL_NEAREST;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
currentFilter = options->filter();
}
void
OpenGLRenderer::reloadOptions()
{
if (options) {
delete options;
options = nullptr;
}
options = new OpenGLOptions(this, true, glslVersion);
applyOptions();
}
void
OpenGLRenderer::applyShader(const OpenGLShaderPass &shader)
{
if (!shader.bind())
return;
if (shader.vertex_coord() != -1) {
glEnableVertexAttribArray(shader.vertex_coord());
glVertexAttribPointer(shader.vertex_coord(), 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), 0);
}
if (shader.tex_coord() != -1) {
glEnableVertexAttribArray(shader.tex_coord());
glVertexAttribPointer(shader.tex_coord(), 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void *) (2 * sizeof(GLfloat)));
}
if (shader.color() != -1) {
glEnableVertexAttribArray(shader.color());
glVertexAttribPointer(shader.color(), 4, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void *) (4 * sizeof(GLfloat)));
}
if (shader.mvp_matrix() != -1) {
static const GLfloat mvp[] = {
1.f, 0.f, 0.f, 0.f,
0.f, 1.f, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f,
0.f, 0.f, 0.f, 1.f
};
glUniformMatrix4fv(shader.mvp_matrix(), 1, GL_FALSE, mvp);
}
if (shader.output_size() != -1)
glUniform2f(shader.output_size(), destination.width(), destination.height());
if (shader.input_size() != -1)
glUniform2f(shader.input_size(), source.width(), source.height());
if (shader.texture_size() != -1)
glUniform2f(shader.texture_size(), source.width(), source.height());
if (shader.frame_count() != -1)
glUniform1i(shader.frame_count(), frameCounter);
}
void
OpenGLRenderer::render()
{
context->makeCurrent(this);
if (options->filter() != currentFilter)
applyOptions();
/* TODO: multiple shader passes */
applyShader(options->shaders().first());
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
context->swapBuffers(this);
frameCounter = (frameCounter + 1) & 1023;
}
void
OpenGLRenderer::updateOptions(OpenGLOptions *newOptions)
{
context->makeCurrent(this);
glUseProgram(0);
delete options;
options = newOptions;
options->setParent(this);
applyOptions();
}
std::vector<std::tuple<uint8_t *, std::atomic_flag *>>
OpenGLRenderer::getBuffers()
{
std::vector<std::tuple<uint8_t *, std::atomic_flag *>> buffers;
if (notReady() || !unpackBuffer)
return buffers;
/* Split the buffer area */
for (int i = 0; i < BUFFERCOUNT; i++) {
buffers.push_back(std::make_tuple((uint8_t *) unpackBuffer + BUFFERBYTES * i, &buf_usage[i]));
}
return buffers;
}
void
OpenGLRenderer::onBlit(int buf_idx, int x, int y, int w, int h)
{
if (notReady())
return;
context->makeCurrent(this);
#ifdef Q_OS_MACOS
glViewport(
destination.x() * devicePixelRatio(),
destination.y() * devicePixelRatio(),
destination.width() * devicePixelRatio(),
destination.height() * devicePixelRatio());
#endif
if (source.width() != w || source.height() != h) {
source.setRect(0, 0, w, h);
/* Resize the texture */
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glTexImage2D(GL_TEXTURE_2D, 0, (GLenum) QOpenGLTexture::RGBA8_UNorm, source.width(), source.height(), 0, (GLenum) QOpenGLTexture::BGRA, (GLenum) QOpenGLTexture::UInt32_RGBA8_Rev, NULL);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, unpackBufferID);
}
if (!hasBufferStorage)
glBufferSubData(GL_PIXEL_UNPACK_BUFFER, BUFFERBYTES * buf_idx, h * ROW_LENGTH * sizeof(uint32_t) + (y * ROW_LENGTH * sizeof(uint32_t)), (uint8_t *) unpackBuffer + BUFFERBYTES * buf_idx);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, BUFFERPIXELS * buf_idx + y * ROW_LENGTH + x);
glPixelStorei(GL_UNPACK_ROW_LENGTH, ROW_LENGTH);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, (GLenum) QOpenGLTexture::BGRA, (GLenum) QOpenGLTexture::UInt32_RGBA8_Rev, NULL);
/* TODO: check if fence sync is implementable here and still has any benefit. */
glFinish();
buf_usage[buf_idx].clear();
if (options->renderBehavior() == OpenGLOptions::SyncWithVideo)
render();
}
``` | /content/code_sandbox/src/qt/qt_openglrenderer.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,341 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Network devices configuration UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
*
*/
#include "qt_settingsnetwork.hpp"
#include "ui_qt_settingsnetwork.h"
extern "C" {
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/machine.h>
#include <86box/timer.h>
#include <86box/thread.h>
#include <86box/network.h>
}
#include "qt_models_common.hpp"
#include "qt_deviceconfig.hpp"
void
SettingsNetwork::enableElements(Ui::SettingsNetwork *ui)
{
for (int i = 0; i < NET_CARD_MAX; ++i) {
auto *nic_cbox = findChild<QComboBox *>(QString("comboBoxNIC%1").arg(i + 1));
auto *net_type_cbox = findChild<QComboBox *>(QString("comboBoxNet%1").arg(i + 1));
auto *intf_cbox = findChild<QComboBox *>(QString("comboBoxIntf%1").arg(i + 1));
auto *conf_btn = findChild<QPushButton *>(QString("pushButtonConf%1").arg(i + 1));
auto *socket_line = findChild<QLineEdit *>(QString("socketVDENIC%1").arg(i + 1));
int netType = net_type_cbox->currentData().toInt();
bool adaptersEnabled = netType == NET_TYPE_NONE
|| netType == NET_TYPE_SLIRP
|| netType == NET_TYPE_VDE
|| (netType == NET_TYPE_PCAP && intf_cbox->currentData().toInt() > 0);
intf_cbox->setEnabled(net_type_cbox->currentData().toInt() == NET_TYPE_PCAP);
nic_cbox->setEnabled(adaptersEnabled);
int netCard = nic_cbox->currentData().toInt();
if ((i == 0) && (netCard == NET_INTERNAL))
conf_btn->setEnabled(adaptersEnabled && machine_has_flags(machineId, MACHINE_NIC) &&
device_has_config(machine_get_net_device(machineId)));
else
conf_btn->setEnabled(adaptersEnabled && network_card_has_config(nic_cbox->currentData().toInt()));
socket_line->setEnabled(net_type_cbox->currentData().toInt() == NET_TYPE_VDE);
}
}
SettingsNetwork::SettingsNetwork(QWidget *parent)
: QWidget(parent)
, ui(new Ui::SettingsNetwork)
{
ui->setupUi(this);
onCurrentMachineChanged(machine);
enableElements(ui);
for (int i = 0; i < NET_CARD_MAX; i++) {
auto *nic_cbox = findChild<QComboBox *>(QString("comboBoxNIC%1").arg(i + 1));
auto *net_type_cbox = findChild<QComboBox *>(QString("comboBoxNet%1").arg(i + 1));
auto *intf_cbox = findChild<QComboBox *>(QString("comboBoxIntf%1").arg(i + 1));
connect(nic_cbox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &SettingsNetwork::on_comboIndexChanged);
connect(net_type_cbox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &SettingsNetwork::on_comboIndexChanged);
connect(intf_cbox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &SettingsNetwork::on_comboIndexChanged);
}
}
SettingsNetwork::~SettingsNetwork()
{
delete ui;
}
void
SettingsNetwork::save()
{
for (int i = 0; i < NET_CARD_MAX; ++i) {
auto *cbox = findChild<QComboBox *>(QString("comboBoxNIC%1").arg(i + 1));
auto *socket_line = findChild<QLineEdit *>(QString("socketVDENIC%1").arg(i + 1));
net_cards_conf[i].device_num = cbox->currentData().toInt();
cbox = findChild<QComboBox *>(QString("comboBoxNet%1").arg(i + 1));
net_cards_conf[i].net_type = cbox->currentData().toInt();
cbox = findChild<QComboBox *>(QString("comboBoxIntf%1").arg(i + 1));
memset(net_cards_conf[i].host_dev_name, '\0', sizeof(net_cards_conf[i].host_dev_name));
if (net_cards_conf[i].net_type == NET_TYPE_PCAP) {
strncpy(net_cards_conf[i].host_dev_name, network_devs[cbox->currentData().toInt()].device, sizeof(net_cards_conf[i].host_dev_name) - 1);
} else if (net_cards_conf[i].net_type == NET_TYPE_VDE) {
strncpy(net_cards_conf[i].host_dev_name, socket_line->text().toUtf8().constData(), sizeof(net_cards_conf[i].host_dev_name));
}
}
}
void
SettingsNetwork::onCurrentMachineChanged(int machineId)
{
this->machineId = machineId;
int c = 0;
int selectedRow = 0;
for (int i = 0; i < NET_CARD_MAX; ++i) {
auto *cbox = findChild<QComboBox *>(QString("comboBoxNIC%1").arg(i + 1));
auto *model = cbox->model();
auto removeRows = model->rowCount();
c = 0;
selectedRow = 0;
while (true) {
/* Skip "internal" if machine doesn't have it or this is not the primary card. */
if ((c == 1) && ((i > 0) || (machine_has_flags(machineId, MACHINE_NIC) == 0))) {
c++;
continue;
}
auto name = DeviceConfig::DeviceName(network_card_getdevice(c), network_card_get_internal_name(c), 1);
if (name.isEmpty()) {
break;
}
if (network_card_available(c) && device_is_valid(network_card_getdevice(c), machineId)) {
int row = Models::AddEntry(model, name, c);
if (c == net_cards_conf[i].device_num) {
selectedRow = row - removeRows;
}
}
c++;
}
model->removeRows(0, removeRows);
cbox->setEnabled(model->rowCount() > 0);
cbox->setCurrentIndex(-1);
cbox->setCurrentIndex(selectedRow);
cbox = findChild<QComboBox *>(QString("comboBoxNet%1").arg(i + 1));
model = cbox->model();
removeRows = model->rowCount();
Models::AddEntry(model, tr("Null Driver"), NET_TYPE_NONE);
Models::AddEntry(model, "SLiRP", NET_TYPE_SLIRP);
if (network_ndev > 1) {
Models::AddEntry(model, "PCap", NET_TYPE_PCAP);
}
if (network_devmap.has_vde) {
Models::AddEntry(model, "VDE", NET_TYPE_VDE);
}
model->removeRows(0, removeRows);
cbox->setCurrentIndex(net_cards_conf[i].net_type);
selectedRow = 0;
if (network_ndev > 0) {
QString currentPcapDevice = net_cards_conf[i].host_dev_name;
cbox = findChild<QComboBox *>(QString("comboBoxIntf%1").arg(i + 1));
model = cbox->model();
removeRows = model->rowCount();
for (int c = 0; c < network_ndev; c++) {
Models::AddEntry(model, tr(network_devs[c].description), c);
if (QString(network_devs[c].device) == currentPcapDevice) {
selectedRow = c;
}
}
model->removeRows(0, removeRows);
cbox->setCurrentIndex(selectedRow);
}
if (net_cards_conf[i].net_type == NET_TYPE_VDE) {
QString currentVdeSocket = net_cards_conf[i].host_dev_name;
auto editline = findChild<QLineEdit *>(QString("socketVDENIC%1").arg(i+1));
editline->setText(currentVdeSocket);
}
}
}
void
SettingsNetwork::on_comboIndexChanged(int index)
{
if (index < 0) {
return;
}
enableElements(ui);
}
void
SettingsNetwork::on_pushButtonConf1_clicked()
{
int netCard = ui->comboBoxNIC1->currentData().toInt();
auto *device = network_card_getdevice(netCard);
if (netCard == NET_INTERNAL)
device = machine_get_net_device(machineId);
DeviceConfig::ConfigureDevice(device, 1, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsNetwork::on_pushButtonConf2_clicked()
{
int netCard = ui->comboBoxNIC2->currentData().toInt();
auto *device = network_card_getdevice(netCard);
DeviceConfig::ConfigureDevice(device, 2, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsNetwork::on_pushButtonConf3_clicked()
{
int netCard = ui->comboBoxNIC3->currentData().toInt();
auto *device = network_card_getdevice(netCard);
DeviceConfig::ConfigureDevice(device, 3, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsNetwork::on_pushButtonConf4_clicked()
{
int netCard = ui->comboBoxNIC4->currentData().toInt();
auto *device = network_card_getdevice(netCard);
DeviceConfig::ConfigureDevice(device, 4, qobject_cast<Settings *>(Settings::settings));
}
``` | /content/code_sandbox/src/qt/qt_settingsnetwork.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,141 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Specify dimensions UI module.
*
*
*
* Authors: Cacodemon345
*
*/
#include "qt_specifydimensions.h"
#include "ui_qt_specifydimensions.h"
#include "qt_mainwindow.hpp"
#include "ui_qt_mainwindow.h"
#include "qt_util.hpp"
#include <QStatusBar>
#include <QMenuBar>
#include <QTimer>
#include <QScreen>
extern "C" {
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/ui.h>
#include <86box/video.h>
}
extern MainWindow *main_window;
SpecifyDimensions::SpecifyDimensions(QWidget *parent)
: QDialog(parent)
, ui(new Ui::SpecifyDimensions)
{
ui->setupUi(this);
ui->checkBox->setChecked(vid_resize == 2);
ui->spinBoxWidth->setRange(16, 2048);
ui->spinBoxWidth->setValue(main_window->getRenderWidgetSize().width());
ui->spinBoxHeight->setRange(16, 2048);
ui->spinBoxHeight->setValue(main_window->getRenderWidgetSize().height());
if (dpi_scale == 0) {
ui->spinBoxWidth->setValue(main_window->getRenderWidgetSize().width() * util::screenOfWidget(main_window)->devicePixelRatio());
ui->spinBoxHeight->setValue(main_window->getRenderWidgetSize().height() * util::screenOfWidget(main_window)->devicePixelRatio());
}
}
SpecifyDimensions::~SpecifyDimensions()
{
delete ui;
}
void
SpecifyDimensions::on_SpecifyDimensions_accepted()
{
if (ui->checkBox->isChecked()) {
vid_resize = 2;
main_window->setWindowFlag(Qt::WindowMaximizeButtonHint, false);
main_window->setWindowFlag(Qt::MSWindowsFixedSizeDialogHint);
window_remember = 0;
fixed_size_x = ui->spinBoxWidth->value();
fixed_size_y = ui->spinBoxHeight->value();
main_window->resizeContents(fixed_size_x, fixed_size_y);
emit main_window->updateMenuResizeOptions();
main_window->show();
for (int i = 1; i < MONITORS_NUM; i++) {
if (main_window->renderers[i]) {
main_window->renderers[i]->setWindowFlag(Qt::WindowMaximizeButtonHint, false);
main_window->renderers[i]->setWindowFlag(Qt::MSWindowsFixedSizeDialogHint);
emit main_window->resizeContentsMonitor(fixed_size_x, fixed_size_y, i);
if (show_second_monitors) {
main_window->renderers[i]->show();
main_window->renderers[i]->switchRenderer((RendererStack::Renderer) vid_api);
}
}
}
main_window->ui->stackedWidget->switchRenderer((RendererStack::Renderer) vid_api);
} else {
main_window->setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
main_window->ui->actionResizable_window->setChecked(false);
vid_resize = 0;
main_window->ui->actionResizable_window->trigger();
window_remember = 1;
window_w = ui->spinBoxWidth->value();
window_h = ui->spinBoxHeight->value();
main_window->setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
emit main_window->resizeContents(ui->spinBoxWidth->value(), ui->spinBoxHeight->value());
for (int i = 1; i < MONITORS_NUM; i++) {
if (main_window->renderers[i]) {
main_window->renderers[i]->setWindowFlag(Qt::WindowMaximizeButtonHint);
main_window->renderers[i]->setWindowFlag(Qt::MSWindowsFixedSizeDialogHint, false);
emit main_window->resizeContentsMonitor(ui->spinBoxWidth->value(), ui->spinBoxHeight->value(), i);
main_window->renderers[i]->setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
if (show_second_monitors) {
main_window->renderers[i]->show();
main_window->renderers[i]->switchRenderer((RendererStack::Renderer) vid_api);
}
}
}
vid_resize = 1;
emit main_window->updateMenuResizeOptions();
}
main_window->show();
emit main_window->updateWindowRememberOption();
}
``` | /content/code_sandbox/src/qt/qt_specifydimensions.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,004 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Definitions for evdev keyboard input module.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
#ifndef EVDEV_KEYBOARD_HPP
#define EVDEV_KEYBOARD_HPP
uint16_t evdev_translate(uint32_t keycode);
#endif
``` | /content/code_sandbox/src/qt/evdev_keyboard.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 125 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Sound/MIDI devices configuration UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Jasmine Iwanek <jriwanek@gmail.com>
*
*/
#include "qt_settingssound.hpp"
#include "ui_qt_settingssound.h"
extern "C" {
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/device.h>
#include <86box/machine.h>
#include <86box/sound.h>
#include <86box/midi.h>
#include <86box/snd_mpu401.h>
#include <86box/snd_opl.h>
}
#include "qt_deviceconfig.hpp"
#include "qt_models_common.hpp"
SettingsSound::SettingsSound(QWidget *parent)
: QWidget(parent)
, ui(new Ui::SettingsSound)
{
ui->setupUi(this);
onCurrentMachineChanged(machine);
}
SettingsSound::~SettingsSound()
{
delete ui;
}
void
SettingsSound::save()
{
for (uint8_t i = 0; i < SOUND_CARD_MAX; ++i) {
auto *cbox = findChild<QComboBox *>(QString("comboBoxSoundCard%1").arg(i + 1));
sound_card_current[i] = cbox->currentData().toInt();
}
midi_output_device_current = ui->comboBoxMidiOut->currentData().toInt();
midi_input_device_current = ui->comboBoxMidiIn->currentData().toInt();
mpu401_standalone_enable = ui->checkBoxMPU401->isChecked() ? 1 : 0;
sound_is_float = ui->checkBoxFloat32->isChecked() ? 1 : 0;
if (ui->radioButtonYMFM->isChecked())
fm_driver = FM_DRV_YMFM;
else
fm_driver = FM_DRV_NUKED;
}
void
SettingsSound::onCurrentMachineChanged(const int machineId)
{
this->machineId = machineId;
int c;
int selectedRow;
for (uint8_t i = 0; i < SOUND_CARD_MAX; ++i) {
auto * cbox = findChild<QComboBox *>(QString("comboBoxSoundCard%1").arg(i + 1));
auto * model = cbox->model();
const auto removeRows = model->rowCount();
c = 0;
selectedRow = 0;
while (true) {
/* Skip "internal" if machine doesn't have it or this is not the primary card. */
if ((c == 1) && ((i > 0) || (machine_has_flags(machineId, MACHINE_SOUND) == 0))) {
c++;
continue;
}
auto name = DeviceConfig::DeviceName(sound_card_getdevice(c), sound_card_get_internal_name(c), 1);
if (name.isEmpty()) {
break;
}
if (sound_card_available(c) && device_is_valid(sound_card_getdevice(c), machineId)) {
int row = Models::AddEntry(model, name, c);
if (c == sound_card_current[i]) {
selectedRow = row - removeRows;
}
}
c++;
}
model->removeRows(0, removeRows);
cbox->setEnabled(model->rowCount() > 0);
cbox->setCurrentIndex(-1);
cbox->setCurrentIndex(selectedRow);
}
auto model = ui->comboBoxMidiOut->model();
auto removeRows = model->rowCount();
c = 0;
selectedRow = 0;
while (true) {
QString name = DeviceConfig::DeviceName(midi_out_device_getdevice(c), midi_out_device_get_internal_name(c), 0);
if (name.isEmpty()) {
break;
}
if (midi_out_device_available(c)) {
int row = Models::AddEntry(model, name, c);
if (c == midi_output_device_current) {
selectedRow = row - removeRows;
}
}
c++;
}
model->removeRows(0, removeRows);
ui->comboBoxMidiOut->setEnabled(model->rowCount() > 0);
ui->comboBoxMidiOut->setCurrentIndex(-1);
ui->comboBoxMidiOut->setCurrentIndex(selectedRow);
model = ui->comboBoxMidiIn->model();
removeRows = model->rowCount();
c = 0;
selectedRow = 0;
while (true) {
QString name = DeviceConfig::DeviceName(midi_in_device_getdevice(c), midi_in_device_get_internal_name(c), 0);
if (name.isEmpty()) {
break;
}
if (midi_in_device_available(c)) {
int row = Models::AddEntry(model, name, c);
if (c == midi_input_device_current) {
selectedRow = row - removeRows;
}
}
c++;
}
model->removeRows(0, removeRows);
ui->comboBoxMidiIn->setEnabled(model->rowCount() > 0);
ui->comboBoxMidiIn->setCurrentIndex(-1);
ui->comboBoxMidiIn->setCurrentIndex(selectedRow);
ui->checkBoxMPU401->setChecked(mpu401_standalone_enable > 0);
ui->checkBoxFloat32->setChecked(sound_is_float > 0);
switch (fm_driver) {
case FM_DRV_YMFM:
ui->radioButtonYMFM->setChecked(true);
break;
case FM_DRV_NUKED:
default:
ui->radioButtonNuked->setChecked(true);
break;
}
}
static bool
allowMpu401(Ui::SettingsSound *ui)
{
QString midiOut = midi_out_device_get_internal_name(ui->comboBoxMidiOut->currentData().toInt());
QString midiIn = midi_in_device_get_internal_name(ui->comboBoxMidiIn->currentData().toInt());
if (midiOut.isEmpty()) {
return false;
}
if (midiOut == QStringLiteral("none") && midiIn == QStringLiteral("none")) {
return false;
}
return true;
}
void
SettingsSound::on_comboBoxSoundCard1_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
int sndCard = ui->comboBoxSoundCard1->currentData().toInt();
if (sndCard == SOUND_INTERNAL)
ui->pushButtonConfigureSoundCard1->setEnabled(machine_has_flags(machineId, MACHINE_SOUND) &&
device_has_config(machine_get_snd_device(machineId)));
else
ui->pushButtonConfigureSoundCard1->setEnabled(sound_card_has_config(sndCard));
}
void
SettingsSound::on_pushButtonConfigureSoundCard1_clicked()
{
int sndCard = ui->comboBoxSoundCard1->currentData().toInt();
auto *device = sound_card_getdevice(sndCard);
if (sndCard == SOUND_INTERNAL)
device = machine_get_snd_device(machineId);
DeviceConfig::ConfigureDevice(device, 1, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsSound::on_comboBoxSoundCard2_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
int sndCard = ui->comboBoxSoundCard2->currentData().toInt();
ui->pushButtonConfigureSoundCard2->setEnabled(sound_card_has_config(sndCard));
}
void
SettingsSound::on_pushButtonConfigureSoundCard2_clicked()
{
int sndCard = ui->comboBoxSoundCard2->currentData().toInt();
auto *device = sound_card_getdevice(sndCard);
DeviceConfig::ConfigureDevice(device, 2, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsSound::on_comboBoxSoundCard3_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
int sndCard = ui->comboBoxSoundCard3->currentData().toInt();
ui->pushButtonConfigureSoundCard3->setEnabled(sound_card_has_config(sndCard));
}
void
SettingsSound::on_pushButtonConfigureSoundCard3_clicked()
{
int sndCard = ui->comboBoxSoundCard3->currentData().toInt();
auto *device = sound_card_getdevice(sndCard);
DeviceConfig::ConfigureDevice(device, 3, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsSound::on_comboBoxSoundCard4_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
int sndCard = ui->comboBoxSoundCard4->currentData().toInt();
ui->pushButtonConfigureSoundCard4->setEnabled(sound_card_has_config(sndCard));
}
void
SettingsSound::on_pushButtonConfigureSoundCard4_clicked()
{
int sndCard = ui->comboBoxSoundCard4->currentData().toInt();
auto *device = sound_card_getdevice(sndCard);
DeviceConfig::ConfigureDevice(device, 4, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsSound::on_comboBoxMidiOut_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
ui->pushButtonConfigureMidiOut->setEnabled(midi_out_device_has_config(ui->comboBoxMidiOut->currentData().toInt()));
ui->checkBoxMPU401->setEnabled(allowMpu401(ui) && (machine_has_bus(machineId, MACHINE_BUS_ISA) || machine_has_bus(machineId, MACHINE_BUS_MCA)));
ui->pushButtonConfigureMPU401->setEnabled(allowMpu401(ui) && ui->checkBoxMPU401->isChecked());
}
void
SettingsSound::on_pushButtonConfigureMidiOut_clicked()
{
DeviceConfig::ConfigureDevice(midi_out_device_getdevice(ui->comboBoxMidiOut->currentData().toInt()), 0,
qobject_cast<Settings *>(Settings::settings));
}
void
SettingsSound::on_comboBoxMidiIn_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
ui->pushButtonConfigureMidiIn->setEnabled(midi_in_device_has_config(ui->comboBoxMidiIn->currentData().toInt()));
ui->checkBoxMPU401->setEnabled(allowMpu401(ui) && (machine_has_bus(machineId, MACHINE_BUS_ISA) || machine_has_bus(machineId, MACHINE_BUS_MCA)));
ui->pushButtonConfigureMPU401->setEnabled(allowMpu401(ui) && ui->checkBoxMPU401->isChecked());
}
void
SettingsSound::on_pushButtonConfigureMidiIn_clicked()
{
DeviceConfig::ConfigureDevice(midi_in_device_getdevice(ui->comboBoxMidiIn->currentData().toInt()), 0,
qobject_cast<Settings *>(Settings::settings));
}
void
SettingsSound::on_checkBoxMPU401_stateChanged(int state)
{
ui->pushButtonConfigureMPU401->setEnabled(state == Qt::Checked);
}
void
SettingsSound::on_pushButtonConfigureMPU401_clicked()
{
if (machine_has_bus(machineId, MACHINE_BUS_MCA) > 0)
DeviceConfig::ConfigureDevice(&mpu401_mca_device, 0, qobject_cast<Settings *>(Settings::settings));
else
DeviceConfig::ConfigureDevice(&mpu401_device, 0, qobject_cast<Settings *>(Settings::settings));
}
``` | /content/code_sandbox/src/qt/qt_settingssound.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,465 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Header file for Unix VM-managers (client-side)
*
*
*
* Authors: Teemu Korhonen
* Cacodemon345
*
*/
#ifndef QT_UNIXMANAGERFILTER_HPP
#define QT_UNIXMANAGERFILTER_HPP
#include <QObject>
#include <QLocalSocket>
#include <QEvent>
/*
* Filters messages from VM-manager and
* window blocked events to notify about open modal dialogs.
*/
class UnixManagerSocket : public QLocalSocket {
Q_OBJECT
public:
UnixManagerSocket(QObject *object = nullptr);
signals:
void pause();
void ctrlaltdel();
void showsettings();
void resetVM();
void request_shutdown();
void force_shutdown();
void dialogstatus(bool open);
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
protected slots:
void readyToRead();
};
#endif
``` | /content/code_sandbox/src/qt/qt_unixmanagerfilter.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 253 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* OpenGL renderer options dialog for Qt
*
*
*
* Authors: Teemu Korhonen
*
*/
#include <QFileDialog>
#include <QMessageBox>
#include <QStringBuilder>
#include <stdexcept>
#include "qt_opengloptionsdialog.hpp"
#include "qt_util.hpp"
#include "ui_qt_opengloptionsdialog.h"
OpenGLOptionsDialog::OpenGLOptionsDialog(QWidget *parent, const OpenGLOptions &options, std::function<OpenGLOptions *()> optionsFactory)
: QDialog(parent)
, ui(new Ui::OpenGLOptionsDialog)
, createOptions(optionsFactory)
{
ui->setupUi(this);
if (options.renderBehavior() == OpenGLOptions::SyncWithVideo)
ui->syncWithVideo->setChecked(true);
else {
ui->syncToFramerate->setChecked(true);
ui->targetFps->setValue(options.framerate());
}
ui->vsync->setChecked(options.vSync());
if (!options.shaders().isEmpty()) {
auto path = options.shaders().first().path();
if (!path.isEmpty())
ui->shader->setPlainText(path);
}
}
OpenGLOptionsDialog::~OpenGLOptionsDialog()
{
delete ui;
}
void
OpenGLOptionsDialog::accept()
{
auto options = createOptions();
options->setRenderBehavior(
ui->syncWithVideo->isChecked()
? OpenGLOptions::SyncWithVideo
: OpenGLOptions::TargetFramerate);
options->setFrameRate(ui->targetFps->value());
options->setVSync(ui->vsync->isChecked());
auto shader = ui->shader->toPlainText();
try {
if (!shader.isEmpty())
options->addShader(shader);
else
options->addDefaultShader();
} catch (const std::runtime_error &e) {
delete options;
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Shader error"));
msgBox.setText(tr("Could not load shaders."));
msgBox.setInformativeText(tr("More information in details."));
msgBox.setDetailedText(e.what());
msgBox.setIcon(QMessageBox::Critical);
msgBox.setStandardButtons(QMessageBox::Close);
msgBox.setDefaultButton(QMessageBox::Close);
msgBox.setStyleSheet("QTextEdit { min-width: 45em; }");
msgBox.exec();
return;
}
options->save();
emit optionsChanged(options);
QDialog::accept();
}
void
OpenGLOptionsDialog::on_addShader_clicked()
{
auto shader = QFileDialog::getOpenFileName(
this,
QString(),
QString(),
tr("OpenGL Shaders") % util::DlgFilter({ "glsl" }, true));
if (shader.isNull())
return;
ui->shader->setPlainText(shader);
}
``` | /content/code_sandbox/src/qt/qt_opengloptionsdialog.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 668 |
```c++
#ifndef QT_FILEFIELD_HPP
#define QT_FILEFIELD_HPP
#include <QWidget>
namespace Ui {
class FileField;
}
class FileField : public QWidget {
Q_OBJECT
public:
explicit FileField(QWidget *parent = nullptr);
~FileField();
QString fileName() const { return fileName_; }
void setFileName(const QString &fileName);
void setFilter(const QString &filter) { filter_ = filter; }
QString selectedFilter() const { return selectedFilter_; }
void setselectedFilter(const QString &selectedFilter) { selectedFilter_ = selectedFilter; }
void setCreateFile(bool createFile) { createFile_ = createFile; }
bool createFile() { return createFile_; }
signals:
void fileSelected(const QString &fileName, bool precheck = false);
void fileTextEntered(const QString &fileName, bool precheck = false);
private slots:
void on_pushButton_clicked();
private:
Ui::FileField *ui;
QString fileName_;
QString selectedFilter_;
QString filter_;
bool createFile_ = false;
};
#endif // QT_FILEFIELD_HPP
``` | /content/code_sandbox/src/qt/qt_filefield.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 237 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* RawInput joystick interface.
*
*
*
* Authors: Miran Grca, <mgrca8@gmail.com>
* GH Cao, <driver1998.ms@outlook.com>
* Jasmine Iwanek,
*
*/
#include <windows.h>
#include <windowsx.h>
#include <hidclass.h>
#include <hidusage.h>
#include <hidsdi.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/plat.h>
#include <86box/gameport.h>
#include <86box/win.h>
/* These are defined in hidusage.h in the Windows SDK, but not in mingw-w64. */
#ifndef HID_USAGE_SIMULATION_AILERON
# define HID_USAGE_SIMULATION_AILERON ((USAGE) 0xb0)
#endif
#ifndef HID_USAGE_SIMULATION_ELEVATOR
# define HID_USAGE_SIMULATION_ELEVATOR ((USAGE) 0xb8)
#endif
#ifndef HID_USAGE_SIMULATION_ACCELLERATOR
# define HID_USAGE_SIMULATION_ACCELLERATOR ((USAGE) 0xc4)
#endif
#ifndef HID_USAGE_SIMULATION_BRAKE
# define HID_USAGE_SIMULATION_BRAKE ((USAGE) 0xc5)
#endif
#ifndef HID_USAGE_SIMULATION_CLUTCH
# define HID_USAGE_SIMULATION_CLUTCH ((USAGE) 0xc6)
#endif
#ifndef HID_USAGE_SIMULATION_SHIFTER
# define HID_USAGE_SIMULATION_SHIFTER ((USAGE) 0xc7)
#endif
#ifndef HID_USAGE_SIMULATION_STEERING
# define HID_USAGE_SIMULATION_STEERING ((USAGE) 0xc8)
#endif
#ifdef ENABLE_JOYSTICK_LOG
int joystick_do_log = ENABLE_JOYSTICK_LOG;
static void
joystick_log(const char *fmt, ...)
{
va_list ap;
if (joystick_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define joystick_log(fmt, ...)
#endif
typedef struct {
HANDLE hdevice;
PHIDP_PREPARSED_DATA data;
USAGE usage_button[256];
struct raw_axis_t {
USAGE usage;
USHORT link;
USHORT bitsize;
LONG max;
LONG min;
} axis[MAX_JOY_AXES];
struct raw_pov_t {
USAGE usage;
USHORT link;
LONG max;
LONG min;
} pov[MAX_JOY_POVS];
} raw_joystick_t;
plat_joystick_t plat_joystick_state[MAX_PLAT_JOYSTICKS];
joystick_t joystick_state[MAX_JOYSTICKS];
int joysticks_present = 0;
raw_joystick_t raw_joystick_state[MAX_PLAT_JOYSTICKS];
/* We only use the first 32 buttons reported, from Usage ID 1-128 */
void
joystick_add_button(raw_joystick_t *rawjoy, plat_joystick_t *joy, USAGE usage)
{
if (joy->nr_buttons >= MAX_JOY_BUTTONS)
return;
if (usage < 1 || usage > 128)
return;
rawjoy->usage_button[usage] = joy->nr_buttons;
sprintf(joy->button[joy->nr_buttons].name, "Button %d", usage);
joy->nr_buttons++;
}
void
joystick_add_axis(raw_joystick_t *rawjoy, plat_joystick_t *joy, PHIDP_VALUE_CAPS prop)
{
if (joy->nr_axes >= MAX_JOY_AXES)
return;
switch (prop->Range.UsageMin) {
case HID_USAGE_GENERIC_X:
sprintf(joy->axis[joy->nr_axes].name, "X");
break;
case HID_USAGE_GENERIC_Y:
sprintf(joy->axis[joy->nr_axes].name, "Y");
break;
case HID_USAGE_GENERIC_Z:
sprintf(joy->axis[joy->nr_axes].name, "Z");
break;
case HID_USAGE_GENERIC_RX:
sprintf(joy->axis[joy->nr_axes].name, "RX");
break;
case HID_USAGE_GENERIC_RY:
sprintf(joy->axis[joy->nr_axes].name, "RY");
break;
case HID_USAGE_GENERIC_RZ:
sprintf(joy->axis[joy->nr_axes].name, "RZ");
break;
case HID_USAGE_GENERIC_SLIDER:
sprintf(joy->axis[joy->nr_axes].name, "Slider");
break;
case HID_USAGE_GENERIC_DIAL:
sprintf(joy->axis[joy->nr_axes].name, "Dial");
break;
case HID_USAGE_GENERIC_WHEEL:
sprintf(joy->axis[joy->nr_axes].name, "Wheel");
break;
case HID_USAGE_SIMULATION_AILERON:
sprintf(joy->axis[joy->nr_axes].name, "Aileron");
break;
case HID_USAGE_SIMULATION_ELEVATOR:
sprintf(joy->axis[joy->nr_axes].name, "Elevator");
break;
case HID_USAGE_SIMULATION_RUDDER:
sprintf(joy->axis[joy->nr_axes].name, "Rudder");
break;
case HID_USAGE_SIMULATION_THROTTLE:
sprintf(joy->axis[joy->nr_axes].name, "Throttle");
break;
case HID_USAGE_SIMULATION_ACCELLERATOR:
sprintf(joy->axis[joy->nr_axes].name, "Accelerator");
break;
case HID_USAGE_SIMULATION_BRAKE:
sprintf(joy->axis[joy->nr_axes].name, "Brake");
break;
case HID_USAGE_SIMULATION_CLUTCH:
sprintf(joy->axis[joy->nr_axes].name, "Clutch");
break;
case HID_USAGE_SIMULATION_SHIFTER:
sprintf(joy->axis[joy->nr_axes].name, "Shifter");
break;
case HID_USAGE_SIMULATION_STEERING:
sprintf(joy->axis[joy->nr_axes].name, "Steering");
break;
default:
return;
}
joy->axis[joy->nr_axes].id = joy->nr_axes;
rawjoy->axis[joy->nr_axes].usage = prop->Range.UsageMin;
rawjoy->axis[joy->nr_axes].link = prop->LinkCollection;
rawjoy->axis[joy->nr_axes].bitsize = prop->BitSize;
/* Assume unsigned when min >= 0 */
if (prop->LogicalMin < 0) {
rawjoy->axis[joy->nr_axes].max = prop->LogicalMax;
} else {
/*
* Some joysticks will send -1 in LogicalMax, like Xbox Controllers
* so we need to mask that to appropriate value (instead of 0xFFFFFFFF)
*/
rawjoy->axis[joy->nr_axes].max = prop->LogicalMax & ((1ULL << prop->BitSize) - 1);
}
rawjoy->axis[joy->nr_axes].min = prop->LogicalMin;
joy->nr_axes++;
}
void
joystick_add_pov(raw_joystick_t *rawjoy, plat_joystick_t *joy, PHIDP_VALUE_CAPS prop)
{
if (joy->nr_povs >= MAX_JOY_POVS)
return;
sprintf(joy->pov[joy->nr_povs].name, "POV %d", joy->nr_povs + 1);
rawjoy->pov[joy->nr_povs].usage = prop->Range.UsageMin;
rawjoy->pov[joy->nr_povs].link = prop->LinkCollection;
rawjoy->pov[joy->nr_povs].min = prop->LogicalMin;
rawjoy->pov[joy->nr_povs].max = prop->LogicalMax;
joy->nr_povs++;
}
void
joystick_get_capabilities(raw_joystick_t *rawjoy, plat_joystick_t *joy)
{
UINT size = 0;
PHIDP_BUTTON_CAPS btn_caps = NULL;
PHIDP_VALUE_CAPS val_caps = NULL;
/* Get preparsed data (HID data format) */
GetRawInputDeviceInfoW(rawjoy->hdevice, RIDI_PREPARSEDDATA, NULL, &size);
rawjoy->data = malloc(size);
if (GetRawInputDeviceInfoW(rawjoy->hdevice, RIDI_PREPARSEDDATA, rawjoy->data, &size) <= 0)
fatal("joystick_get_capabilities: Failed to get preparsed data.\n");
HIDP_CAPS caps;
HidP_GetCaps(rawjoy->data, &caps);
/* Buttons */
if (caps.NumberInputButtonCaps > 0) {
btn_caps = calloc(caps.NumberInputButtonCaps, sizeof(HIDP_BUTTON_CAPS));
if (HidP_GetButtonCaps(HidP_Input, btn_caps, &caps.NumberInputButtonCaps, rawjoy->data) != HIDP_STATUS_SUCCESS) {
joystick_log("joystick_get_capabilities: Failed to query input buttons.\n");
goto end;
}
/* We only detect generic stuff */
for (int c = 0; c < caps.NumberInputButtonCaps; c++) {
if (btn_caps[c].UsagePage != HID_USAGE_PAGE_BUTTON)
continue;
int button_count = btn_caps[c].Range.UsageMax - btn_caps[c].Range.UsageMin + 1;
for (int b = 0; b < button_count; b++) {
joystick_add_button(rawjoy, joy, b + btn_caps[c].Range.UsageMin);
}
}
}
/* Values (axes and povs) */
if (caps.NumberInputValueCaps > 0) {
val_caps = calloc(caps.NumberInputValueCaps, sizeof(HIDP_VALUE_CAPS));
if (HidP_GetValueCaps(HidP_Input, val_caps, &caps.NumberInputValueCaps, rawjoy->data) != HIDP_STATUS_SUCCESS) {
joystick_log("joystick_get_capabilities: Failed to query axes and povs.\n");
goto end;
}
/* We only detect generic stuff */
for (int c = 0; c < caps.NumberInputValueCaps; c++) {
if (val_caps[c].UsagePage != HID_USAGE_PAGE_GENERIC)
continue;
if (val_caps[c].Range.UsageMin == HID_USAGE_GENERIC_HATSWITCH)
joystick_add_pov(rawjoy, joy, &val_caps[c]);
else
joystick_add_axis(rawjoy, joy, &val_caps[c]);
}
}
end:
free(btn_caps);
free(val_caps);
}
void
joystick_get_device_name(raw_joystick_t *rawjoy, plat_joystick_t *joy, PRID_DEVICE_INFO info)
{
UINT size = 0;
WCHAR *device_name = NULL;
WCHAR device_desc_wide[200] = { 0 };
GetRawInputDeviceInfoW(rawjoy->hdevice, RIDI_DEVICENAME, device_name, &size);
device_name = calloc(size, sizeof(WCHAR));
if (GetRawInputDeviceInfoW(rawjoy->hdevice, RIDI_DEVICENAME, device_name, &size) <= 0)
fatal("joystick_get_capabilities: Failed to get device name.\n");
HANDLE hDevObj = CreateFileW(device_name, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDevObj) {
HidD_GetProductString(hDevObj, device_desc_wide, sizeof(WCHAR) * 200);
CloseHandle(hDevObj);
}
free(device_name);
int result = WideCharToMultiByte(CP_ACP, 0, device_desc_wide, 200, joy->name, 260, NULL, NULL);
if (result == 0 || strlen(joy->name) == 0)
sprintf(joy->name,
"RawInput %s, VID:%04lX PID:%04lX",
info->hid.usUsage == HID_USAGE_GENERIC_JOYSTICK ? "Joystick" : "Gamepad",
info->hid.dwVendorId,
info->hid.dwProductId);
}
void
joystick_init(void)
{
UINT size = 0;
atexit(joystick_close);
joysticks_present = 0;
memset(raw_joystick_state, 0, sizeof(raw_joystick_t) * MAX_PLAT_JOYSTICKS);
/* Get a list of raw input devices from Windows */
UINT raw_devices = 0;
GetRawInputDeviceList(NULL, &raw_devices, sizeof(RAWINPUTDEVICELIST));
PRAWINPUTDEVICELIST deviceList = calloc(raw_devices, sizeof(RAWINPUTDEVICELIST));
GetRawInputDeviceList(deviceList, &raw_devices, sizeof(RAWINPUTDEVICELIST));
for (int i = 0; i < raw_devices; i++) {
PRID_DEVICE_INFO info = NULL;
if (joysticks_present >= MAX_PLAT_JOYSTICKS)
break;
if (deviceList[i].dwType != RIM_TYPEHID)
continue;
/* Get device info: hardware IDs and usage IDs */
GetRawInputDeviceInfoA(deviceList[i].hDevice, RIDI_DEVICEINFO, NULL, &size);
info = malloc(size);
info->cbSize = sizeof(RID_DEVICE_INFO);
if (GetRawInputDeviceInfoA(deviceList[i].hDevice, RIDI_DEVICEINFO, info, &size) <= 0)
goto end_loop;
/* If this is not a joystick/gamepad, skip */
if (info->hid.usUsagePage != HID_USAGE_PAGE_GENERIC)
goto end_loop;
if (info->hid.usUsage != HID_USAGE_GENERIC_JOYSTICK && info->hid.usUsage != HID_USAGE_GENERIC_GAMEPAD)
goto end_loop;
plat_joystick_t *joy = &plat_joystick_state[joysticks_present];
raw_joystick_t *rawjoy = &raw_joystick_state[joysticks_present];
rawjoy->hdevice = deviceList[i].hDevice;
joystick_get_capabilities(rawjoy, joy);
joystick_get_device_name(rawjoy, joy, info);
joystick_log("joystick_init: %s - %d buttons, %d axes, %d POVs\n",
joy->name, joy->nr_buttons, joy->nr_axes, joy->nr_povs);
joysticks_present++;
end_loop:
free(info);
}
joystick_log("joystick_init: joysticks_present=%i\n", joysticks_present);
/* Initialize the RawInput (joystick and gamepad) module. */
RAWINPUTDEVICE ridev[2];
ridev[0].dwFlags = 0;
ridev[0].hwndTarget = NULL;
ridev[0].usUsagePage = HID_USAGE_PAGE_GENERIC;
ridev[0].usUsage = HID_USAGE_GENERIC_JOYSTICK;
ridev[1].dwFlags = 0;
ridev[1].hwndTarget = NULL;
ridev[1].usUsagePage = HID_USAGE_PAGE_GENERIC;
ridev[1].usUsage = HID_USAGE_GENERIC_GAMEPAD;
if (!RegisterRawInputDevices(ridev, 2, sizeof(RAWINPUTDEVICE)))
fatal("plat_joystick_init: RegisterRawInputDevices failed\n");
}
void
joystick_close(void)
{
RAWINPUTDEVICE ridev[2];
ridev[0].dwFlags = RIDEV_REMOVE;
ridev[0].hwndTarget = NULL;
ridev[0].usUsagePage = HID_USAGE_PAGE_GENERIC;
ridev[0].usUsage = HID_USAGE_GENERIC_JOYSTICK;
ridev[1].dwFlags = RIDEV_REMOVE;
ridev[1].hwndTarget = NULL;
ridev[1].usUsagePage = HID_USAGE_PAGE_GENERIC;
ridev[1].usUsage = HID_USAGE_GENERIC_GAMEPAD;
RegisterRawInputDevices(ridev, 2, sizeof(RAWINPUTDEVICE));
}
void
win_joystick_handle(PRAWINPUT raw)
{
HRESULT r;
int j = -1; /* current joystick index, -1 when not found */
/* If the input is not from a known device, we ignore it */
for (int i = 0; i < joysticks_present; i++) {
if (raw_joystick_state[i].hdevice == raw->header.hDevice) {
j = i;
break;
}
}
if (j == -1)
return;
/* Read buttons */
USAGE usage_list[128] = { 0 };
ULONG usage_length = plat_joystick_state[j].nr_buttons;
memset(plat_joystick_state[j].b, 0, 32 * sizeof(int));
r = HidP_GetUsages(HidP_Input, HID_USAGE_PAGE_BUTTON, 0, usage_list, &usage_length,
raw_joystick_state[j].data, (PCHAR) raw->data.hid.bRawData, raw->data.hid.dwSizeHid);
if (r == HIDP_STATUS_SUCCESS) {
for (int i = 0; i < usage_length; i++) {
int button = raw_joystick_state[j].usage_button[usage_list[i]];
plat_joystick_state[j].b[button] = 128;
}
}
/* Read axes */
for (int a = 0; a < plat_joystick_state[j].nr_axes; a++) {
const struct raw_axis_t *axis = &raw_joystick_state[j].axis[a];
ULONG uvalue = 0;
LONG value = 0;
LONG center = (axis->max - axis->min + 1) / 2;
r = HidP_GetUsageValue(HidP_Input, HID_USAGE_PAGE_GENERIC, axis->link, axis->usage, &uvalue,
raw_joystick_state[j].data, (PCHAR) raw->data.hid.bRawData, raw->data.hid.dwSizeHid);
if (r == HIDP_STATUS_SUCCESS) {
if (axis->min < 0) {
/* extend signed uvalue to LONG */
if (uvalue & (1 << (axis->bitsize - 1))) {
ULONG mask = (1 << axis->bitsize) - 1;
value = -1U ^ mask;
value |= uvalue;
} else {
value = uvalue;
}
} else {
/* Assume unsigned when min >= 0, convert to a signed value */
value = (LONG) uvalue - center;
}
if (abs(value) == 1)
value = 0;
value = value * 32768 / center;
}
plat_joystick_state[j].a[a] = value;
#if 0
joystick_log("%s %-06d ", plat_joystick_state[j].axis[a].name, plat_joystick_state[j].a[a]);
#endif
}
/* read povs */
for (int p = 0; p < plat_joystick_state[j].nr_povs; p++) {
const struct raw_pov_t *pov = &raw_joystick_state[j].pov[p];
ULONG uvalue = 0;
LONG value = -1;
r = HidP_GetUsageValue(HidP_Input, HID_USAGE_PAGE_GENERIC, pov->link, pov->usage, &uvalue,
raw_joystick_state[j].data, (PCHAR) raw->data.hid.bRawData, raw->data.hid.dwSizeHid);
if (r == HIDP_STATUS_SUCCESS && (uvalue >= pov->min && uvalue <= pov->max)) {
value = (uvalue - pov->min) * 36000;
value /= (pov->max - pov->min + 1);
value %= 36000;
}
plat_joystick_state[j].p[p] = value;
#if 0
joystick_log("%s %-3d ", plat_joystick_state[j].pov[p].name, plat_joystick_state[j].p[p]);
#endif
}
#if 0
joystick_log("\n");
#endif
}
static int
joystick_get_axis(int joystick_nr, int mapping)
{
if (mapping & POV_X) {
int pov = plat_joystick_state[joystick_nr].p[mapping & 3];
if (LOWORD(pov) == 0xFFFF)
return 0;
else
return sin((2 * M_PI * (double) pov) / 36000.0) * 32767;
} else if (mapping & POV_Y) {
int pov = plat_joystick_state[joystick_nr].p[mapping & 3];
if (LOWORD(pov) == 0xFFFF)
return 0;
else
return -cos((2 * M_PI * (double) pov) / 36000.0) * 32767;
} else
return plat_joystick_state[joystick_nr].a[plat_joystick_state[joystick_nr].axis[mapping].id];
}
void
joystick_process(void)
{
int d;
if (joystick_type == JS_TYPE_NONE)
return;
for (int c = 0; c < joystick_get_max_joysticks(joystick_type); c++) {
if (joystick_state[c].plat_joystick_nr) {
int joystick_nr = joystick_state[c].plat_joystick_nr - 1;
for (d = 0; d < joystick_get_axis_count(joystick_type); d++)
joystick_state[c].axis[d] = joystick_get_axis(joystick_nr, joystick_state[c].axis_mapping[d]);
for (d = 0; d < joystick_get_button_count(joystick_type); d++)
joystick_state[c].button[d] = plat_joystick_state[joystick_nr].b[joystick_state[c].button_mapping[d]];
for (d = 0; d < joystick_get_pov_count(joystick_type); d++) {
int x;
int y;
double angle;
double magnitude;
x = joystick_get_axis(joystick_nr, joystick_state[c].pov_mapping[d][0]);
y = joystick_get_axis(joystick_nr, joystick_state[c].pov_mapping[d][1]);
angle = (atan2((double) y, (double) x) * 360.0) / (2 * M_PI);
magnitude = sqrt((double) x * (double) x + (double) y * (double) y);
if (magnitude < 16384)
joystick_state[c].pov[d] = -1;
else
joystick_state[c].pov[d] = ((int) angle + 90 + 360) % 360;
}
} else {
for (d = 0; d < joystick_get_axis_count(joystick_type); d++)
joystick_state[c].axis[d] = 0;
for (d = 0; d < joystick_get_button_count(joystick_type); d++)
joystick_state[c].button[d] = 0;
for (d = 0; d < joystick_get_pov_count(joystick_type); d++)
joystick_state[c].pov[d] = -1;
}
}
}
``` | /content/code_sandbox/src/qt/win_joystick_rawinput.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 5,165 |
```c++
#ifndef QT_SETTINGSOTHERREMOVABLE_HPP
#define QT_SETTINGSOTHERREMOVABLE_HPP
#include <QWidget>
namespace Ui {
class SettingsOtherRemovable;
}
class SettingsOtherRemovable : public QWidget {
Q_OBJECT
public:
explicit SettingsOtherRemovable(QWidget *parent = nullptr);
~SettingsOtherRemovable();
void reloadBusChannels_MO();
void reloadBusChannels_ZIP();
void save();
signals:
void moChannelChanged();
void zipChannelChanged();
private slots:
void on_checkBoxZIP250_stateChanged(int arg1);
private slots:
void on_comboBoxZIPChannel_activated(int index);
private slots:
void on_comboBoxZIPBus_activated(int index);
private slots:
void on_comboBoxZIPBus_currentIndexChanged(int index);
private slots:
void on_comboBoxMOType_activated(int index);
private slots:
void on_comboBoxMOChannel_activated(int index);
private slots:
void on_comboBoxMOBus_activated(int index);
private slots:
void on_comboBoxMOBus_currentIndexChanged(int index);
private slots:
void onMORowChanged(const QModelIndex ¤t);
void onZIPRowChanged(const QModelIndex ¤t);
private:
Ui::SettingsOtherRemovable *ui;
void enableCurrentlySelectedChannel_MO();
void enableCurrentlySelectedChannel_ZIP();
};
#endif // QT_SETTINGSOTHERREMOVABLE_HPP
``` | /content/code_sandbox/src/qt/qt_settingsotherremovable.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 287 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Mouse/Joystick configuration UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
*
*/
#include "qt_settingsinput.hpp"
#include "ui_qt_settingsinput.h"
#include <QDebug>
extern "C" {
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/machine.h>
#include <86box/mouse.h>
#include <86box/gameport.h>
}
#include "qt_models_common.hpp"
#include "qt_deviceconfig.hpp"
#include "qt_joystickconfiguration.hpp"
SettingsInput::SettingsInput(QWidget *parent)
: QWidget(parent)
, ui(new Ui::SettingsInput)
{
ui->setupUi(this);
onCurrentMachineChanged(machine);
}
SettingsInput::~SettingsInput()
{
delete ui;
}
void
SettingsInput::save()
{
mouse_type = ui->comboBoxMouse->currentData().toInt();
joystick_type = ui->comboBoxJoystick->currentData().toInt();
}
void
SettingsInput::onCurrentMachineChanged(int machineId)
{
// win_settings_video_proc, WM_INITDIALOG
this->machineId = machineId;
auto *mouseModel = ui->comboBoxMouse->model();
auto removeRows = mouseModel->rowCount();
int selectedRow = 0;
for (int i = 0; i < mouse_get_ndev(); ++i) {
const auto *dev = mouse_get_device(i);
if ((i == MOUSE_TYPE_INTERNAL) && (machine_has_flags(machineId, MACHINE_MOUSE) == 0)) {
continue;
}
if (device_is_valid(dev, machineId) == 0) {
continue;
}
QString name = DeviceConfig::DeviceName(dev, mouse_get_internal_name(i), 0);
int row = mouseModel->rowCount();
mouseModel->insertRow(row);
auto idx = mouseModel->index(row, 0);
mouseModel->setData(idx, name, Qt::DisplayRole);
mouseModel->setData(idx, i, Qt::UserRole);
if (i == mouse_type) {
selectedRow = row - removeRows;
}
}
mouseModel->removeRows(0, removeRows);
ui->comboBoxMouse->setCurrentIndex(selectedRow);
int i = 0;
const char *joyName = joystick_get_name(i);
auto *joystickModel = ui->comboBoxJoystick->model();
removeRows = joystickModel->rowCount();
selectedRow = 0;
while (joyName) {
int row = Models::AddEntry(joystickModel, tr(joyName).toUtf8().data(), i);
if (i == joystick_type) {
selectedRow = row - removeRows;
}
++i;
joyName = joystick_get_name(i);
}
joystickModel->removeRows(0, removeRows);
ui->comboBoxJoystick->setCurrentIndex(selectedRow);
}
void
SettingsInput::on_comboBoxMouse_currentIndexChanged(int index)
{
int mouseId = ui->comboBoxMouse->currentData().toInt();
ui->pushButtonConfigureMouse->setEnabled(mouse_has_config(mouseId) > 0);
}
void
SettingsInput::on_comboBoxJoystick_currentIndexChanged(int index)
{
int joystickId = ui->comboBoxJoystick->currentData().toInt();
for (int i = 0; i < MAX_JOYSTICKS; ++i) {
auto *btn = findChild<QPushButton *>(QString("pushButtonJoystick%1").arg(i + 1));
if (btn == nullptr) {
continue;
}
btn->setEnabled(joystick_get_max_joysticks(joystickId) > i);
}
}
void
SettingsInput::on_pushButtonConfigureMouse_clicked()
{
int mouseId = ui->comboBoxMouse->currentData().toInt();
DeviceConfig::ConfigureDevice(mouse_get_device(mouseId), 0, qobject_cast<Settings *>(Settings::settings));
}
static int
get_axis(JoystickConfiguration &jc, int axis, int joystick_nr)
{
int axis_sel = jc.selectedAxis(axis);
int nr_axes = plat_joystick_state[joystick_state[joystick_nr].plat_joystick_nr - 1].nr_axes;
if (axis_sel < nr_axes) {
return axis_sel;
}
axis_sel -= nr_axes;
if (axis_sel & 1)
return POV_Y | (axis_sel >> 1);
else
return POV_X | (axis_sel >> 1);
}
static int
get_pov(JoystickConfiguration &jc, int pov, int joystick_nr)
{
int pov_sel = jc.selectedPov(pov);
int nr_povs = plat_joystick_state[joystick_state[joystick_nr].plat_joystick_nr - 1].nr_povs * 2;
if (pov_sel < nr_povs) {
if (pov_sel & 1)
return POV_Y | (pov_sel >> 1);
else
return POV_X | (pov_sel >> 1);
}
return pov_sel - nr_povs;
}
static void
updateJoystickConfig(int type, int joystick_nr, QWidget *parent)
{
JoystickConfiguration jc(type, joystick_nr, parent);
switch (jc.exec()) {
case QDialog::Rejected:
return;
case QDialog::Accepted:
break;
}
joystick_state[joystick_nr].plat_joystick_nr = jc.selectedDevice();
if (joystick_state[joystick_nr].plat_joystick_nr) {
for (int c = 0; c < joystick_get_axis_count(type); c++) {
joystick_state[joystick_nr].axis_mapping[c] = get_axis(jc, c, joystick_nr);
}
for (int c = 0; c < joystick_get_button_count(type); c++) {
joystick_state[joystick_nr].button_mapping[c] = jc.selectedButton(c);
}
for (int c = 0; c < joystick_get_pov_count(type) * 2; c += 2) {
joystick_state[joystick_nr].pov_mapping[c][0] = get_pov(jc, c, joystick_nr);
joystick_state[joystick_nr].pov_mapping[c][1] = get_pov(jc, c + 1, joystick_nr);
}
}
}
void
SettingsInput::on_pushButtonJoystick1_clicked()
{
updateJoystickConfig(ui->comboBoxJoystick->currentData().toInt(), 0, this);
}
void
SettingsInput::on_pushButtonJoystick2_clicked()
{
updateJoystickConfig(ui->comboBoxJoystick->currentData().toInt(), 1, this);
}
void
SettingsInput::on_pushButtonJoystick3_clicked()
{
updateJoystickConfig(ui->comboBoxJoystick->currentData().toInt(), 2, this);
}
void
SettingsInput::on_pushButtonJoystick4_clicked()
{
updateJoystickConfig(ui->comboBoxJoystick->currentData().toInt(), 3, this);
}
``` | /content/code_sandbox/src/qt/qt_settingsinput.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,570 |
```c++
#include <QAbstractNativeEventFilter>
#include <QByteArray>
#if QT_VERSION_MAJOR >= 6
# define result_t qintptr
#else
# define result_t long
#endif
class CocoaEventFilter : public QAbstractNativeEventFilter {
public:
CocoaEventFilter() {};
~CocoaEventFilter();
virtual bool nativeEventFilter(const QByteArray &eventType, void *message, result_t *result) override;
};
``` | /content/code_sandbox/src/qt/cocoa_mouse.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 91 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Common storage devices module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
* Teemu Korhonen
*
*/
#include "qt_newfloppydialog.hpp"
#include "ui_qt_newfloppydialog.h"
#include "qt_models_common.hpp"
#include "qt_util.hpp"
extern "C" {
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/random.h>
#include <86box/scsi_device.h>
#include <86box/zip.h>
#include <86box/mo.h>
}
#include <cstdio>
#include <cstdlib>
#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#include <QProgressDialog>
#include <thread>
#include <QStringBuilder>
struct disk_size_t {
int hole;
int sides;
int data_rate;
int encoding;
int rpm;
int tracks;
int sectors; /* For IMG and Japanese FDI only. */
int sector_len; /* For IMG and Japanese FDI only. */
int media_desc;
int spc;
int num_fats;
int spfat;
int root_dir_entries;
};
static const disk_size_t disk_sizes[14] = {
// clang-format off
#if 0
{ 1, 1, 2, 1, 1, 77, 26, 0, 0, 4, 2, 6, 68 }, /* 250k 8" */
{ 1, 2, 2, 1, 1, 77, 26, 0, 0, 4, 2, 6, 68 }, /* 500k 8" */
{ 1, 1, 2, 1, 1, 77, 8, 3, 0, 1, 2, 2, 192 }, /* 616k 8" */
{ 1, 2, 0, 1, 1, 77, 8, 3, 0, 1, 2, 2, 192 }, /* 1232k 8" */
#endif
{ 0, 1, 2, 1, 0, 40, 8, 2, 0xfe, 2, 2, 1, 64 }, /* 160k */
{ 0, 1, 2, 1, 0, 40, 9, 2, 0xfc, 2, 2, 1, 64 }, /* 180k */
{ 0, 2, 2, 1, 0, 40, 8, 2, 0xff, 2, 2, 1, 112 }, /* 320k */
{ 0, 2, 2, 1, 0, 40, 9, 2, 0xfd, 2, 2, 2, 112 }, /* 360k */
{ 0, 2, 2, 1, 0, 80, 8, 2, 0xfb, 2, 2, 2, 112 }, /* 640k */
{ 0, 2, 2, 1, 0, 80, 9, 2, 0xf9, 2, 2, 3, 112 }, /* 720k */
{ 1, 2, 0, 1, 1, 80, 15, 2, 0xf9, 1, 2, 7, 224 }, /* 1.2M */
{ 1, 2, 0, 1, 1, 77, 8, 3, 0xfe, 1, 2, 2, 192 }, /* 1.25M */
{ 1, 2, 0, 1, 0, 80, 18, 2, 0xf0, 1, 2, 9, 224 }, /* 1.44M */
{ 1, 2, 0, 1, 0, 80, 21, 2, 0xf0, 2, 2, 5, 16 }, /* DMF cluster 1024 */
{ 1, 2, 0, 1, 0, 80, 21, 2, 0xf0, 4, 2, 3, 16 }, /* DMF cluster 2048 */
{ 2, 2, 3, 1, 0, 80, 36, 2, 0xf0, 2, 2, 9, 240 }, /* 2.88M */
{ 0, 64, 0, 0, 0, 96, 32, 2, 0, 0, 0, 0, 0 }, /* ZIP 100 */
{ 0, 64, 0, 0, 0, 239, 32, 2, 0, 0, 0, 0, 0 }, /* ZIP 250 */
#if 0
{ 0, 8, 0, 0, 0, 963, 32, 2, 0, 0, 0, 0, 0 }, /* LS-120 */
{ 0, 32, 0, 0, 0, 262, 56, 2, 0, 0, 0, 0, 0 } /* LS-240 */
#endif
// clang-format on
};
static const QStringList rpmModes = {
"Perfect RPM",
"1% below perfect RPM",
"1.5% below perfect RPM",
"2% below perfect RPM",
};
static const QStringList floppyTypes = {
"160 kB",
"180 kB",
"320 kB",
"360 kB",
"640 kB",
"720 kB",
"1.2 MB",
"1.25 MB",
"1.44 MB",
"DMF (cluster 1024)",
"DMF (cluster 2048)",
"2.88 MB",
};
static const QStringList zipTypes = {
"ZIP 100",
"ZIP 250",
};
static const QStringList moTypes = {
"3.5\" 128 MB (ISO 10090)",
"3.5\" 230 MB (ISO 13963)",
"3.5\" 540 MB (ISO 15498)",
"3.5\" 640 MB (ISO 15498)",
"3.5\" 1.3 GB (GigaMO)",
"3.5\" 2.3 GB (GigaMO 2)",
"5.25\" 600 MB",
"5.25\" 650 MB",
"5.25\" 1 GB",
"5.25\" 1.3 GB",
};
NewFloppyDialog::NewFloppyDialog(MediaType type, QWidget *parent)
: QDialog(parent)
, ui(new Ui::NewFloppyDialog)
, mediaType_(type)
{
ui->setupUi(this);
ui->fileField->setCreateFile(true);
auto *model = ui->comboBoxSize->model();
switch (type) {
case MediaType::Floppy:
for (int i = 0; i < floppyTypes.size(); ++i) {
Models::AddEntry(model, tr(floppyTypes[i].toUtf8().data()), i);
}
ui->fileField->setFilter(
tr("All images") % util::DlgFilter({ "86f", "dsk", "flp", "im?", "img", "*fd?" }) % tr("Basic sector images") % util::DlgFilter({ "dsk", "flp", "im?", "img", "*fd?" }) % tr("Surface images") % util::DlgFilter({ "86f" }, true));
break;
case MediaType::Zip:
for (int i = 0; i < zipTypes.size(); ++i) {
Models::AddEntry(model, tr(zipTypes[i].toUtf8().data()), i);
}
ui->fileField->setFilter(tr("ZIP images") % util::DlgFilter({ "im?", "img", "zdi" }, true));
break;
case MediaType::Mo:
for (int i = 0; i < moTypes.size(); ++i) {
Models::AddEntry(model, tr(moTypes[i].toUtf8().data()), i);
}
ui->fileField->setFilter(tr("MO images") % util::DlgFilter({ "im?", "img", "mdi" }) % tr("All files") % util::DlgFilter({ "*" }, true));
break;
}
model = ui->comboBoxRpm->model();
for (int i = 0; i < rpmModes.size(); ++i) {
Models::AddEntry(model, tr(rpmModes[i].toUtf8().data()), i);
}
connect(ui->fileField, &FileField::fileSelected, this, [this](const QString &filename) {
bool hide = true;
if (mediaType_ == MediaType::Floppy) {
if (QFileInfo(filename).suffix().toLower() == QStringLiteral("86f")) {
hide = false;
}
}
ui->labelRpm->setHidden(hide);
ui->comboBoxRpm->setHidden(hide);
});
connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &NewFloppyDialog::onCreate);
ui->labelRpm->setHidden(true);
ui->comboBoxRpm->setHidden(true);
}
NewFloppyDialog::~NewFloppyDialog()
{
delete ui;
}
QString
NewFloppyDialog::fileName() const
{
return ui->fileField->fileName();
}
void
NewFloppyDialog::onCreate()
{
auto filename = ui->fileField->fileName();
QFileInfo fi(filename);
filename = (fi.isRelative() && !fi.filePath().isEmpty()) ? (usr_path + fi.filePath()) : fi.filePath();
ui->fileField->setFileName(filename);
FileType fileType;
QProgressDialog progress("Creating floppy image", QString(), 0, 100, this);
connect(this, &NewFloppyDialog::fileProgress, &progress, &QProgressDialog::setValue);
connect(this, &NewFloppyDialog::fileProgress, [] { QApplication::processEvents(); });
switch (mediaType_) {
case MediaType::Floppy:
if (fi.suffix().toLower() == QStringLiteral("86f")) {
if (create86f(filename, disk_sizes[ui->comboBoxSize->currentIndex()], ui->comboBoxRpm->currentIndex())) {
return;
}
} else {
fileType = fi.suffix().toLower() == QStringLiteral("zdi") ? FileType::Fdi : FileType::Img;
if (createSectorImage(filename, disk_sizes[ui->comboBoxSize->currentIndex()], fileType)) {
return;
}
}
break;
case MediaType::Zip:
{
fileType = fi.suffix().toLower() == QStringLiteral("zdi") ? FileType::Zdi : FileType::Img;
std::atomic_bool res;
std::thread t([this, &res, filename, fileType, &progress] {
res = createZipSectorImage(filename, disk_sizes[ui->comboBoxSize->currentIndex() + 12], fileType, progress);
});
progress.exec();
t.join();
if (res) {
return;
}
}
break;
case MediaType::Mo:
{
fileType = fi.suffix().toLower() == QStringLiteral("mdi") ? FileType::Mdi : FileType::Img;
std::atomic_bool res;
std::thread t([this, &res, filename, fileType, &progress] {
res = createMoSectorImage(filename, ui->comboBoxSize->currentIndex(), fileType, progress);
});
progress.exec();
t.join();
if (res) {
return;
}
}
break;
}
QMessageBox::critical(this, tr("Unable to write file"), tr("Make sure the file is being saved to a writable directory"));
reject();
}
bool
NewFloppyDialog::create86f(const QString &filename, const disk_size_t &disk_size, uint8_t rpm_mode)
{
FILE *fp;
uint32_t magic = 0x46423638;
uint16_t version = 0x020C;
uint16_t dflags = 0;
uint16_t tflags = 0;
uint32_t index_hole_pos = 0;
uint32_t tarray[512];
uint32_t array_size;
uint32_t track_base;
uint32_t track_size;
int i;
uint32_t shift = 0;
dflags = 0; /* Has surface data? - Assume no for now. */
dflags |= (disk_size.hole << 1); /* Hole */
dflags |= ((disk_size.sides - 1) << 3); /* Sides. */
dflags |= (0 << 4); /* Write protect? - Assume no for now. */
dflags |= (rpm_mode << 5); /* RPM mode. */
dflags |= (0 << 7); /* Has extra bit cells? - Assume no for now. */
tflags = disk_size.data_rate; /* Data rate. */
tflags |= (disk_size.encoding << 3); /* Encoding. */
tflags |= (disk_size.rpm << 5); /* RPM. */
switch (disk_size.hole) {
case 0:
case 1:
default:
switch (rpm_mode) {
case 1:
array_size = 25250;
break;
case 2:
array_size = 25374;
break;
case 3:
array_size = 25750;
break;
default:
array_size = 25000;
break;
}
break;
case 2:
switch (rpm_mode) {
case 1:
array_size = 50500;
break;
case 2:
array_size = 50750;
break;
case 3:
array_size = 51000;
break;
default:
array_size = 50000;
break;
}
break;
}
auto empty = (unsigned char *) malloc(array_size);
memset(tarray, 0, 2048);
memset(empty, 0, array_size);
fp = plat_fopen(filename.toUtf8().data(), "wb");
if (!fp)
return false;
fwrite(&magic, 4, 1, fp);
fwrite(&version, 2, 1, fp);
fwrite(&dflags, 2, 1, fp);
track_size = array_size + 6;
track_base = 8 + ((disk_size.sides == 2) ? 2048 : 1024);
if (disk_size.tracks <= 43)
shift = 1;
for (i = 0; i < (disk_size.tracks * disk_size.sides) << shift; i++)
tarray[i] = track_base + (i * track_size);
fwrite(tarray, 1, (disk_size.sides == 2) ? 2048 : 1024, fp);
for (i = 0; i < (disk_size.tracks * disk_size.sides) << shift; i++) {
fwrite(&tflags, 2, 1, fp);
fwrite(&index_hole_pos, 4, 1, fp);
fwrite(empty, 1, array_size, fp);
}
free(empty);
fclose(fp);
return true;
}
/* Ignore false positive warning caused by a bug on gcc */
#if __GNUC__ >= 11
# pragma GCC diagnostic ignored "-Wstringop-overflow"
#endif
bool
NewFloppyDialog::createSectorImage(const QString &filename, const disk_size_t &disk_size, FileType type)
{
uint32_t total_size = 0;
uint32_t total_sectors = 0;
uint32_t sector_bytes = 0;
uint32_t root_dir_bytes = 0;
uint32_t fat_size = 0;
uint32_t fat1_offs = 0;
uint32_t fat2_offs = 0;
uint32_t zero_bytes = 0;
uint16_t base = 0x1000;
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
return false;
}
QDataStream stream(&file);
stream.setByteOrder(QDataStream::LittleEndian);
sector_bytes = (128 << disk_size.sector_len);
total_sectors = disk_size.sides * disk_size.tracks * disk_size.sectors;
if (total_sectors > ZIP_SECTORS)
total_sectors = ZIP_250_SECTORS;
total_size = total_sectors * sector_bytes;
root_dir_bytes = (disk_size.root_dir_entries << 5);
fat_size = (disk_size.spfat * sector_bytes);
fat1_offs = sector_bytes;
fat2_offs = fat1_offs + fat_size;
zero_bytes = fat2_offs + fat_size + root_dir_bytes;
if (type == FileType::Fdi) {
QByteArray bytes(base, 0);
auto empty = bytes.data();
*(uint32_t *) &(empty[0x08]) = (uint32_t) base;
*(uint32_t *) &(empty[0x0C]) = total_size;
*(uint16_t *) &(empty[0x10]) = (uint16_t) sector_bytes;
*(uint8_t *) &(empty[0x14]) = (uint8_t) disk_size.sectors;
*(uint8_t *) &(empty[0x18]) = (uint8_t) disk_size.sides;
*(uint8_t *) &(empty[0x1C]) = (uint8_t) disk_size.tracks;
stream.writeRawData(empty, base);
}
QByteArray bytes(total_size, 0);
auto empty = bytes.data();
memset(empty + zero_bytes, 0xF6, total_size - zero_bytes);
empty[0x00] = 0xEB; /* Jump to make MS-DOS happy. */
empty[0x01] = 0x58;
empty[0x02] = 0x90;
empty[0x03] = 0x38; /* '86BOX5.0' OEM ID. */
empty[0x04] = 0x36;
empty[0x05] = 0x42;
empty[0x06] = 0x4F;
empty[0x07] = 0x58;
empty[0x08] = 0x35;
empty[0x09] = 0x2E;
empty[0x0A] = 0x30;
*(uint16_t *) &(empty[0x0B]) = (uint16_t) sector_bytes;
*(uint8_t *) &(empty[0x0D]) = (uint8_t) disk_size.spc;
*(uint16_t *) &(empty[0x0E]) = (uint16_t) 1;
*(uint8_t *) &(empty[0x10]) = (uint8_t) disk_size.num_fats;
*(uint16_t *) &(empty[0x11]) = (uint16_t) disk_size.root_dir_entries;
*(uint16_t *) &(empty[0x13]) = (uint16_t) total_sectors;
*(uint8_t *) &(empty[0x15]) = (uint8_t) disk_size.media_desc;
*(uint16_t *) &(empty[0x16]) = (uint16_t) disk_size.spfat;
*(uint8_t *) &(empty[0x18]) = (uint8_t) disk_size.sectors;
*(uint8_t *) &(empty[0x1A]) = (uint8_t) disk_size.sides;
empty[0x26] = 0x29; /* ')' followed by randomly-generated volume serial number. */
empty[0x27] = random_generate();
empty[0x28] = random_generate();
empty[0x29] = random_generate();
empty[0x2A] = random_generate();
memset(&(empty[0x2B]), 0x20, 11);
empty[0x36] = 'F';
empty[0x37] = 'A';
empty[0x38] = 'T';
empty[0x39] = '1';
empty[0x3A] = '2';
memset(&(empty[0x3B]), 0x20, 0x0003);
empty[0x1FE] = 0x55;
empty[0x1FF] = 0xAA;
empty[fat1_offs + 0x00] = empty[fat2_offs + 0x00] = empty[0x15];
empty[fat1_offs + 0x01] = empty[fat2_offs + 0x01] = 0xFF;
empty[fat1_offs + 0x02] = empty[fat2_offs + 0x02] = 0xFF;
stream.writeRawData(empty, total_size);
return true;
}
bool
NewFloppyDialog::createZipSectorImage(const QString &filename, const disk_size_t &disk_size, FileType type, QProgressDialog &pbar)
{
uint32_t total_size = 0;
uint32_t total_sectors = 0;
uint32_t sector_bytes = 0;
uint16_t base = 0x1000;
uint32_t pbar_max = 0;
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
return false;
}
QDataStream stream(&file);
stream.setByteOrder(QDataStream::LittleEndian);
sector_bytes = (128 << disk_size.sector_len);
total_sectors = disk_size.sides * disk_size.tracks * disk_size.sectors;
if (total_sectors > ZIP_SECTORS)
total_sectors = ZIP_250_SECTORS;
total_size = total_sectors * sector_bytes;
pbar_max = total_size;
if (type == FileType::Zdi) {
pbar_max += base;
}
pbar_max >>= 11;
if (type == FileType::Zdi) {
QByteArray data(base, 0);
auto empty = data.data();
*(uint32_t *) &(empty[0x08]) = (uint32_t) base;
*(uint32_t *) &(empty[0x0C]) = total_size;
*(uint16_t *) &(empty[0x10]) = (uint16_t) sector_bytes;
*(uint8_t *) &(empty[0x14]) = (uint8_t) disk_size.sectors;
*(uint8_t *) &(empty[0x18]) = (uint8_t) disk_size.sides;
*(uint8_t *) &(empty[0x1C]) = (uint8_t) disk_size.tracks;
stream.writeRawData(empty, base);
pbar_max -= 2;
}
QByteArray bytes(total_size, 0);
auto empty = bytes.data();
if (total_sectors == ZIP_SECTORS) {
/* ZIP 100 */
/* MBR */
*(uint64_t *) &(empty[0x0000]) = 0x2054524150492EEBLL;
*(uint64_t *) &(empty[0x0008]) = 0x3930302065646F63LL;
*(uint64_t *) &(empty[0x0010]) = 0x67656D6F49202D20LL;
*(uint64_t *) &(empty[0x0018]) = 0x726F70726F432061LL;
*(uint64_t *) &(empty[0x0020]) = 0x202D206E6F697461LL;
*(uint64_t *) &(empty[0x0028]) = 0x30392F33322F3131LL;
*(uint64_t *) &(empty[0x01AE]) = 0x0116010100E90644LL;
*(uint64_t *) &(empty[0x01B6]) = 0xED08BBE5014E0135LL;
*(uint64_t *) &(empty[0x01BE]) = 0xFFFFFE06FFFFFE80LL;
*(uint64_t *) &(empty[0x01C6]) = 0x0002FFE000000020LL;
*(uint16_t *) &(empty[0x01FE]) = 0xAA55;
/* 31 sectors filled with 0x48 */
memset(&(empty[0x0200]), 0x48, 0x3E00);
/* Boot sector */
*(uint64_t *) &(empty[0x4000]) = 0x584F4236389058EBLL;
*(uint64_t *) &(empty[0x4008]) = 0x0008040200302E35LL;
*(uint64_t *) &(empty[0x4010]) = 0x00C0F80000020002LL;
*(uint64_t *) &(empty[0x4018]) = 0x0000002000FF003FLL;
*(uint32_t *) &(empty[0x4020]) = 0x0002FFE0;
*(uint16_t *) &(empty[0x4024]) = 0x0080;
empty[0x4026] = 0x29; /* ')' followed by randomly-generated volume serial number. */
empty[0x4027] = random_generate();
empty[0x4028] = random_generate();
empty[0x4029] = random_generate();
empty[0x402A] = random_generate();
memset(&(empty[0x402B]), 0x00, 0x000B);
memset(&(empty[0x4036]), 0x20, 0x0008);
empty[0x4036] = 'F';
empty[0x4037] = 'A';
empty[0x4038] = 'T';
empty[0x4039] = '1';
empty[0x403A] = '6';
memset(&(empty[0x403B]), 0x20, 0x0003);
empty[0x41FE] = 0x55;
empty[0x41FF] = 0xAA;
empty[0x5000] = empty[0x1D000] = empty[0x4015];
empty[0x5001] = empty[0x1D001] = 0xFF;
empty[0x5002] = empty[0x1D002] = 0xFF;
empty[0x5003] = empty[0x1D003] = 0xFF;
/* Root directory = 0x35000
Data = 0x39000 */
} else {
/* ZIP 250 */
/* MBR */
*(uint64_t *) &(empty[0x0000]) = 0x2054524150492EEBLL;
*(uint64_t *) &(empty[0x0008]) = 0x3930302065646F63LL;
*(uint64_t *) &(empty[0x0010]) = 0x67656D6F49202D20LL;
*(uint64_t *) &(empty[0x0018]) = 0x726F70726F432061LL;
*(uint64_t *) &(empty[0x0020]) = 0x202D206E6F697461LL;
*(uint64_t *) &(empty[0x0028]) = 0x30392F33322F3131LL;
*(uint64_t *) &(empty[0x01AE]) = 0x0116010100E900E9LL;
*(uint64_t *) &(empty[0x01B6]) = 0x2E32A7AC014E0135LL;
*(uint64_t *) &(empty[0x01EE]) = 0xEE203F0600010180LL;
*(uint64_t *) &(empty[0x01F6]) = 0x000777E000000020LL;
*(uint16_t *) &(empty[0x01FE]) = 0xAA55;
/* 31 sectors filled with 0x48 */
memset(&(empty[0x0200]), 0x48, 0x3E00);
/* The second sector begins with some strange data
in my reference image. */
*(uint64_t *) &(empty[0x0200]) = 0x3831393230334409LL;
*(uint64_t *) &(empty[0x0208]) = 0x6A57766964483130LL;
*(uint64_t *) &(empty[0x0210]) = 0x3C3A34676063653FLL;
*(uint64_t *) &(empty[0x0218]) = 0x586A56A8502C4161LL;
*(uint64_t *) &(empty[0x0220]) = 0x6F2D702535673D6CLL;
*(uint64_t *) &(empty[0x0228]) = 0x255421B8602D3456LL;
*(uint64_t *) &(empty[0x0230]) = 0x577B22447B52603ELL;
*(uint64_t *) &(empty[0x0238]) = 0x46412CC871396170LL;
*(uint64_t *) &(empty[0x0240]) = 0x704F55237C5E2626LL;
*(uint64_t *) &(empty[0x0248]) = 0x6C7932C87D5C3C20LL;
*(uint64_t *) &(empty[0x0250]) = 0x2C50503E47543D6ELL;
*(uint64_t *) &(empty[0x0258]) = 0x46394E807721536ALL;
*(uint64_t *) &(empty[0x0260]) = 0x505823223F245325LL;
*(uint64_t *) &(empty[0x0268]) = 0x365C79B0393B5B6ELL;
/* Boot sector */
*(uint64_t *) &(empty[0x4000]) = 0x584F4236389058EBLL;
*(uint64_t *) &(empty[0x4008]) = 0x0001080200302E35LL;
*(uint64_t *) &(empty[0x4010]) = 0x00EFF80000020002LL;
*(uint64_t *) &(empty[0x4018]) = 0x0000002000400020LL;
*(uint32_t *) &(empty[0x4020]) = 0x000777E0;
*(uint16_t *) &(empty[0x4024]) = 0x0080;
empty[0x4026] = 0x29; /* ')' followed by randomly-generated volume serial number. */
empty[0x4027] = random_generate();
empty[0x4028] = random_generate();
empty[0x4029] = random_generate();
empty[0x402A] = random_generate();
memset(&(empty[0x402B]), 0x00, 0x000B);
memset(&(empty[0x4036]), 0x20, 0x0008);
empty[0x4036] = 'F';
empty[0x4037] = 'A';
empty[0x4038] = 'T';
empty[0x4039] = '1';
empty[0x403A] = '6';
memset(&(empty[0x403B]), 0x20, 0x0003);
empty[0x41FE] = 0x55;
empty[0x41FF] = 0xAA;
empty[0x4200] = empty[0x22000] = empty[0x4015];
empty[0x4201] = empty[0x22001] = 0xFF;
empty[0x4202] = empty[0x22002] = 0xFF;
empty[0x4203] = empty[0x22003] = 0xFF;
/* Root directory = 0x3FE00
Data = 0x38200 */
}
pbar.setMaximum(pbar_max);
for (uint32_t i = 0; i < pbar_max; i++) {
stream.writeRawData(&empty[i << 11], 2048);
fileProgress(i);
}
fileProgress(pbar_max);
return true;
}
bool
NewFloppyDialog::createMoSectorImage(const QString &filename, int8_t disk_size, FileType type, QProgressDialog &pbar)
{
const mo_type_t *dp = &mo_types[disk_size];
uint32_t total_size = 0;
uint32_t total_size2;
uint32_t total_sectors = 0;
uint32_t sector_bytes = 0;
uint16_t base = 0x1000;
uint32_t pbar_max = 0;
uint32_t blocks_num;
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
return false;
}
QDataStream stream(&file);
stream.setByteOrder(QDataStream::LittleEndian);
sector_bytes = dp->bytes_per_sector;
total_sectors = dp->sectors;
total_size = total_sectors * sector_bytes;
total_size2 = (total_size >> 20) << 20;
total_size2 = total_size - total_size2;
pbar_max = total_size;
pbar_max >>= 20;
blocks_num = pbar_max;
if (type == FileType::Mdi)
pbar_max++;
if (total_size2 == 0)
pbar_max++;
if (type == FileType::Mdi) {
QByteArray bytes(base, 0);
auto empty = bytes.data();
*(uint32_t *) &(empty[0x08]) = (uint32_t) base;
*(uint32_t *) &(empty[0x0C]) = total_size;
*(uint16_t *) &(empty[0x10]) = (uint16_t) sector_bytes;
*(uint8_t *) &(empty[0x14]) = (uint8_t) 25;
*(uint8_t *) &(empty[0x18]) = (uint8_t) 64;
*(uint8_t *) &(empty[0x1C]) = (uint8_t) (dp->sectors / 64) / 25;
stream.writeRawData(empty, base);
}
QByteArray bytes(1048576, 0);
auto empty = bytes.data();
pbar.setMaximum(blocks_num);
for (uint32_t i = 0; i < blocks_num; i++) {
stream.writeRawData(empty, bytes.size());
fileProgress(i);
}
if (total_size2 > 0) {
QByteArray extra_bytes(total_size2, 0);
stream.writeRawData(extra_bytes.data(), total_size2);
}
fileProgress(blocks_num);
return true;
}
``` | /content/code_sandbox/src/qt/qt_newfloppydialog.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 8,057 |
```c++
#ifndef QT_HARDDISKDIALOG_HPP
#define QT_HARDDISKDIALOG_HPP
#include <QDialog>
namespace Ui {
class HarddiskDialog;
}
class HarddiskDialog : public QDialog {
Q_OBJECT
public:
explicit HarddiskDialog(bool existing, QWidget *parent = nullptr);
~HarddiskDialog();
uint8_t bus() const;
uint8_t channel() const;
QString fileName() const;
uint32_t cylinders() const { return cylinders_; }
uint32_t heads() const { return heads_; }
uint32_t sectors() const { return sectors_; }
uint32_t speed() const;
signals:
void fileProgress(int i);
public slots:
void accept() override;
private slots:
void on_comboBoxType_currentIndexChanged(int index);
void on_lineEditSectors_textEdited(const QString &arg1);
void on_lineEditHeads_textEdited(const QString &arg1);
void on_lineEditCylinders_textEdited(const QString &arg1);
void on_lineEditSize_textEdited(const QString &arg1);
void on_comboBoxBus_currentIndexChanged(int index);
void on_comboBoxFormat_currentIndexChanged(int index);
void onCreateNewFile();
void onExistingFileSelected(const QString &fileName, bool precheck);
private:
Ui::HarddiskDialog *ui;
uint32_t cylinders_;
uint32_t heads_;
uint32_t sectors_;
uint32_t max_sectors = 0;
uint32_t max_heads = 0;
uint32_t max_cylinders = 0;
bool disallowSizeModifications = false;
QStringList filters;
// "Dynamic-size VHD" is number 4 in the `filters` list and the
// comboBoxFormat model
const uint8_t DEFAULT_DISK_FORMAT = 4;
bool checkAndAdjustCylinders();
bool checkAndAdjustHeads();
bool checkAndAdjustSectors();
void recalcSize();
void recalcSelection();
};
#endif // QT_HARDDISKDIALOG_HPP
``` | /content/code_sandbox/src/qt/qt_harddiskdialog.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 439 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Program settings UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
*
*/
#include "qt_renderercommon.hpp"
#include "qt_mainwindow.hpp"
#include <QPainter>
#include <QWidget>
#include <QEvent>
#include <QApplication>
#include <cmath>
extern "C" {
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/video.h>
}
RendererCommon::RendererCommon() = default;
extern MainWindow *main_window;
static void
integer_scale(double *d, double *g)
{
double ratio;
if (*d > *g) {
ratio = std::floor(*d / *g);
*d = *g * ratio;
} else {
ratio = std::ceil(*d / *g);
*d = *g / ratio;
}
}
void
RendererCommon::onResize(int width, int height)
{
/* This is needed so that the if below does not take like, 5 lines. */
bool is_fs = (video_fullscreen == 0);
bool parent_max = (parentWidget->isMaximized() == false);
bool main_is_ancestor = main_window->isAncestorOf(parentWidget);
bool main_max = main_window->isMaximized();
bool main_is_max = (main_is_ancestor && main_max == false);
if (is_fs && (video_fullscreen_scale_maximized ? (parent_max && main_is_max) : 1))
destination.setRect(0, 0, width, height);
else {
double dx;
double dy;
double dw;
double dh;
double gsr;
double hw = width;
double hh = height;
double gw = source.width();
double gh = source.height();
double hsr = hw / hh;
double r43 = 4.0 / 3.0;
switch (video_fullscreen_scale) {
case FULLSCR_SCALE_INT:
case FULLSCR_SCALE_INT43:
gsr = gw / gh;
if (video_fullscreen_scale == FULLSCR_SCALE_INT43) {
gh = gw / r43;
// gw = gw;
gsr = r43;
}
if (gsr <= hsr) {
dw = hh * gsr;
dh = hh;
} else {
dw = hw;
dh = hw / gsr;
}
integer_scale(&dw, &gw);
integer_scale(&dh, &gh);
dx = (hw - dw) / 2.0;
dy = (hh - dh) / 2.0;
destination.setRect((int) dx, (int) dy, (int) dw, (int) dh);
break;
case FULLSCR_SCALE_43:
case FULLSCR_SCALE_KEEPRATIO:
if (video_fullscreen_scale == FULLSCR_SCALE_43)
gsr = r43;
else
gsr = gw / gh;
if (gsr <= hsr) {
dw = hh * gsr;
dh = hh;
} else {
dw = hw;
dh = hw / gsr;
}
dx = (hw - dw) / 2.0;
dy = (hh - dh) / 2.0;
destination.setRect((int) dx, (int) dy, (int) dw, (int) dh);
break;
case FULLSCR_SCALE_FULL:
default:
destination.setRect(0, 0, (int) hw, (int) hh);
break;
}
}
monitors[r_monitor_index].mon_res_x = (double) destination.width();
monitors[r_monitor_index].mon_res_y = (double) destination.height();
}
bool
RendererCommon::eventDelegate(QEvent *event, bool &result)
{
switch (event->type()) {
default:
return false;
case QEvent::KeyPress:
case QEvent::KeyRelease:
result = QApplication::sendEvent(main_window, event);
return true;
case QEvent::MouseButtonPress:
case QEvent::MouseMove:
case QEvent::MouseButtonRelease:
case QEvent::Wheel:
case QEvent::Enter:
case QEvent::Leave:
result = QApplication::sendEvent(parentWidget, event);
return true;
}
}
``` | /content/code_sandbox/src/qt/qt_renderercommon.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,019 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Program settings UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
* Teemu Korhonen
*
*/
#include "qt_rendererstack.hpp"
#include "ui_qt_rendererstack.h"
#include "qt_hardwarerenderer.hpp"
#include "qt_openglrenderer.hpp"
#include "qt_softwarerenderer.hpp"
#include "qt_vulkanwindowrenderer.hpp"
#include "qt_mainwindow.hpp"
#include "qt_util.hpp"
#include "ui_qt_mainwindow.h"
#include "evdev_mouse.hpp"
#include <atomic>
#include <stdexcept>
#include <QScreen>
#include <QMessageBox>
#ifdef __APPLE__
# include <CoreGraphics/CoreGraphics.h>
#endif
extern "C" {
#include <86box/86box.h>
#include <86box/config.h>
#include <86box/plat.h>
#include <86box/video.h>
#include <86box/mouse.h>
}
struct mouseinputdata {
atomic_bool mouse_tablet_in_proximity;
char *mouse_type;
};
static mouseinputdata mousedata;
extern MainWindow *main_window;
RendererStack::RendererStack(QWidget *parent, int monitor_index)
: QStackedWidget(parent)
, ui(new Ui::RendererStack)
{
#ifdef Q_OS_WINDOWS
int raw = 1;
#else
int raw = 0;
#endif
ui->setupUi(this);
m_monitor_index = monitor_index;
#if defined __unix__ && !defined __HAIKU__
char auto_mouse_type[16];
mousedata.mouse_type = getenv("EMU86BOX_MOUSE");
if (!mousedata.mouse_type || (mousedata.mouse_type[0] == '\0') || !stricmp(mousedata.mouse_type, "auto")) {
if (QApplication::platformName().contains("wayland"))
strcpy(auto_mouse_type, "wayland");
else if (QApplication::platformName() == "eglfs")
strcpy(auto_mouse_type, "evdev");
else if (QApplication::platformName() == "xcb")
strcpy(auto_mouse_type, "xinput2");
else
auto_mouse_type[0] = '\0';
mousedata.mouse_type = auto_mouse_type;
}
# ifdef WAYLAND
if (!stricmp(mousedata.mouse_type, "wayland")) {
wl_init();
this->mouse_capture_func = wl_mouse_capture;
this->mouse_uncapture_func = wl_mouse_uncapture;
}
# endif
# ifdef EVDEV_INPUT
if (!stricmp(mousedata.mouse_type, "evdev")) {
evdev_init();
raw = 0;
}
# endif
if (!stricmp(mousedata.mouse_type, "xinput2")) {
extern void xinput2_init();
extern void xinput2_exit();
xinput2_init();
this->mouse_exit_func = xinput2_exit;
}
#endif
if (monitor_index == 0)
mouse_set_raw(raw);
}
RendererStack::~RendererStack()
{
while (QApplication::overrideCursor())
QApplication::restoreOverrideCursor();
delete ui;
}
void
qt_mouse_capture(int on)
{
if (!on) {
mouse_capture = 0;
while (QApplication::overrideCursor()) QApplication::restoreOverrideCursor();
#ifdef __APPLE__
CGAssociateMouseAndMouseCursorPosition(true);
#endif
return;
}
mouse_capture = 1;
QApplication::setOverrideCursor(Qt::BlankCursor);
#ifdef __APPLE__
CGAssociateMouseAndMouseCursorPosition(false);
#endif
return;
}
int ignoreNextMouseEvent = 1;
void
RendererStack::mouseReleaseEvent(QMouseEvent *event)
{
if (!dopause && this->geometry().contains(m_monitor_index >= 1 ? event->globalPos() : event->pos()) &&
(event->button() == Qt::LeftButton) && !mouse_capture &&
(isMouseDown & 1) && (kbd_req_capture || (mouse_get_buttons() != 0)) &&
(mouse_input_mode == 0)) {
plat_mouse_capture(1);
this->setCursor(Qt::BlankCursor);
if (!ignoreNextMouseEvent)
ignoreNextMouseEvent++; // Avoid jumping cursor when moved.
isMouseDown &= ~1;
return;
}
if (mouse_capture && (event->button() == Qt::MiddleButton) && (mouse_get_buttons() < 3)) {
plat_mouse_capture(0);
this->setCursor(Qt::ArrowCursor);
isMouseDown &= ~1;
return;
}
if (mouse_capture || (mouse_input_mode >= 1)) {
#ifdef Q_OS_WINDOWS
if (((m_monitor_index >= 1) && (mouse_input_mode >= 1) && mousedata.mouse_tablet_in_proximity) ||
((m_monitor_index < 1) && (mouse_input_mode >= 1)))
#else
#ifndef __APPLE__
if (((m_monitor_index >= 1) && (mouse_input_mode >= 1) && mousedata.mouse_tablet_in_proximity) ||
(m_monitor_index < 1))
#else
if ((m_monitor_index >= 1) && (mouse_input_mode >= 1) && mousedata.mouse_tablet_in_proximity)
#endif
#endif
mouse_set_buttons_ex(mouse_get_buttons_ex() & ~event->button());
}
isMouseDown &= ~1;
}
void
RendererStack::mousePressEvent(QMouseEvent *event)
{
isMouseDown |= 1;
if (mouse_capture || (mouse_input_mode >= 1)) {
#ifdef Q_OS_WINDOWS
if (((m_monitor_index >= 1) && (mouse_input_mode >= 1) && mousedata.mouse_tablet_in_proximity) ||
((m_monitor_index < 1) && (mouse_input_mode >= 1)))
#else
#ifndef __APPLE__
if (((m_monitor_index >= 1) && (mouse_input_mode >= 1) && mousedata.mouse_tablet_in_proximity) ||
(m_monitor_index < 1))
#else
if ((m_monitor_index >= 1) && (mouse_input_mode >= 1) && mousedata.mouse_tablet_in_proximity)
#endif
#endif
mouse_set_buttons_ex(mouse_get_buttons_ex() | event->button());
}
event->accept();
}
void
RendererStack::wheelEvent(QWheelEvent *event)
{
mouse_set_z(event->pixelDelta().y());
}
void
RendererStack::mouseMoveEvent(QMouseEvent *event)
{
if (QApplication::platformName().contains("wayland")) {
event->accept();
return;
}
if (!mouse_capture) {
event->ignore();
return;
}
#if defined __APPLE__ || defined _WIN32
event->accept();
return;
#else
static QPoint oldPos = QCursor::pos();
if (ignoreNextMouseEvent) {
oldPos = event->pos();
ignoreNextMouseEvent--;
event->accept();
return;
}
#if defined __unix__ && !defined __HAIKU__
if (!stricmp(mousedata.mouse_type, "wayland"))
mouse_scale(event->pos().x() - oldPos.x(), event->pos().y() - oldPos.y());
#endif
if (QApplication::platformName() == "eglfs") {
leaveEvent((QEvent *) event);
ignoreNextMouseEvent--;
}
QCursor::setPos(mapToGlobal(QPoint(width() / 2, height() / 2)));
ignoreNextMouseEvent = 2;
oldPos = event->pos();
#endif
}
void
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
RendererStack::enterEvent(QEnterEvent *event)
#else
RendererStack::enterEvent(QEvent *event)
#endif
{
mousedata.mouse_tablet_in_proximity = m_monitor_index + 1;
if (mouse_input_mode == 1)
QApplication::setOverrideCursor(Qt::BlankCursor);
else if (mouse_input_mode == 2)
QApplication::setOverrideCursor(Qt::CrossCursor);
}
void
RendererStack::leaveEvent(QEvent *event)
{
mousedata.mouse_tablet_in_proximity = 0;
if (mouse_input_mode == 1 && QApplication::overrideCursor()) {
while (QApplication::overrideCursor())
QApplication::restoreOverrideCursor();
}
if (QApplication::platformName().contains("wayland")) {
event->accept();
return;
}
if (!mouse_capture)
return;
QCursor::setPos(mapToGlobal(QPoint(width() / 2, height() / 2)));
ignoreNextMouseEvent = 2;
event->accept();
}
void
RendererStack::switchRenderer(Renderer renderer)
{
startblit();
if (current) {
rendererWindow->finalize();
removeWidget(current.get());
disconnect(this, &RendererStack::blitToRenderer, nullptr, nullptr);
/* Create new renderer only after previous is destroyed! */
connect(current.get(), &QObject::destroyed, [this, renderer](QObject *) { createRenderer(renderer); });
current.release()->deleteLater();
} else {
createRenderer(renderer);
}
}
void
RendererStack::createRenderer(Renderer renderer)
{
switch (renderer) {
default:
case Renderer::Software:
{
auto sw = new SoftwareRenderer(this);
rendererWindow = sw;
connect(this, &RendererStack::blitToRenderer, sw, &SoftwareRenderer::onBlit, Qt::QueuedConnection);
#ifdef __HAIKU__
current.reset(sw);
#else
current.reset(this->createWindowContainer(sw, this));
#endif
}
break;
case Renderer::OpenGL:
{
this->createWinId();
auto hw = new HardwareRenderer(this);
rendererWindow = hw;
connect(this, &RendererStack::blitToRenderer, hw, &HardwareRenderer::onBlit, Qt::QueuedConnection);
current.reset(this->createWindowContainer(hw, this));
break;
}
case Renderer::OpenGLES:
{
this->createWinId();
auto hw = new HardwareRenderer(this, HardwareRenderer::RenderType::OpenGLES);
rendererWindow = hw;
connect(this, &RendererStack::blitToRenderer, hw, &HardwareRenderer::onBlit, Qt::QueuedConnection);
current.reset(this->createWindowContainer(hw, this));
break;
}
case Renderer::OpenGL3:
{
this->createWinId();
auto hw = new OpenGLRenderer(this);
rendererWindow = hw;
connect(this, &RendererStack::blitToRenderer, hw, &OpenGLRenderer::onBlit, Qt::QueuedConnection);
connect(hw, &OpenGLRenderer::initialized, [=]() {
/* Buffers are available only after initialization. */
imagebufs = rendererWindow->getBuffers();
endblit();
emit rendererChanged();
});
connect(hw, &OpenGLRenderer::errorInitializing, [=]() {
/* Renderer not could initialize, fallback to software. */
imagebufs = {};
QTimer::singleShot(0, this, [this]() { switchRenderer(Renderer::Software); });
});
current.reset(this->createWindowContainer(hw, this));
break;
}
#if QT_CONFIG(vulkan)
case Renderer::Vulkan:
{
this->createWinId();
VulkanWindowRenderer *hw = nullptr;
try {
hw = new VulkanWindowRenderer(this);
} catch (std::runtime_error &e) {
auto msgBox = new QMessageBox(QMessageBox::Critical, "86Box", e.what() + QString("\nFalling back to software rendering."), QMessageBox::Ok);
msgBox->setAttribute(Qt::WA_DeleteOnClose);
msgBox->show();
imagebufs = {};
QTimer::singleShot(0, this, [this]() { switchRenderer(Renderer::Software); });
current.reset(nullptr);
break;
}
rendererWindow = hw;
connect(this, &RendererStack::blitToRenderer, hw, &VulkanWindowRenderer::onBlit, Qt::QueuedConnection);
connect(hw, &VulkanWindowRenderer::rendererInitialized, [=]() {
/* Buffers are available only after initialization. */
imagebufs = rendererWindow->getBuffers();
endblit();
emit rendererChanged();
});
connect(hw, &VulkanWindowRenderer::errorInitializing, [=]() {
/* Renderer could not initialize, fallback to software. */
auto msgBox = new QMessageBox(QMessageBox::Critical, "86Box", QString("Failed to initialize Vulkan renderer.\nFalling back to software rendering."), QMessageBox::Ok);
msgBox->setAttribute(Qt::WA_DeleteOnClose);
msgBox->show();
imagebufs = {};
QTimer::singleShot(0, this, [this]() { switchRenderer(Renderer::Software); });
});
current.reset(this->createWindowContainer(hw, this));
break;
}
#endif
}
if (current.get() == nullptr)
return;
current->setFocusPolicy(Qt::NoFocus);
current->setFocusProxy(this);
current->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
current->setStyleSheet("background-color: black");
addWidget(current.get());
this->setStyleSheet("background-color: black");
currentBuf = 0;
if (renderer != Renderer::OpenGL3 && renderer != Renderer::Vulkan) {
imagebufs = rendererWindow->getBuffers();
endblit();
emit rendererChanged();
}
}
// called from blitter thread
void
RendererStack::blit(int x, int y, int w, int h)
{
if ((x < 0) || (y < 0) || (w <= 0) || (h <= 0) ||
(w > 2048) || (h > 2048) ||
(monitors[m_monitor_index].target_buffer == NULL) || imagebufs.empty() ||
std::get<std::atomic_flag *>(imagebufs[currentBuf])->test_and_set()) {
video_blit_complete_monitor(m_monitor_index);
return;
}
sx = x;
sy = y;
sw = this->w = w;
sh = this->h = h;
uint8_t *imagebits = std::get<uint8_t *>(imagebufs[currentBuf]);
for (int y1 = y; y1 < (y + h); y1++) {
auto scanline = imagebits + (y1 * rendererWindow->getBytesPerRow()) + (x * 4);
video_copy(scanline, &(monitors[m_monitor_index].target_buffer->line[y1][x]), w * 4);
}
if (monitors[m_monitor_index].mon_screenshots) {
video_screenshot_monitor((uint32_t *) imagebits, x, y, 2048, m_monitor_index);
}
video_blit_complete_monitor(m_monitor_index);
emit blitToRenderer(currentBuf, sx, sy, sw, sh);
currentBuf = (currentBuf + 1) % imagebufs.size();
}
void
RendererStack::closeEvent(QCloseEvent *event)
{
if (cpu_thread_run == 1 || is_quit == 0) {
event->accept();
main_window->ui->actionShow_non_primary_monitors->setChecked(false);
return;
}
event->ignore();
main_window->close();
}
void
RendererStack::changeEvent(QEvent *event)
{
if (m_monitor_index != 0 && isVisible()) {
monitor_settings[m_monitor_index].mon_window_maximized = isMaximized();
config_save();
}
}
bool
RendererStack::event(QEvent* event)
{
if (event->type() == QEvent::MouseMove) {
QMouseEvent* mouse_event = (QMouseEvent*)event;
if (m_monitor_index >= 1) {
if (mouse_input_mode >= 1) {
mouse_x_abs = (mouse_event->localPos().x()) / (long double)width();
mouse_y_abs = (mouse_event->localPos().y()) / (long double)height();
if (!mouse_tablet_in_proximity)
mouse_tablet_in_proximity = mousedata.mouse_tablet_in_proximity;
}
return QStackedWidget::event(event);
}
#ifdef Q_OS_WINDOWS
if (mouse_input_mode == 0) {
mouse_x_abs = (mouse_event->localPos().x()) / (long double)width();
mouse_y_abs = (mouse_event->localPos().y()) / (long double)height();
return QStackedWidget::event(event);
}
#endif
mouse_x_abs = (mouse_event->localPos().x()) / (long double)width();
mouse_y_abs = (mouse_event->localPos().y()) / (long double)height();
mouse_tablet_in_proximity = mousedata.mouse_tablet_in_proximity;
}
return QStackedWidget::event(event);
}
void
RendererStack::setFocusRenderer()
{
if (current)
current->setFocus();
}
void
RendererStack::onResize(int width, int height)
{
if (rendererWindow) {
rendererWindow->r_monitor_index = m_monitor_index;
rendererWindow->onResize(width, height);
}
}
``` | /content/code_sandbox/src/qt/qt_rendererstack.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,817 |
```c++
class QWindow;
void wl_mouse_capture(QWindow *window);
void wl_mouse_uncapture();
void wl_init();
``` | /content/code_sandbox/src/qt/wl_mouse.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 24 |
```objective-c
#ifdef __cplusplus
extern "C" {
#endif
void set_wm_class(unsigned long window, char *res_name);
#ifdef __cplusplus
}
#endif
``` | /content/code_sandbox/src/qt/x11_util.h | objective-c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 33 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Hard disk configuration UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
*
*/
#include "qt_settingsharddisks.hpp"
#include "ui_qt_settingsharddisks.h"
extern "C" {
#include <86box/86box.h>
#include <86box/hdd.h>
}
#include <QStandardItemModel>
#include "qt_harddiskdialog.hpp"
#include "qt_harddrive_common.hpp"
#include "qt_settings_bus_tracking.hpp"
#include "qt_progsettings.hpp"
const int ColumnBus = 0;
const int ColumnFilename = 1;
const int ColumnCylinders = 2;
const int ColumnHeads = 3;
const int ColumnSectors = 4;
const int ColumnSize = 5;
const int ColumnSpeed = 6;
const int DataBus = Qt::UserRole;
const int DataBusChannel = Qt::UserRole + 1;
const int DataBusPrevious = Qt::UserRole + 2;
const int DataBusChannelPrevious = Qt::UserRole + 3;
#if 0
static void
normalize_hd_list()
{
hard_disk_t ihdd[HDD_NUM];
int j;
j = 0;
memset(ihdd, 0x00, HDD_NUM * sizeof(hard_disk_t));
for (uint8_t i = 0; i < HDD_NUM; i++) {
if (temp_hdd[i].bus != HDD_BUS_DISABLED) {
memcpy(&(ihdd[j]), &(temp_hdd[i]), sizeof(hard_disk_t));
j++;
}
}
memcpy(temp_hdd, ihdd, HDD_NUM * sizeof(hard_disk_t));
}
#endif
static QString
busChannelName(const QModelIndex &idx)
{
return Harddrives::BusChannelName(idx.data(DataBus).toUInt(), idx.data(DataBusChannel).toUInt());
}
static void
addRow(QAbstractItemModel *model, hard_disk_t *hd)
{
const QString userPath = usr_path;
int row = model->rowCount();
model->insertRow(row);
QString busName = Harddrives::BusChannelName(hd->bus, hd->channel);
model->setData(model->index(row, ColumnBus), busName);
model->setData(model->index(row, ColumnBus), ProgSettings::loadIcon("/hard_disk.ico"), Qt::DecorationRole);
model->setData(model->index(row, ColumnBus), hd->bus, DataBus);
model->setData(model->index(row, ColumnBus), hd->bus, DataBusPrevious);
model->setData(model->index(row, ColumnBus), hd->channel, DataBusChannel);
model->setData(model->index(row, ColumnBus), hd->channel, DataBusChannelPrevious);
Harddrives::busTrackClass->device_track(1, DEV_HDD, hd->bus, hd->channel);
QString fileName = hd->fn;
if (fileName.startsWith(userPath, Qt::CaseInsensitive)) {
model->setData(model->index(row, ColumnFilename), fileName.mid(userPath.size()));
} else {
model->setData(model->index(row, ColumnFilename), fileName);
}
model->setData(model->index(row, ColumnFilename), fileName, Qt::UserRole);
model->setData(model->index(row, ColumnCylinders), hd->tracks);
model->setData(model->index(row, ColumnHeads), hd->hpc);
model->setData(model->index(row, ColumnSectors), hd->spt);
model->setData(model->index(row, ColumnSize), (hd->tracks * hd->hpc * hd->spt) >> 11);
model->setData(model->index(row, ColumnSpeed), hdd_preset_getname(hd->speed_preset));
model->setData(model->index(row, ColumnSpeed), hd->speed_preset, Qt::UserRole);
}
SettingsHarddisks::SettingsHarddisks(QWidget *parent)
: QWidget(parent)
, ui(new Ui::SettingsHarddisks)
{
ui->setupUi(this);
QAbstractItemModel *model = new QStandardItemModel(0, 7, this);
model->setHeaderData(ColumnBus, Qt::Horizontal, tr("Bus"));
model->setHeaderData(ColumnFilename, Qt::Horizontal, tr("File"));
model->setHeaderData(ColumnCylinders, Qt::Horizontal, tr("C"));
model->setHeaderData(ColumnHeads, Qt::Horizontal, tr("H"));
model->setHeaderData(ColumnSectors, Qt::Horizontal, tr("S"));
model->setHeaderData(ColumnSize, Qt::Horizontal, tr("MiB"));
model->setHeaderData(ColumnSpeed, Qt::Horizontal, tr("Speed"));
ui->tableView->setModel(model);
for (int i = 0; i < HDD_NUM; i++) {
if (hdd[i].bus > 0) {
addRow(model, &hdd[i]);
}
}
if (model->rowCount() == HDD_NUM) {
ui->pushButtonNew->setEnabled(false);
ui->pushButtonExisting->setEnabled(false);
}
ui->tableView->resizeColumnsToContents();
ui->tableView->horizontalHeader()->setSectionResizeMode(ColumnFilename, QHeaderView::Stretch);
auto *tableSelectionModel = ui->tableView->selectionModel();
connect(tableSelectionModel, &QItemSelectionModel::currentRowChanged, this, &SettingsHarddisks::onTableRowChanged);
onTableRowChanged(QModelIndex());
Harddrives::populateBuses(ui->comboBoxBus->model());
on_comboBoxBus_currentIndexChanged(0);
}
SettingsHarddisks::~SettingsHarddisks()
{
delete ui;
}
void
SettingsHarddisks::save()
{
memset(hdd, 0, sizeof(hdd));
auto *model = ui->tableView->model();
int rows = model->rowCount();
for (int i = 0; i < rows; ++i) {
auto idx = model->index(i, ColumnBus);
hdd[i].bus = idx.data(DataBus).toUInt();
hdd[i].channel = idx.data(DataBusChannel).toUInt();
hdd[i].tracks = idx.siblingAtColumn(ColumnCylinders).data().toUInt();
hdd[i].hpc = idx.siblingAtColumn(ColumnHeads).data().toUInt();
hdd[i].spt = idx.siblingAtColumn(ColumnSectors).data().toUInt();
hdd[i].speed_preset = idx.siblingAtColumn(ColumnSpeed).data(Qt::UserRole).toUInt();
QByteArray fileName = idx.siblingAtColumn(ColumnFilename).data(Qt::UserRole).toString().toUtf8();
strncpy(hdd[i].fn, fileName.data(), sizeof(hdd[i].fn) - 1);
hdd[i].priv = nullptr;
}
}
void SettingsHarddisks::reloadBusChannels() {
const auto selected = ui->comboBoxChannel->currentIndex();
Harddrives::populateBusChannels(ui->comboBoxChannel->model(), ui->comboBoxBus->currentData().toInt(), Harddrives::busTrackClass);
ui->comboBoxChannel->setCurrentIndex(selected);
enableCurrentlySelectedChannel();
}
void
SettingsHarddisks::on_comboBoxBus_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
buschangeinprogress = true;
auto idx = ui->tableView->selectionModel()->currentIndex();
if (idx.isValid()) {
auto *model = ui->tableView->model();
auto col = idx.siblingAtColumn(ColumnBus);
model->setData(col, ui->comboBoxBus->currentData(Qt::UserRole), DataBus);
model->setData(col, busChannelName(col), Qt::DisplayRole);
Harddrives::busTrackClass->device_track(0, DEV_HDD, model->data(col, DataBusPrevious).toInt(), model->data(col, DataBusChannelPrevious).toInt());
model->setData(col, ui->comboBoxBus->currentData(Qt::UserRole), DataBusPrevious);
}
Harddrives::populateBusChannels(ui->comboBoxChannel->model(), ui->comboBoxBus->currentData().toInt(), Harddrives::busTrackClass);
Harddrives::populateSpeeds(ui->comboBoxSpeed->model(), ui->comboBoxBus->currentData().toInt());
int chanIdx = 0;
switch (ui->comboBoxBus->currentData().toInt()) {
case HDD_BUS_MFM:
chanIdx = (Harddrives::busTrackClass->next_free_mfm_channel());
break;
case HDD_BUS_XTA:
chanIdx = (Harddrives::busTrackClass->next_free_xta_channel());
break;
case HDD_BUS_ESDI:
chanIdx = (Harddrives::busTrackClass->next_free_esdi_channel());
break;
case HDD_BUS_ATAPI:
case HDD_BUS_IDE:
chanIdx = (Harddrives::busTrackClass->next_free_ide_channel());
break;
case HDD_BUS_SCSI:
chanIdx = (Harddrives::busTrackClass->next_free_scsi_id());
break;
}
if (idx.isValid()) {
auto *model = ui->tableView->model();
auto col = idx.siblingAtColumn(ColumnBus);
model->setData(col, chanIdx, DataBusChannelPrevious);
}
ui->comboBoxChannel->setCurrentIndex(chanIdx);
buschangeinprogress = false;
}
void
SettingsHarddisks::on_comboBoxChannel_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
auto idx = ui->tableView->selectionModel()->currentIndex();
if (idx.isValid()) {
auto *model = ui->tableView->model();
auto col = idx.siblingAtColumn(ColumnBus);
model->setData(col, ui->comboBoxChannel->currentData(Qt::UserRole), DataBusChannel);
model->setData(col, busChannelName(col), Qt::DisplayRole);
if (!buschangeinprogress)
Harddrives::busTrackClass->device_track(0, DEV_HDD, model->data(col, DataBus).toInt(), model->data(col, DataBusChannelPrevious).toUInt());
Harddrives::busTrackClass->device_track(1, DEV_HDD, model->data(col, DataBus).toInt(), model->data(col, DataBusChannel).toUInt());
model->setData(col, ui->comboBoxChannel->currentData(Qt::UserRole), DataBusChannelPrevious);
emit driveChannelChanged();
}
}
void
SettingsHarddisks::enableCurrentlySelectedChannel()
{
const auto *item_model = qobject_cast<QStandardItemModel*>(ui->comboBoxChannel->model());
const auto index = ui->comboBoxChannel->currentIndex();
auto *item = item_model->item(index);
if(item) {
item->setEnabled(true);
}
}
void
SettingsHarddisks::on_comboBoxSpeed_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
auto idx = ui->tableView->selectionModel()->currentIndex();
if (idx.isValid()) {
auto *model = ui->tableView->model();
auto col = idx.siblingAtColumn(ColumnSpeed);
model->setData(col, ui->comboBoxSpeed->currentData(Qt::UserRole), Qt::UserRole);
model->setData(col, hdd_preset_getname(ui->comboBoxSpeed->currentData(Qt::UserRole).toUInt()));
}
}
void
SettingsHarddisks::onTableRowChanged(const QModelIndex ¤t)
{
bool hidden = !current.isValid();
ui->labelBus->setHidden(hidden);
ui->labelChannel->setHidden(hidden);
ui->labelSpeed->setHidden(hidden);
ui->comboBoxBus->setHidden(hidden);
ui->comboBoxChannel->setHidden(hidden);
ui->comboBoxSpeed->setHidden(hidden);
uint32_t bus = current.siblingAtColumn(ColumnBus).data(DataBus).toUInt();
uint32_t busChannel = current.siblingAtColumn(ColumnBus).data(DataBusChannel).toUInt();
uint32_t speed = current.siblingAtColumn(ColumnSpeed).data(Qt::UserRole).toUInt();
auto *model = ui->comboBoxBus->model();
auto match = model->match(model->index(0, 0), Qt::UserRole, bus);
if (!match.isEmpty()) {
ui->comboBoxBus->setCurrentIndex(match.first().row());
}
model = ui->comboBoxChannel->model();
match = model->match(model->index(0, 0), Qt::UserRole, busChannel);
if (!match.isEmpty()) {
ui->comboBoxChannel->setCurrentIndex(match.first().row());
}
model = ui->comboBoxSpeed->model();
match = model->match(model->index(0, 0), Qt::UserRole, speed);
if (!match.isEmpty()) {
ui->comboBoxSpeed->setCurrentIndex(match.first().row());
}
reloadBusChannels();
}
static void
addDriveFromDialog(Ui::SettingsHarddisks *ui, const HarddiskDialog &dlg)
{
QByteArray fn = dlg.fileName().toUtf8();
hard_disk_t hd;
memset(&hd, 0, sizeof(hd));
hd.bus = dlg.bus();
hd.channel = dlg.channel();
hd.tracks = dlg.cylinders();
hd.hpc = dlg.heads();
hd.spt = dlg.sectors();
strncpy(hd.fn, fn.data(), sizeof(hd.fn) - 1);
hd.speed_preset = dlg.speed();
addRow(ui->tableView->model(), &hd);
ui->tableView->resizeColumnsToContents();
ui->tableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
if (ui->tableView->model()->rowCount() == HDD_NUM) {
ui->pushButtonNew->setEnabled(false);
ui->pushButtonExisting->setEnabled(false);
}
}
void
SettingsHarddisks::on_pushButtonNew_clicked()
{
HarddiskDialog dialog(false, this);
switch (dialog.exec()) {
case QDialog::Accepted:
addDriveFromDialog(ui, dialog);
reloadBusChannels();
break;
}
}
void
SettingsHarddisks::on_pushButtonExisting_clicked()
{
HarddiskDialog dialog(true, this);
switch (dialog.exec()) {
case QDialog::Accepted:
addDriveFromDialog(ui, dialog);
reloadBusChannels();
break;
}
}
void
SettingsHarddisks::on_pushButtonRemove_clicked()
{
auto idx = ui->tableView->selectionModel()->currentIndex();
if (!idx.isValid()) {
return;
}
auto *model = ui->tableView->model();
const auto col = idx.siblingAtColumn(ColumnBus);
Harddrives::busTrackClass->device_track(0, DEV_HDD, model->data(col, DataBus).toInt(), model->data(col, DataBusChannel).toInt());
model->removeRow(idx.row());
ui->pushButtonNew->setEnabled(true);
ui->pushButtonExisting->setEnabled(true);
}
``` | /content/code_sandbox/src/qt/qt_settingsharddisks.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,314 |
```c++
#pragma once
#include <QDialog>
#include <QEvent>
#include <QImage>
#include <QRect>
#include <QWidget>
#include <atomic>
#include <memory>
#include <tuple>
#include <vector>
class QWidget;
class RendererCommon {
public:
RendererCommon();
void onResize(int width, int height);
virtual void finalize() { }
virtual uint32_t getBytesPerRow() { return 2048 * 4; }
virtual std::vector<std::tuple<uint8_t *, std::atomic_flag *>> getBuffers()
{
std::vector<std::tuple<uint8_t *, std::atomic_flag *>> buffers;
return buffers;
}
/* Does renderer implement options dialog */
virtual bool hasOptions() const { return false; }
/* Returns options dialog for renderer */
virtual QDialog *getOptions(QWidget *parent) { return nullptr; }
/* Reloads options of renderer */
virtual void reloadOptions() { }
int r_monitor_index = 0;
protected:
bool eventDelegate(QEvent *event, bool &result);
void drawStatusBarIcons(QPainter* painter);
QRect source { 0, 0, 0, 0 };
QRect destination;
QWidget *parentWidget { nullptr };
std::vector<std::atomic_flag> buf_usage;
};
``` | /content/code_sandbox/src/qt/qt_renderercommon.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 282 |
```c++
#ifndef QT_SETTINGSSOUND_HPP
#define QT_SETTINGSSOUND_HPP
#include <QWidget>
namespace Ui {
class SettingsSound;
}
class SettingsSound : public QWidget {
Q_OBJECT
public:
explicit SettingsSound(QWidget *parent = nullptr);
~SettingsSound();
void save();
public slots:
void onCurrentMachineChanged(int machineId);
private slots:
void on_pushButtonConfigureMPU401_clicked();
void on_checkBoxMPU401_stateChanged(int arg1);
void on_pushButtonConfigureMidiIn_clicked();
void on_pushButtonConfigureMidiOut_clicked();
void on_comboBoxMidiIn_currentIndexChanged(int index);
void on_comboBoxMidiOut_currentIndexChanged(int index);
void on_pushButtonConfigureSoundCard1_clicked();
void on_comboBoxSoundCard1_currentIndexChanged(int index);
void on_pushButtonConfigureSoundCard2_clicked();
void on_comboBoxSoundCard2_currentIndexChanged(int index);
void on_pushButtonConfigureSoundCard3_clicked();
void on_comboBoxSoundCard3_currentIndexChanged(int index);
void on_pushButtonConfigureSoundCard4_clicked();
void on_comboBoxSoundCard4_currentIndexChanged(int index);
private:
Ui::SettingsSound *ui;
int machineId = 0;
};
#endif // QT_SETTINGSSOUND_HPP
``` | /content/code_sandbox/src/qt/qt_settingssound.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 265 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* OpenGL renderer options for Qt
*
*
*
* Authors: Teemu Korhonen
*
*/
#include <QByteArray>
#include <QFile>
#include <QRegularExpression>
#include <QStringBuilder>
#include <stdexcept>
#include "qt_opengloptions.hpp"
extern "C" {
#include <86box/86box.h>
}
/* Default vertex shader. */
static const GLchar *vertex_shader = "\
in vec2 VertexCoord;\n\
in vec2 TexCoord;\n\
out vec2 tex;\n\
void main(){\n\
gl_Position = vec4(VertexCoord, 0.0, 1.0);\n\
tex = TexCoord;\n\
}\n";
/* Default fragment shader. */
static const GLchar *fragment_shader = "\
in vec2 tex;\n\
uniform sampler2D texsampler;\n\
out vec4 color;\n\
void main() {\n\
color = texture(texsampler, tex);\n\
}\n";
OpenGLOptions::OpenGLOptions(QObject *parent, bool loadConfig, const QString &glslVersion)
: QObject(parent)
, m_glslVersion(glslVersion)
{
m_filter = video_filter_method == 0
? FilterType::Nearest
: FilterType::Linear;
if (!loadConfig)
return;
/* Initialize with config. */
m_vsync = video_vsync != 0;
m_framerate = video_framerate;
m_renderBehavior = video_framerate == -1
? RenderBehaviorType::SyncWithVideo
: RenderBehaviorType::TargetFramerate;
QString shaderPath(video_shader);
if (shaderPath.isEmpty()) {
addDefaultShader();
} else {
try {
addShader(shaderPath);
} catch (const std::runtime_error &) {
/* Fallback to default shader */
addDefaultShader();
}
}
}
void
OpenGLOptions::save() const
{
video_vsync = m_vsync ? 1 : 0;
video_framerate = m_renderBehavior == RenderBehaviorType::SyncWithVideo ? -1 : m_framerate;
video_filter_method = m_filter == FilterType::Nearest ? 0 : 1;
/* TODO: multiple shaders */
auto path = m_shaders.first().path().toLocal8Bit();
if (!path.isEmpty())
qstrncpy(video_shader, path.constData(), sizeof(video_shader));
else
video_shader[0] = '\0';
}
OpenGLOptions::FilterType
OpenGLOptions::filter() const
{
/* Filter method is controlled externally */
return video_filter_method == 0
? FilterType::Nearest
: FilterType::Linear;
}
void
OpenGLOptions::setRenderBehavior(RenderBehaviorType value)
{
m_renderBehavior = value;
}
void
OpenGLOptions::setFrameRate(int value)
{
m_framerate = value;
}
void
OpenGLOptions::setVSync(bool value)
{
m_vsync = value;
}
void
OpenGLOptions::setFilter(FilterType value)
{
m_filter = value;
}
void
OpenGLOptions::addShader(const QString &path)
{
QFile shader_file(path);
if (!shader_file.open(QIODevice::ReadOnly | QIODevice::Text)) {
throw std::runtime_error(
QString(tr("Error opening \"%1\": %2"))
.arg(path)
.arg(shader_file.errorString())
.toStdString());
}
auto shader_text = QString(shader_file.readAll());
shader_file.close();
/* Remove parameter lines */
shader_text.remove(QRegularExpression("^\\s*#pragma parameter.*?\\n", QRegularExpression::MultilineOption));
QRegularExpression version("^\\s*(#version\\s+\\w+)", QRegularExpression::MultilineOption);
auto match = version.match(shader_text);
QString version_line(m_glslVersion);
if (match.hasMatch()) {
/* Extract existing version and remove it. */
version_line = match.captured(1);
shader_text.remove(version);
}
auto shader = new QOpenGLShaderProgram(this);
auto throw_shader_error = [path, shader](const QString &what) {
throw std::runtime_error(
QString(what % ":\n\n %2")
.arg(path)
.arg(shader->log())
.toStdString());
};
static const char *extension = "\n#extension GL_ARB_shading_language_420pack : enable\n";
if (!shader->addShaderFromSourceCode(QOpenGLShader::Vertex, version_line % extension % "\n#define VERTEX\n#line 1\n" % shader_text))
throw_shader_error(tr("Error compiling vertex shader in file \"%1\""));
if (!shader->addShaderFromSourceCode(QOpenGLShader::Fragment, version_line % extension % "\n#define FRAGMENT\n#line 1\n" % shader_text))
throw_shader_error(tr("Error compiling fragment shader in file \"%1\""));
if (!shader->link())
throw_shader_error(tr("Error linking shader program in file \"%1\""));
m_shaders << OpenGLShaderPass(shader, path);
}
void
OpenGLOptions::addDefaultShader()
{
auto shader = new QOpenGLShaderProgram(this);
shader->addShaderFromSourceCode(QOpenGLShader::Vertex, m_glslVersion % "\n" % vertex_shader);
shader->addShaderFromSourceCode(QOpenGLShader::Fragment, m_glslVersion % "\n" % fragment_shader);
shader->link();
m_shaders << OpenGLShaderPass(shader, QString());
}
``` | /content/code_sandbox/src/qt/qt_opengloptions.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,277 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Utility functions.
*
*
*
* Authors: Teemu Korhonen
*
*/
#include <QDir>
#include <QFileInfo>
#include <QStringBuilder>
#include <QStringList>
#include <QWidget>
#include <QApplication>
#if QT_VERSION <= QT_VERSION_CHECK(5, 14, 0)
# include <QDesktopWidget>
#endif
#include <QUuid>
#include "qt_util.hpp"
extern "C" {
#include <86box/86box.h>
#include <86box/config.h>
#include <86box/device.h>
#include <86box/ini.h>
#include <86box/random.h>
#include <86box/thread.h>
#include <86box/timer.h>
#include <86box/network.h>
}
namespace util {
QScreen *
screenOfWidget(QWidget *widget)
{
#if QT_VERSION <= QT_VERSION_CHECK(5, 14, 0)
return QApplication::screens()[QApplication::desktop()->screenNumber(widget) == -1 ? 0 : QApplication::desktop()->screenNumber(widget)];
#else
return widget->screen();
#endif
}
QString
DlgFilter(std::initializer_list<QString> extensions, bool last)
{
QStringList temp;
for (auto ext : extensions) {
#ifdef Q_OS_UNIX
if (ext == "*") {
temp.append("*");
continue;
}
temp.append("*." % ext.toUpper());
#endif
temp.append("*." % ext);
}
#ifdef Q_OS_UNIX
temp.removeDuplicates();
#endif
return " (" % temp.join(' ') % ")" % (!last ? ";;" : "");
}
QString currentUuid()
{
auto configPath = QFileInfo(cfg_path).dir().canonicalPath();
if(!configPath.endsWith("/")) {
configPath.append("/");
}
return QUuid::createUuidV5(QUuid{}, configPath).toString(QUuid::WithoutBraces);
}
bool compareUuid()
{
// A uuid not set in the config file will have a zero length.
// Any uuid that is lower than the minimum length will be considered invalid
// and a new one will be generated
if (const auto currentUuidLength = QString(uuid).length(); currentUuidLength < UUID_MIN_LENGTH) {
storeCurrentUuid();
return true;
}
// Do not prompt on mismatch if the system does not have any configured NICs. Just update the uuid
if(!hasConfiguredNICs() && uuid != currentUuid()) {
storeCurrentUuid();
return true;
}
// The uuid appears to be a valid, at least by length.
// Compare with a simple string match
return uuid == currentUuid();
}
void
storeCurrentUuid()
{
strncpy(uuid, currentUuid().toUtf8().constData(), sizeof(uuid) - 1);
}
void
generateNewMacAdresses()
{
for (int i = 0; i < NET_CARD_MAX; ++i) {
auto net_card = net_cards_conf[i];
if (net_card.device_num != 0) {
const auto network_device = network_card_getdevice(net_card.device_num);
device_context_t device_context;
device_set_context(&device_context, network_device, i + 1);
auto generatedMac = QString::asprintf("%02X:%02X:%02X", random_generate(), random_generate(), random_generate()).toLower();
config_set_string(device_context.name, "mac", generatedMac.toUtf8().constData());
}
}
}
bool
hasConfiguredNICs()
{
for (int i = 0; i < NET_CARD_MAX; ++i) {
if (const auto net_card = net_cards_conf[i]; net_card.device_num != 0) {
return true;
}
}
return false;
}
}
``` | /content/code_sandbox/src/qt/qt_util.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 863 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* xkbcommon-x11 keyboard input module.
*
* Heavily inspired by libxkbcommon interactive-x11.c
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
extern "C" {
/* xkb.h has identifiers named "explicit", which is a C++ keyword now... */
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wkeyword-macro"
#endif
#define explicit explicit_
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include <xcb/xkb.h>
#undef explicit
#include <xkbcommon/xkbcommon-x11.h>
};
#include "xkbcommon_keyboard.hpp"
#include <qpa/qplatformnativeinterface.h>
#include <QtDebug>
#include <QGuiApplication>
void
xkbcommon_x11_init()
{
xcb_connection_t *conn;
struct xkb_context *ctx;
int32_t core_kbd_device_id;
struct xkb_keymap *keymap;
conn = (xcb_connection_t *) QGuiApplication::platformNativeInterface()->nativeResourceForIntegration("connection");
if (!conn) {
qWarning() << "XKB Keyboard: X server connection failed";
return;
}
int ret = xkb_x11_setup_xkb_extension(conn,
XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION,
XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS,
NULL, NULL, NULL, NULL);
if (!ret) {
qWarning() << "XKB Keyboard: XKB extension setup failed";
return;
}
ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
if (!ctx) {
qWarning() << "XKB Keyboard: XKB context creation failed";
return;
}
core_kbd_device_id = xkb_x11_get_core_keyboard_device_id(conn);
if (core_kbd_device_id == -1) {
qWarning() << "XKB Keyboard: Core keyboard device not found";
goto err_ctx;
}
keymap = xkb_x11_keymap_new_from_device(ctx, conn, core_kbd_device_id, XKB_KEYMAP_COMPILE_NO_FLAGS);
if (!keymap) {
qWarning() << "XKB Keyboard: Keymap loading failed";
goto err_ctx;
}
xkbcommon_init(keymap);
return;
err_ctx:
xkb_context_unref(ctx);
}
``` | /content/code_sandbox/src/qt/xkbcommon_x11_keyboard.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 583 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* X11 Xinput2 mouse input module.
*
*
*
* Authors: Cacodemon345
* RichardG <richardg867@gmail.com>
*
*/
#include <QDebug>
#include <QThread>
#include <QProcess>
#include <QApplication>
#include <QAbstractNativeEventFilter>
#include "qt_mainwindow.hpp"
extern MainWindow *main_window;
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <atomic>
extern "C" {
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/XInput2.h>
#include <unistd.h>
#include <fcntl.h>
#include <86box/86box.h>
#include <86box/mouse.h>
#include <86box/plat.h>
}
static Display *disp = nullptr;
static QThread *procThread = nullptr;
static XIEventMask ximask;
static std::atomic<bool> exitfromthread = false;
static std::atomic<double> xi2_mouse_abs_x = 0, xi2_mouse_abs_y = 0;
static int xi2opcode = 0;
static double prev_coords[2] = { 0.0 };
static Time prev_time = 0;
/* Based on SDL2. */
static void
parse_valuators(const double *input_values,
const unsigned char *mask, int mask_len,
double *output_values, int output_values_len)
{
int i = 0;
int z = 0;
int top = mask_len * 8;
if (top > 16)
top = 16;
memset(output_values, 0, output_values_len * sizeof(output_values[0]));
for (; i < top && z < output_values_len; i++) {
if (XIMaskIsSet(mask, i)) {
output_values[z] = *input_values;
input_values++;
}
z++;
}
}
static bool exitthread = false;
static int
xinput2_get_xtest_pointer()
{
/* The XTEST pointer events injected by VNC servers to move the cursor always report
absolute coordinates, despite XTEST declaring relative axes (related: SDL issue 1836).
This looks for the XTEST pointer so that we can assume it's absolute as a workaround.
TigerVNC publishes both the XTEST pointer and a TigerVNC pointer, but actual
RawMotion events are published using the TigerVNC pointer */
int devs;
XIDeviceInfo *info = XIQueryDevice(disp, XIAllDevices, &devs), *dev;
for (int i = 0; i < devs; i++) {
dev = &info[i];
if ((dev->use == XISlavePointer) && !strcmp(dev->name, "TigerVNC pointer"))
return dev->deviceid;
}
/* Steam Input on SteamOS uses XTEST the intended way for trackpad movement.
Hope nobody is remoting into their Steam Deck with a non-TigerVNC server. */
for (int i = 0; i < devs; i++) {
dev = &info[i];
if ((dev->use == XISlavePointer) && !strncmp(dev->name, "Valve Software Steam Deck", 25))
return -1;
}
for (int i = 0; i < devs; i++) {
dev = &info[i];
if ((dev->use == XISlavePointer) && !strcmp(dev->name, "Virtual core XTEST pointer"))
return dev->deviceid;
}
return -1;
}
void
xinput2_proc()
{
Window win;
win = DefaultRootWindow(disp);
int xtest_pointer = xinput2_get_xtest_pointer();
ximask.deviceid = XIAllMasterDevices;
ximask.mask_len = XIMaskLen(XI_LASTEVENT);
ximask.mask = (unsigned char *) calloc(ximask.mask_len, sizeof(unsigned char));
XISetMask(ximask.mask, XI_RawMotion);
XISetMask(ximask.mask, XI_Motion);
XISetMask(ximask.mask, XI_DeviceChanged);
XISelectEvents(disp, win, &ximask, 1);
XSync(disp, False);
while (true) {
XEvent ev;
XGenericEventCookie *cookie = (XGenericEventCookie *) &ev.xcookie;
XNextEvent(disp, (XEvent *) &ev);
if (XGetEventData(disp, cookie) && (cookie->type == GenericEvent) && (cookie->extension == xi2opcode)) {
const XIRawEvent *rawev = (const XIRawEvent *) cookie->data;
double coords[2] = { 0.0 };
switch (cookie->evtype) {
case XI_Motion:
{
const XIDeviceEvent *devev = (const XIDeviceEvent *) cookie->data;
parse_valuators(devev->valuators.values, devev->valuators.mask, devev->valuators.mask_len, coords, 2);
/* XIDeviceEvent and XIRawEvent share the XIEvent base struct, which
doesn't contain deviceid, but that's at the same offset on both. */
goto common_motion;
}
case XI_RawMotion:
{
parse_valuators(rawev->raw_values, rawev->valuators.mask, rawev->valuators.mask_len, coords, 2);
common_motion:
/* Ignore duplicated events. */
if ((rawev->time == prev_time) && (coords[0] == prev_coords[0]) && (coords[1] == prev_coords[1]))
break;
/* SDL2 queries the device on every event, so doing that should be fine. */
int i;
XIDeviceInfo *xidevinfo = XIQueryDevice(disp, rawev->deviceid, &i);
if (xidevinfo) {
/* Process the device's axes. */
int axis = 0;
for (i = 0; i < xidevinfo->num_classes; i++) {
const XIValuatorClassInfo *v = (const XIValuatorClassInfo *) xidevinfo->classes[i];
if (v->type == XIValuatorClass) {
/* Is this an absolute or relative axis? */
if ((v->mode == XIModeRelative) && (rawev->sourceid != xtest_pointer)) {
/* Set relative coordinates. */
if (axis == 0)
mouse_scale_x(coords[axis]);
else
mouse_scale_y(coords[axis]);
} else {
/* Convert absolute value range to pixel granularity, then to relative coordinates. */
int disp_screen = XDefaultScreen(disp);
double abs_div;
if (axis == 0) {
if (v->mode == XIModeRelative) {
/* XTEST axes have dummy min/max values because they're nominally relative,
but in practice, the injected absolute coordinates are already in pixels. */
abs_div = coords[axis];
} else {
abs_div = (v->max - v->min) / (double) XDisplayWidth(disp, disp_screen);
if (abs_div <= 0)
abs_div = 1;
abs_div = (coords[axis] - v->min) / abs_div;
}
if (xi2_mouse_abs_x != 0)
mouse_scale_x(abs_div - xi2_mouse_abs_x);
xi2_mouse_abs_x = abs_div;
} else {
if (v->mode == XIModeRelative) {
/* Same as above. */
abs_div = coords[axis];
} else {
abs_div = (v->max - v->min) / (double) XDisplayHeight(disp, disp_screen);
if (abs_div <= 0)
abs_div = 1;
abs_div = (coords[axis] - v->min) / abs_div;
}
if (xi2_mouse_abs_y != 0)
mouse_scale_y(abs_div - xi2_mouse_abs_y);
xi2_mouse_abs_y = abs_div;
}
}
prev_coords[axis] = coords[axis];
if (++axis >= 2) /* stop after X and Y processed */
break;
}
}
}
prev_time = rawev->time;
if (!mouse_capture)
break;
XWindowAttributes winattrib {};
if (XGetWindowAttributes(disp, main_window->winId(), &winattrib)) {
auto globalPoint = main_window->mapToGlobal(QPoint(main_window->width() / 2, main_window->height() / 2));
XWarpPointer(disp, XRootWindow(disp, XScreenNumberOfScreen(winattrib.screen)), XRootWindow(disp, XScreenNumberOfScreen(winattrib.screen)), 0, 0, 0, 0, globalPoint.x(), globalPoint.y());
XFlush(disp);
}
break;
}
case XI_DeviceChanged:
{
/* Re-scan for XTEST pointer, just in case. */
xtest_pointer = xinput2_get_xtest_pointer();
break;
}
}
}
XFreeEventData(disp, cookie);
if (exitthread)
break;
}
XCloseDisplay(disp);
}
void
xinput2_exit()
{
if (!exitthread) {
exitthread = true;
procThread->wait(5000);
procThread->terminate();
}
}
void
xinput2_init()
{
disp = XOpenDisplay(nullptr);
if (!disp) {
qWarning() << "Cannot open current X11 display";
return;
}
auto event = 0;
auto err = 0;
auto minor = 1;
auto major = 2;
if (XQueryExtension(disp, "XInputExtension", &xi2opcode, &event, &err)) {
if (XIQueryVersion(disp, &major, &minor) == Success) {
procThread = QThread::create(xinput2_proc);
procThread->start();
atexit(xinput2_exit);
}
}
}
``` | /content/code_sandbox/src/qt/xinput2_mouse.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,293 |
```c++
#ifndef QT_STYLEOVERRIDE_HPP
#define QT_STYLEOVERRIDE_HPP
#include <QProxyStyle>
#include <QWidget>
#include <QLayout>
class StyleOverride : public QProxyStyle {
public:
int styleHint(
StyleHint hint,
const QStyleOption *option = nullptr,
const QWidget *widget = nullptr,
QStyleHintReturn *returnData = nullptr) const override;
void polish(QWidget *widget) override;
};
#endif
``` | /content/code_sandbox/src/qt/qt_styleoverride.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 100 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Program settings UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
*
*/
#include "qt_settings.hpp"
#include "ui_qt_settings.h"
#include "qt_settingsmachine.hpp"
#include "qt_settingsdisplay.hpp"
#include "qt_settingsinput.hpp"
#include "qt_settingssound.hpp"
#include "qt_settingsnetwork.hpp"
#include "qt_settingsports.hpp"
#include "qt_settingsstoragecontrollers.hpp"
#include "qt_settingsharddisks.hpp"
#include "qt_settingsfloppycdrom.hpp"
#include "qt_settingsotherremovable.hpp"
#include "qt_settingsotherperipherals.hpp"
#include "qt_progsettings.hpp"
#include "qt_harddrive_common.hpp"
#include "qt_settings_bus_tracking.hpp"
extern "C" {
#include <86box/86box.h>
}
#include <QDebug>
#include <QMessageBox>
#include <QCheckBox>
#include <QApplication>
#include <QStyle>
class SettingsModel : public QAbstractListModel {
public:
SettingsModel(QObject *parent)
: QAbstractListModel(parent)
{
fontHeight = QApplication::fontMetrics().height();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
private:
QStringList pages = {
"Machine",
"Display",
"Input devices",
"Sound",
"Network",
"Ports (COM & LPT)",
"Storage controllers",
"Hard disks",
"Floppy & CD-ROM drives",
"Other removable devices",
"Other peripherals",
};
QStringList page_icons = {
"machine",
"display",
"input_devices",
"sound",
"network",
"ports",
"storage_controllers",
"hard_disk",
"floppy_and_cdrom_drives",
"other_removable_devices",
"other_peripherals",
};
int fontHeight;
};
QVariant
SettingsModel::data(const QModelIndex &index, int role) const
{
Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid | QAbstractItemModel::CheckIndexOption::ParentIsInvalid));
switch (role) {
case Qt::DisplayRole:
return tr(pages.at(index.row()).toUtf8().data());
case Qt::DecorationRole:
return QIcon(QString("%1/%2.ico").arg(ProgSettings::getIconSetPath(), page_icons[index.row()]));
case Qt::SizeHintRole:
return QSize(-1, fontHeight * 2);
default:
return {};
}
}
int
SettingsModel::rowCount(const QModelIndex &parent) const
{
(void) parent;
return pages.size();
}
Settings *Settings::settings = nullptr;
;
Settings::Settings(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Settings)
{
ui->setupUi(this);
auto *model = new SettingsModel(this);
ui->listView->setModel(model);
Harddrives::busTrackClass = new SettingsBusTracking;
machine = new SettingsMachine(this);
display = new SettingsDisplay(this);
input = new SettingsInput(this);
sound = new SettingsSound(this);
network = new SettingsNetwork(this);
ports = new SettingsPorts(this);
storageControllers = new SettingsStorageControllers(this);
harddisks = new SettingsHarddisks(this);
floppyCdrom = new SettingsFloppyCDROM(this);
otherRemovable = new SettingsOtherRemovable(this);
otherPeripherals = new SettingsOtherPeripherals(this);
ui->stackedWidget->addWidget(machine);
ui->stackedWidget->addWidget(display);
ui->stackedWidget->addWidget(input);
ui->stackedWidget->addWidget(sound);
ui->stackedWidget->addWidget(network);
ui->stackedWidget->addWidget(ports);
ui->stackedWidget->addWidget(storageControllers);
ui->stackedWidget->addWidget(harddisks);
ui->stackedWidget->addWidget(floppyCdrom);
ui->stackedWidget->addWidget(otherRemovable);
ui->stackedWidget->addWidget(otherPeripherals);
connect(machine, &SettingsMachine::currentMachineChanged, display,
&SettingsDisplay::onCurrentMachineChanged);
connect(machine, &SettingsMachine::currentMachineChanged, input,
&SettingsInput::onCurrentMachineChanged);
connect(machine, &SettingsMachine::currentMachineChanged, sound,
&SettingsSound::onCurrentMachineChanged);
connect(machine, &SettingsMachine::currentMachineChanged, network,
&SettingsNetwork::onCurrentMachineChanged);
connect(machine, &SettingsMachine::currentMachineChanged, storageControllers,
&SettingsStorageControllers::onCurrentMachineChanged);
connect(machine, &SettingsMachine::currentMachineChanged, otherPeripherals,
&SettingsOtherPeripherals::onCurrentMachineChanged);
connect(floppyCdrom, &SettingsFloppyCDROM::cdromChannelChanged, harddisks,
&SettingsHarddisks::reloadBusChannels);
connect(floppyCdrom, &SettingsFloppyCDROM::cdromChannelChanged, otherRemovable,
&SettingsOtherRemovable::reloadBusChannels_MO);
connect(floppyCdrom, &SettingsFloppyCDROM::cdromChannelChanged, otherRemovable,
&SettingsOtherRemovable::reloadBusChannels_ZIP);
connect(harddisks, &SettingsHarddisks::driveChannelChanged, floppyCdrom,
&SettingsFloppyCDROM::reloadBusChannels);
connect(harddisks, &SettingsHarddisks::driveChannelChanged, otherRemovable,
&SettingsOtherRemovable::reloadBusChannels_MO);
connect(harddisks, &SettingsHarddisks::driveChannelChanged, otherRemovable,
&SettingsOtherRemovable::reloadBusChannels_ZIP);
connect(otherRemovable, &SettingsOtherRemovable::moChannelChanged, harddisks,
&SettingsHarddisks::reloadBusChannels);
connect(otherRemovable, &SettingsOtherRemovable::moChannelChanged, floppyCdrom,
&SettingsFloppyCDROM::reloadBusChannels);
connect(otherRemovable, &SettingsOtherRemovable::moChannelChanged, otherRemovable,
&SettingsOtherRemovable::reloadBusChannels_ZIP);
connect(otherRemovable, &SettingsOtherRemovable::zipChannelChanged, harddisks,
&SettingsHarddisks::reloadBusChannels);
connect(otherRemovable, &SettingsOtherRemovable::zipChannelChanged, floppyCdrom,
&SettingsFloppyCDROM::reloadBusChannels);
connect(otherRemovable, &SettingsOtherRemovable::zipChannelChanged, otherRemovable,
&SettingsOtherRemovable::reloadBusChannels_MO);
connect(ui->listView->selectionModel(), &QItemSelectionModel::currentChanged, this,
[this](const QModelIndex ¤t, const QModelIndex &previous) {
ui->stackedWidget->setCurrentIndex(current.row()); });
ui->listView->setCurrentIndex(model->index(0, 0));
Settings::settings = this;
}
Settings::~Settings()
{
delete ui;
delete Harddrives::busTrackClass;
Harddrives::busTrackClass = nullptr;
Settings::settings = nullptr;
}
void
Settings::save()
{
machine->save();
display->save();
input->save();
sound->save();
network->save();
ports->save();
storageControllers->save();
harddisks->save();
floppyCdrom->save();
otherRemovable->save();
otherPeripherals->save();
}
void
Settings::accept()
{
if (confirm_save && !settings_only) {
QMessageBox questionbox(QMessageBox::Icon::Question, "86Box",
QStringLiteral("%1\n\n%2").arg(tr("Do you want to save the settings?"),
tr("This will hard reset the emulated machine.")),
QMessageBox::Save | QMessageBox::Cancel, this);
QCheckBox *chkbox = new QCheckBox(tr("Don't show this message again"));
questionbox.setCheckBox(chkbox);
chkbox->setChecked(!confirm_save);
QObject::connect(chkbox, &QCheckBox::stateChanged, [](int state) {
confirm_save = (state == Qt::CheckState::Unchecked); });
questionbox.exec();
if (questionbox.result() == QMessageBox::Cancel) {
confirm_save = true;
return;
}
}
QDialog::accept();
}
``` | /content/code_sandbox/src/qt/qt_settings.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,892 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* SDL2 joystick interface.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Joakim L. Gilje <jgilje@jgilje.net>
*
*/
#include <SDL2/SDL.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _USE_MATH_DEFINES
#include <math.h>
/* This #undef is needed because a SDL include header redefines HAVE_STDARG_H. */
#undef HAVE_STDARG_H
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/gameport.h>
#include <86box/plat_unused.h>
int joysticks_present;
joystick_t joystick_state[MAX_JOYSTICKS];
plat_joystick_t plat_joystick_state[MAX_PLAT_JOYSTICKS];
static SDL_Joystick *sdl_joy[MAX_PLAT_JOYSTICKS];
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
void
joystick_init(void)
{
/* This is needed for SDL's Windows raw input backend to work properly without SDL video. */
SDL_SetHint(SDL_HINT_JOYSTICK_THREAD, "1");
if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {
return;
}
joysticks_present = SDL_NumJoysticks();
memset(sdl_joy, 0, sizeof(sdl_joy));
for (int c = 0; c < joysticks_present; c++) {
sdl_joy[c] = SDL_JoystickOpen(c);
if (sdl_joy[c]) {
int d;
strncpy(plat_joystick_state[c].name, SDL_JoystickNameForIndex(c), 64);
plat_joystick_state[c].nr_axes = MIN(SDL_JoystickNumAxes(sdl_joy[c]), MAX_JOY_AXES);
plat_joystick_state[c].nr_buttons = MIN(SDL_JoystickNumButtons(sdl_joy[c]), MAX_JOY_BUTTONS);
plat_joystick_state[c].nr_povs = MIN(SDL_JoystickNumHats(sdl_joy[c]), MAX_JOY_POVS);
for (d = 0; d < plat_joystick_state[c].nr_axes; d++) {
snprintf(plat_joystick_state[c].axis[d].name, sizeof(plat_joystick_state[c].axis[d].name), "Axis %i", d);
plat_joystick_state[c].axis[d].id = d;
}
for (d = 0; d < plat_joystick_state[c].nr_buttons; d++) {
snprintf(plat_joystick_state[c].button[d].name, sizeof(plat_joystick_state[c].button[d].name), "Button %i", d);
plat_joystick_state[c].button[d].id = d;
}
for (d = 0; d < plat_joystick_state[c].nr_povs; d++) {
snprintf(plat_joystick_state[c].pov[d].name, sizeof(plat_joystick_state[c].pov[d].name), "POV %i", d);
plat_joystick_state[c].pov[d].id = d;
}
}
}
}
void
joystick_close(void)
{
int c;
for (c = 0; c < joysticks_present; c++) {
if (sdl_joy[c])
SDL_JoystickClose(sdl_joy[c]);
}
}
static int
joystick_get_axis(int joystick_nr, int mapping)
{
if (mapping & POV_X) {
switch (plat_joystick_state[joystick_nr].p[mapping & 3]) {
case SDL_HAT_LEFTUP:
case SDL_HAT_LEFT:
case SDL_HAT_LEFTDOWN:
return -32767;
case SDL_HAT_RIGHTUP:
case SDL_HAT_RIGHT:
case SDL_HAT_RIGHTDOWN:
return 32767;
default:
return 0;
}
} else if (mapping & POV_Y) {
switch (plat_joystick_state[joystick_nr].p[mapping & 3]) {
case SDL_HAT_LEFTUP:
case SDL_HAT_UP:
case SDL_HAT_RIGHTUP:
return -32767;
case SDL_HAT_LEFTDOWN:
case SDL_HAT_DOWN:
case SDL_HAT_RIGHTDOWN:
return 32767;
default:
return 0;
}
} else
return plat_joystick_state[joystick_nr].a[plat_joystick_state[joystick_nr].axis[mapping].id];
}
void
joystick_process(void)
{
int c;
int d;
if (!joystick_type)
return;
SDL_JoystickUpdate();
for (c = 0; c < joysticks_present; c++) {
int b;
for (b = 0; b < plat_joystick_state[c].nr_axes; b++)
plat_joystick_state[c].a[b] = SDL_JoystickGetAxis(sdl_joy[c], b);
for (b = 0; b < plat_joystick_state[c].nr_buttons; b++)
plat_joystick_state[c].b[b] = SDL_JoystickGetButton(sdl_joy[c], b);
for (b = 0; b < plat_joystick_state[c].nr_povs; b++)
plat_joystick_state[c].p[b] = SDL_JoystickGetHat(sdl_joy[c], b);
// pclog("joystick %i - x=%i y=%i b[0]=%i b[1]=%i %i\n", c, joystick_state[c].x, joystick_state[c].y, joystick_state[c].b[0], joystick_state[c].b[1], joysticks_present);
}
for (c = 0; c < joystick_get_max_joysticks(joystick_type); c++) {
if (joystick_state[c].plat_joystick_nr) {
int joystick_nr = joystick_state[c].plat_joystick_nr - 1;
for (d = 0; d < joystick_get_axis_count(joystick_type); d++)
joystick_state[c].axis[d] = joystick_get_axis(joystick_nr, joystick_state[c].axis_mapping[d]);
for (d = 0; d < joystick_get_button_count(joystick_type); d++)
joystick_state[c].button[d] = plat_joystick_state[joystick_nr].b[joystick_state[c].button_mapping[d]];
for (d = 0; d < joystick_get_pov_count(joystick_type); d++) {
int x, y;
double angle, magnitude;
x = joystick_get_axis(joystick_nr, joystick_state[c].pov_mapping[d][0]);
y = joystick_get_axis(joystick_nr, joystick_state[c].pov_mapping[d][1]);
angle = (atan2((double) y, (double) x) * 360.0) / (2 * M_PI);
magnitude = sqrt((double) x * (double) x + (double) y * (double) y);
if (magnitude < 16384)
joystick_state[c].pov[d] = -1;
else
joystick_state[c].pov[d] = ((int) angle + 90 + 360) % 360;
}
} else {
for (d = 0; d < joystick_get_axis_count(joystick_type); d++)
joystick_state[c].axis[d] = 0;
for (d = 0; d < joystick_get_button_count(joystick_type); d++)
joystick_state[c].button[d] = 0;
for (d = 0; d < joystick_get_pov_count(joystick_type); d++)
joystick_state[c].pov[d] = -1;
}
}
}
#ifdef _WIN32
void
win_joystick_handle(UNUSED(void *raw))
{
/* Nothing to be done here, atleast currently */
}
#endif
``` | /content/code_sandbox/src/qt/sdl_joystick.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,792 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Storage devices configuration UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
*
*/
#include "qt_settingsstoragecontrollers.hpp"
#include "ui_qt_settingsstoragecontrollers.h"
extern "C" {
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/device.h>
#include <86box/machine.h>
#include <86box/hdc.h>
#include <86box/hdc_ide.h>
#include <86box/fdc_ext.h>
#include <86box/cdrom_interface.h>
#include <86box/scsi.h>
#include <86box/scsi_device.h>
#include <86box/cassette.h>
}
#include "qt_deviceconfig.hpp"
#include "qt_models_common.hpp"
SettingsStorageControllers::SettingsStorageControllers(QWidget *parent)
: QWidget(parent)
, ui(new Ui::SettingsStorageControllers)
{
ui->setupUi(this);
onCurrentMachineChanged(machine);
}
SettingsStorageControllers::~SettingsStorageControllers()
{
delete ui;
}
void
SettingsStorageControllers::save()
{
/* Storage devices category */
for (int i = 0; i < SCSI_CARD_MAX; ++i) {
auto *cbox = findChild<QComboBox *>(QString("comboBoxSCSI%1").arg(i + 1));
scsi_card_current[i] = cbox->currentData().toInt();
}
hdc_current[0] = ui->comboBoxHD->currentData().toInt();
fdc_current[0] = ui->comboBoxFD->currentData().toInt();
cdrom_interface_current = ui->comboBoxCDInterface->currentData().toInt();
ide_ter_enabled = ui->checkBoxTertiaryIDE->isChecked() ? 1 : 0;
ide_qua_enabled = ui->checkBoxQuaternaryIDE->isChecked() ? 1 : 0;
cassette_enable = ui->checkBoxCassette->isChecked() ? 1 : 0;
lba_enhancer_enabled = ui->checkBoxLbaEnhancer->isChecked() ? 1 : 0;
}
void
SettingsStorageControllers::onCurrentMachineChanged(int machineId)
{
this->machineId = machineId;
/*HD controller config*/
auto *model = ui->comboBoxHD->model();
auto removeRows = model->rowCount();
int c = 0;
int selectedRow = 0;
while (true) {
/* Skip "internal" if machine doesn't have it. */
if ((c == 1) && (machine_has_flags(machineId, MACHINE_HDC) == 0)) {
c++;
continue;
}
QString name = DeviceConfig::DeviceName(hdc_get_device(c), hdc_get_internal_name(c), 1);
if (name.isEmpty()) {
break;
}
if (hdc_available(c)) {
auto *hdc_dev = hdc_get_device(c);
if (device_is_valid(hdc_dev, machineId)) {
int row = Models::AddEntry(model, name, c);
if (c == hdc_current[0]) {
selectedRow = row - removeRows;
}
}
}
c++;
}
model->removeRows(0, removeRows);
ui->comboBoxHD->setEnabled(model->rowCount() > 0);
ui->comboBoxHD->setCurrentIndex(-1);
ui->comboBoxHD->setCurrentIndex(selectedRow);
/*FD controller config*/
model = ui->comboBoxFD->model();
removeRows = model->rowCount();
c = 0;
selectedRow = 0;
while (true) {
#if 0
/* Skip "internal" if machine doesn't have it. */
if ((c == 1) && (machine_has_flags(machineId, MACHINE_FDC) == 0)) {
c++;
continue;
}
#endif
QString name = DeviceConfig::DeviceName(fdc_card_getdevice(c), fdc_card_get_internal_name(c), 1);
if (name.isEmpty()) {
break;
}
if (fdc_card_available(c)) {
auto *fdc_dev = fdc_card_getdevice(c);
if (device_is_valid(fdc_dev, machineId)) {
int row = Models::AddEntry(model, name, c);
if (c == fdc_current[0]) {
selectedRow = row - removeRows;
}
}
}
c++;
}
model->removeRows(0, removeRows);
ui->comboBoxFD->setEnabled(model->rowCount() > 0);
ui->comboBoxFD->setCurrentIndex(-1);
ui->comboBoxFD->setCurrentIndex(selectedRow);
/*CD interface controller config*/
model = ui->comboBoxCDInterface->model();
removeRows = model->rowCount();
c = 0;
selectedRow = 0;
while (true) {
/* Skip "internal" if machine doesn't have it. */
QString name = DeviceConfig::DeviceName(cdrom_interface_get_device(c), cdrom_interface_get_internal_name(c), 1);
if (name.isEmpty()) {
break;
}
if (cdrom_interface_available(c)) {
auto *cdrom_interface_dev = cdrom_interface_get_device(c);
if (device_is_valid(cdrom_interface_dev, machineId)) {
int row = Models::AddEntry(model, name, c);
if (c == cdrom_interface_current) {
selectedRow = row - removeRows;
}
}
}
c++;
}
model->removeRows(0, removeRows);
ui->comboBoxCDInterface->setEnabled(model->rowCount() > 0);
ui->comboBoxCDInterface->setCurrentIndex(-1);
ui->comboBoxCDInterface->setCurrentIndex(selectedRow);
for (int i = 0; i < SCSI_CARD_MAX; ++i) {
auto *cbox = findChild<QComboBox *>(QString("comboBoxSCSI%1").arg(i + 1));
model = cbox->model();
removeRows = model->rowCount();
c = 0;
selectedRow = 0;
while (true) {
auto name = DeviceConfig::DeviceName(scsi_card_getdevice(c), scsi_card_get_internal_name(c), 1);
if (name.isEmpty()) {
break;
}
if (scsi_card_available(c)) {
auto *scsi_dev = scsi_card_getdevice(c);
if (device_is_valid(scsi_dev, machineId)) {
int row = Models::AddEntry(model, name, c);
if (c == scsi_card_current[i]) {
selectedRow = row - removeRows;
}
}
}
c++;
}
model->removeRows(0, removeRows);
cbox->setEnabled(model->rowCount() > 0);
cbox->setCurrentIndex(-1);
cbox->setCurrentIndex(selectedRow);
}
int is_at = IS_AT(machineId);
ui->checkBoxTertiaryIDE->setEnabled(is_at > 0);
ui->checkBoxQuaternaryIDE->setEnabled(is_at > 0);
ui->checkBoxTertiaryIDE->setChecked(ui->checkBoxTertiaryIDE->isEnabled() && ide_ter_enabled);
ui->checkBoxQuaternaryIDE->setChecked(ui->checkBoxQuaternaryIDE->isEnabled() && ide_qua_enabled);
if (machine_has_bus(machineId, MACHINE_BUS_CASSETTE)) {
ui->checkBoxCassette->setChecked(cassette_enable > 0);
ui->checkBoxCassette->setEnabled(true);
} else {
ui->checkBoxCassette->setChecked(false);
ui->checkBoxCassette->setEnabled(false);
}
ui->checkBoxLbaEnhancer->setChecked(lba_enhancer_enabled > 0 && device_available(&lba_enhancer_device));
ui->pushButtonConfigureLbaEnhancer->setEnabled(ui->checkBoxLbaEnhancer->isChecked());
}
void
SettingsStorageControllers::on_comboBoxHD_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
ui->pushButtonHD->setEnabled(hdc_has_config(ui->comboBoxHD->currentData().toInt()) > 0);
}
void
SettingsStorageControllers::on_comboBoxFD_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
ui->pushButtonFD->setEnabled(hdc_has_config(ui->comboBoxFD->currentData().toInt()) > 0);
}
void SettingsStorageControllers::on_comboBoxCDInterface_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
ui->pushButtonCDInterface->setEnabled(cdrom_interface_has_config(ui->comboBoxCDInterface->currentData().toInt()) > 0);
}
void
SettingsStorageControllers::on_checkBoxTertiaryIDE_stateChanged(int arg1)
{
ui->pushButtonTertiaryIDE->setEnabled(arg1 == Qt::Checked);
}
void
SettingsStorageControllers::on_checkBoxQuaternaryIDE_stateChanged(int arg1)
{
ui->pushButtonQuaternaryIDE->setEnabled(arg1 == Qt::Checked);
}
void
SettingsStorageControllers::on_pushButtonHD_clicked()
{
DeviceConfig::ConfigureDevice(hdc_get_device(ui->comboBoxHD->currentData().toInt()), 0, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsStorageControllers::on_pushButtonFD_clicked()
{
DeviceConfig::ConfigureDevice(fdc_card_getdevice(ui->comboBoxFD->currentData().toInt()), 0, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsStorageControllers::on_pushButtonCDInterface_clicked()
{
DeviceConfig::ConfigureDevice(cdrom_interface_get_device(ui->comboBoxCDInterface->currentData().toInt()), 0, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsStorageControllers::on_pushButtonTertiaryIDE_clicked()
{
DeviceConfig::ConfigureDevice(&ide_ter_device, 0, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsStorageControllers::on_pushButtonQuaternaryIDE_clicked()
{
DeviceConfig::ConfigureDevice(&ide_qua_device, 0, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsStorageControllers::on_comboBoxSCSI1_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
ui->pushButtonSCSI1->setEnabled(scsi_card_has_config(ui->comboBoxSCSI1->currentData().toInt()) > 0);
}
void
SettingsStorageControllers::on_comboBoxSCSI2_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
ui->pushButtonSCSI2->setEnabled(scsi_card_has_config(ui->comboBoxSCSI2->currentData().toInt()) > 0);
}
void
SettingsStorageControllers::on_comboBoxSCSI3_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
ui->pushButtonSCSI3->setEnabled(scsi_card_has_config(ui->comboBoxSCSI3->currentData().toInt()) > 0);
}
void
SettingsStorageControllers::on_comboBoxSCSI4_currentIndexChanged(int index)
{
if (index < 0) {
return;
}
ui->pushButtonSCSI4->setEnabled(scsi_card_has_config(ui->comboBoxSCSI4->currentData().toInt()) > 0);
}
void
SettingsStorageControllers::on_pushButtonSCSI1_clicked()
{
DeviceConfig::ConfigureDevice(scsi_card_getdevice(ui->comboBoxSCSI1->currentData().toInt()), 1, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsStorageControllers::on_pushButtonSCSI2_clicked()
{
DeviceConfig::ConfigureDevice(scsi_card_getdevice(ui->comboBoxSCSI2->currentData().toInt()), 2, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsStorageControllers::on_pushButtonSCSI3_clicked()
{
DeviceConfig::ConfigureDevice(scsi_card_getdevice(ui->comboBoxSCSI3->currentData().toInt()), 3, qobject_cast<Settings *>(Settings::settings));
}
void
SettingsStorageControllers::on_pushButtonSCSI4_clicked()
{
DeviceConfig::ConfigureDevice(scsi_card_getdevice(ui->comboBoxSCSI4->currentData().toInt()), 4, qobject_cast<Settings *>(Settings::settings));
}
void SettingsStorageControllers::on_checkBoxLbaEnhancer_stateChanged(int arg1)
{
ui->pushButtonConfigureLbaEnhancer->setEnabled(arg1 != 0);
}
void SettingsStorageControllers::on_pushButtonConfigureLbaEnhancer_clicked()
{
DeviceConfig::ConfigureDevice(&lba_enhancer_device);
}
``` | /content/code_sandbox/src/qt/qt_settingsstoragecontrollers.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,773 |
```c++
#ifndef QT_SETTINGS_BUS_TRACKING_HPP
#define QT_SETTINGS_BUS_TRACKING_HPP
#include <QWidget>
#define TRACK_CLEAR 0
#define TRACK_SET 1
#define DEV_HDD 0x01
#define DEV_CDROM 0x02
#define DEV_ZIP 0x04
#define DEV_MO 0x08
#define BUS_MFM 0
#define BUS_ESDI 1
#define BUS_XTA 2
#define BUS_IDE 3
#define BUS_SCSI 4
#define CHANNEL_NONE 0xff
namespace Ui {
class SettingsBusTracking;
}
class SettingsBusTracking {
public:
explicit SettingsBusTracking();
~SettingsBusTracking() = default;
QList<int> busChannelsInUse(int bus);
/* These return 0xff is none is free. */
uint8_t next_free_mfm_channel();
uint8_t next_free_esdi_channel();
uint8_t next_free_xta_channel();
uint8_t next_free_ide_channel();
uint8_t next_free_scsi_id();
int mfm_bus_full();
int esdi_bus_full();
int xta_bus_full();
int ide_bus_full();
int scsi_bus_full();
/* Set: 0 = Clear the device from the tracking, 1 = Set the device on the tracking.
Device type: 1 = Hard Disk, 2 = CD-ROM, 4 = ZIP, 8 = Magneto-Optical.
Bus: 0 = MFM, 1 = ESDI, 2 = XTA, 3 = IDE, 4 = SCSI. */
void device_track(int set, uint8_t dev_type, int bus, int channel);
private:
/* 1 channel, 2 devices per channel, 8 bits per device = 16 bits. */
uint64_t mfm_tracking { 0 };
/* 1 channel, 2 devices per channel, 8 bits per device = 16 bits. */
uint64_t esdi_tracking { 0 };
/* 1 channel, 2 devices per channel, 8 bits per device = 16 bits. */
uint64_t xta_tracking { 0 };
/* 16 channels (prepatation for that weird IDE card), 2 devices per channel, 8 bits per device = 256 bits. */
uint64_t ide_tracking[4] { 0, 0, 0, 0 };
/* 9 buses (rounded upwards to 16for future-proofing), 16 devices per bus,
8 bits per device (future-proofing) = 2048 bits. */
uint64_t scsi_tracking[32] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
};
#endif // QT_SETTINGS_BUS_TRACKING_HPP
``` | /content/code_sandbox/src/qt/qt_settings_bus_tracking.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 682 |
```c++
#ifndef QT_SETTINGSINPUT_HPP
#define QT_SETTINGSINPUT_HPP
#include <QWidget>
namespace Ui {
class SettingsInput;
}
class SettingsInput : public QWidget {
Q_OBJECT
public:
explicit SettingsInput(QWidget *parent = nullptr);
~SettingsInput();
void save();
public slots:
void onCurrentMachineChanged(int machineId);
private slots:
void on_pushButtonConfigureMouse_clicked();
void on_comboBoxJoystick_currentIndexChanged(int index);
void on_comboBoxMouse_currentIndexChanged(int index);
void on_pushButtonJoystick1_clicked();
void on_pushButtonJoystick2_clicked();
void on_pushButtonJoystick3_clicked();
void on_pushButtonJoystick4_clicked();
private:
Ui::SettingsInput *ui;
int machineId = 0;
};
#endif // QT_SETTINGSINPUT_HPP
``` | /content/code_sandbox/src/qt/qt_settingsinput.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 167 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Windows raw input native filter for QT
*
*
*
* Authors: Teemu Korhonen
* Miran Grca, <mgrca8@gmail.com>
*
*
* This program is free software; you can redistribute it and/or
* as published by the Free Software Foundation; either version 2
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "qt_winrawinputfilter.hpp"
#include <QMenuBar>
#include <atomic>
#include <windows.h>
#include <86box/keyboard.h>
#include <86box/mouse.h>
#include <86box/plat.h>
#include <86box/86box.h>
#include <array>
#include <memory>
#include "qt_rendererstack.hpp"
extern "C" void win_joystick_handle(PRAWINPUT);
std::unique_ptr<WindowsRawInputFilter>
WindowsRawInputFilter::Register(MainWindow *window)
{
RAWINPUTDEVICE rid[2] = {
{.usUsagePage = 0x01,
.usUsage = 0x06,
.dwFlags = RIDEV_NOHOTKEYS,
.hwndTarget = nullptr},
{ .usUsagePage = 0x01,
.usUsage = 0x02,
.dwFlags = 0,
.hwndTarget = nullptr}
};
if (RegisterRawInputDevices(rid, 2, sizeof(rid[0])) == FALSE)
return std::unique_ptr<WindowsRawInputFilter>(nullptr);
std::unique_ptr<WindowsRawInputFilter> inputfilter(new WindowsRawInputFilter(window));
return inputfilter;
}
WindowsRawInputFilter::WindowsRawInputFilter(MainWindow *window)
{
this->window = window;
for (auto menu : window->findChildren<QMenu *>()) {
connect(menu, &QMenu::aboutToShow, this, [=]() { menus_open++; });
connect(menu, &QMenu::aboutToHide, this, [=]() { menus_open--; });
}
for (size_t i = 0; i < sizeof(scancode_map) / sizeof(scancode_map[0]); i++)
scancode_map[i] = i;
keyboard_getkeymap();
}
WindowsRawInputFilter::~WindowsRawInputFilter()
{
RAWINPUTDEVICE rid[2] = {
{.usUsagePage = 0x01,
.usUsage = 0x06,
.dwFlags = RIDEV_REMOVE,
.hwndTarget = NULL},
{ .usUsagePage = 0x01,
.usUsage = 0x02,
.dwFlags = RIDEV_REMOVE,
.hwndTarget = NULL}
};
RegisterRawInputDevices(rid, 2, sizeof(rid[0]));
}
bool
WindowsRawInputFilter::nativeEventFilter(const QByteArray &eventType, void *message, result_t *result)
{
if (eventType == "windows_generic_MSG") {
MSG *msg = static_cast<MSG *>(message);
if (msg->message == WM_INPUT) {
if (window->isActiveWindow() && menus_open == 0)
handle_input((HRAWINPUT) msg->lParam);
else
{
for (auto &w : window->renderers) {
if (w && w->isActiveWindow()) {
handle_input((HRAWINPUT) msg->lParam);
break;
}
}
}
return true;
}
/* Stop processing of Alt-F4 */
if (msg->message == WM_SYSKEYDOWN) {
if (msg->wParam == 0x73) {
return true;
}
}
}
return false;
}
void
WindowsRawInputFilter::handle_input(HRAWINPUT input)
{
UINT size = 0;
GetRawInputData(input, RID_INPUT, NULL, &size, sizeof(RAWINPUTHEADER));
std::vector<BYTE> buf(size);
if (GetRawInputData(input, RID_INPUT, buf.data(), &size, sizeof(RAWINPUTHEADER)) == size) {
PRAWINPUT raw = (PRAWINPUT) buf.data();
switch (raw->header.dwType) {
case RIM_TYPEKEYBOARD:
keyboard_handle(raw);
break;
case RIM_TYPEMOUSE:
if (mouse_capture)
mouse_handle(raw);
break;
case RIM_TYPEHID:
{
win_joystick_handle(raw);
break;
}
}
}
}
/* The following is more or less a direct copy of the old WIN32 implementation */
void
WindowsRawInputFilter::keyboard_handle(PRAWINPUT raw)
{
USHORT scancode;
RAWKEYBOARD rawKB = raw->data.keyboard;
scancode = rawKB.MakeCode;
/* If it's not a scan code that starts with 0xE1 */
if ((rawKB.Flags & RI_KEY_E1)) {
if (rawKB.MakeCode == 0x1D) {
scancode = scancode_map[0x100]; /* Translate E1 1D to 0x100 (which would
otherwise be E0 00 but that is invalid
anyway).
Also, take a potential mapping into
account. */
} else
scancode = 0xFFFF;
if (scancode != 0xFFFF)
keyboard_input(!(rawKB.Flags & RI_KEY_BREAK), scancode);
} else {
if (rawKB.Flags & RI_KEY_E0)
scancode |= 0x100;
/* Translate the scan code to 9-bit */
scancode = convert_scan_code(scancode);
/* Remap it according to the list from the Registry */
if ((scancode < (sizeof(scancode_map) / sizeof(scancode_map[0]))) && (scancode != scancode_map[scancode])) {
pclog("Scan code remap: %03X -> %03X\n", scancode, scancode_map[scancode]);
scancode = scancode_map[scancode];
}
/* If it's not 0xFFFF, send it to the emulated
keyboard.
We use scan code 0xFFFF to mean a mapping that
has a prefix other than E0 and that is not E1 1D,
which is, for our purposes, invalid. */
/* Translate right CTRL to left ALT if the user has so
chosen. */
if ((scancode == 0x11d) && rctrl_is_lalt)
scancode = 0x038;
/* Normal scan code pass through, pass it through as is if
it's not an invalid scan code. */
if (scancode != 0xFFFF)
keyboard_input(!(rawKB.Flags & RI_KEY_BREAK), scancode);
window->checkFullscreenHotkey();
}
}
/* This is so we can disambiguate scan codes that would otherwise conflict and get
passed on incorrectly. */
UINT16
WindowsRawInputFilter::convert_scan_code(UINT16 scan_code)
{
if ((scan_code & 0xff00) == 0xe000)
scan_code = (scan_code & 0xff) | 0x0100;
if (scan_code == 0xE11D)
scan_code = 0x0100;
/* E0 00 is sent by some USB keyboards for their special keys, as it is an
invalid scan code (it has no untranslated set 2 equivalent), we mark it
appropriately so it does not get passed through. */
else if ((scan_code > 0x01FF) || (scan_code == 0x0100))
scan_code = 0xFFFF;
return scan_code;
}
void
WindowsRawInputFilter::keyboard_getkeymap()
{
const LPCSTR keyName = "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout";
const LPCSTR valueName = "Scancode Map";
unsigned char buf[32768];
DWORD bufSize;
HKEY hKey;
int j;
UINT32 *bufEx2;
int scMapCount;
UINT16 *bufEx;
int scancode_unmapped;
int scancode_mapped;
/* First, prepare the default scan code map list which is 1:1.
* Remappings will be inserted directly into it.
* 512 bytes so this takes less memory, bit 9 set means E0
* prefix.
*/
for (j = 0; j < 512; j++)
scancode_map[j] = j;
/* Get the scan code remappings from:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout */
bufSize = 32768;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, keyName, 0, 1, &hKey) == ERROR_SUCCESS) {
if (RegQueryValueExA(hKey, valueName, NULL, NULL, buf, &bufSize) == ERROR_SUCCESS) {
bufEx2 = (UINT32 *) buf;
scMapCount = bufEx2[2];
if ((bufSize != 0) && (scMapCount != 0)) {
bufEx = (UINT16 *) (buf + 12);
for (j = 0; j < scMapCount * 2; j += 2) {
/* Each scan code is 32-bit: 16 bits of remapped scan code,
and 16 bits of original scan code. */
scancode_unmapped = bufEx[j + 1];
scancode_mapped = bufEx[j];
scancode_unmapped = convert_scan_code(scancode_unmapped);
scancode_mapped = convert_scan_code(scancode_mapped);
/* Ignore source scan codes with prefixes other than E1
that are not E1 1D. */
if (scancode_unmapped != 0xFFFF)
scancode_map[scancode_unmapped] = scancode_mapped;
}
}
}
RegCloseKey(hKey);
}
}
void
WindowsRawInputFilter::mouse_handle(PRAWINPUT raw)
{
RAWMOUSE state = raw->data.mouse;
static int x, delta_x;
static int y, delta_y;
static int b, delta_z;
b = mouse_get_buttons_ex();
/* read mouse buttons and wheel */
if (state.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN)
b |= 1;
else if (state.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP)
b &= ~1;
if (state.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_DOWN)
b |= 4;
else if (state.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_UP)
b &= ~4;
if (state.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN)
b |= 2;
else if (state.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP)
b &= ~2;
if (state.usButtonFlags & RI_MOUSE_BUTTON_4_DOWN)
b |= 8;
else if (state.usButtonFlags & RI_MOUSE_BUTTON_4_UP)
b &= ~8;
if (state.usButtonFlags & RI_MOUSE_BUTTON_5_DOWN)
b |= 16;
else if (state.usButtonFlags & RI_MOUSE_BUTTON_5_UP)
b &= ~16;
mouse_set_buttons_ex(b);
if (state.usButtonFlags & RI_MOUSE_WHEEL) {
delta_z = (SHORT) state.usButtonData / 120;
mouse_set_z(delta_z);
} else
delta_z = 0;
if (state.usFlags & MOUSE_MOVE_ABSOLUTE) {
/* absolute mouse, i.e. RDP or VNC
* seems to work fine for RDP on Windows 10
* Not sure about other environments.
*/
delta_x = (state.lLastX - x) / 25;
delta_y = (state.lLastY - y) / 25;
x = state.lLastX;
y = state.lLastY;
} else {
/* relative mouse, i.e. regular mouse */
delta_x = state.lLastX;
delta_y = state.lLastY;
}
mouse_scale(delta_x, delta_y);
HWND wnd = (HWND)window->winId();
RECT rect;
GetWindowRect(wnd, &rect);
int left = rect.left + (rect.right - rect.left) / 2;
int top = rect.top + (rect.bottom - rect.top) / 2;
SetCursorPos(left, top);
}
``` | /content/code_sandbox/src/qt/qt_winrawinputfilter.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,843 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Wayland mouse input module.
*
*
*
* Authors: Cacodemon345
*
*/
#include "wl_mouse.hpp"
#include <QGuiApplication>
#include <wayland-client-core.h>
#include <wayland-client-protocol.h>
#include <wayland-relative-pointer-unstable-v1-client-protocol.h>
#include <wayland-pointer-constraints-unstable-v1-client-protocol.h>
#include <qpa/qplatformnativeinterface.h>
#include <QWindow>
#include <QGuiApplication>
extern "C" {
#include <86box/mouse.h>
#include <86box/plat.h>
}
static zwp_relative_pointer_manager_v1 *rel_manager = nullptr;
static zwp_relative_pointer_v1 *rel_pointer = nullptr;
static zwp_pointer_constraints_v1 *conf_pointer_interface = nullptr;
static zwp_locked_pointer_v1 *conf_pointer = nullptr;
static bool wl_init_ok = false;
void
rel_mouse_event(void *data, zwp_relative_pointer_v1 *zwp_relative_pointer_v1, uint32_t tstmp, uint32_t tstmpl, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t dx_real, wl_fixed_t dy_real)
{
mouse_scale(wl_fixed_to_int(dx_real), wl_fixed_to_int(dy_real));
}
static struct zwp_relative_pointer_v1_listener rel_listener = {
rel_mouse_event
};
static void
display_handle_global(void *data, struct wl_registry *registry, uint32_t id,
const char *interface, uint32_t version)
{
if (!strcmp(interface, "zwp_relative_pointer_manager_v1")) {
rel_manager = (zwp_relative_pointer_manager_v1 *) wl_registry_bind(registry, id, &zwp_relative_pointer_manager_v1_interface, version);
}
if (!strcmp(interface, "zwp_pointer_constraints_v1")) {
conf_pointer_interface = (zwp_pointer_constraints_v1 *) wl_registry_bind(registry, id, &zwp_pointer_constraints_v1_interface, version);
}
}
static void
display_global_remove(void *data, struct wl_registry *wl_registry, uint32_t name)
{
plat_mouse_capture(0);
zwp_relative_pointer_manager_v1_destroy(rel_manager);
zwp_pointer_constraints_v1_destroy(conf_pointer_interface);
rel_manager = nullptr;
conf_pointer_interface = nullptr;
}
static const struct wl_registry_listener registry_listener = {
display_handle_global,
display_global_remove
};
void
wl_init()
{
if (!wl_init_ok) {
wl_display *display = (wl_display *) QGuiApplication::platformNativeInterface()->nativeResourceForIntegration("wl_display");
if (display) {
auto registry = wl_display_get_registry(display);
if (registry) {
wl_registry_add_listener(registry, ®istry_listener, nullptr);
wl_display_roundtrip(display);
}
}
wl_init_ok = true;
}
}
void
wl_mouse_capture(QWindow *window)
{
if (rel_manager) {
rel_pointer = zwp_relative_pointer_manager_v1_get_relative_pointer(rel_manager, (wl_pointer *) QGuiApplication::platformNativeInterface()->nativeResourceForIntegration("wl_pointer"));
zwp_relative_pointer_v1_add_listener(rel_pointer, &rel_listener, nullptr);
}
if (conf_pointer_interface)
conf_pointer = zwp_pointer_constraints_v1_lock_pointer(conf_pointer_interface, (wl_surface *) QGuiApplication::platformNativeInterface()->nativeResourceForWindow("surface", window), (wl_pointer *) QGuiApplication::platformNativeInterface()->nativeResourceForIntegration("wl_pointer"), nullptr, ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);
}
void
wl_mouse_uncapture()
{
if (conf_pointer)
zwp_locked_pointer_v1_destroy(conf_pointer);
if (rel_pointer)
zwp_relative_pointer_v1_destroy(rel_pointer);
rel_pointer = nullptr;
conf_pointer = nullptr;
}
``` | /content/code_sandbox/src/qt/wl_mouse.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 895 |
```c++
#ifndef VULKANWINDOWRENDERER_HPP
#define VULKANWINDOWRENDERER_HPP
#include <QVulkanWindow>
#if QT_CONFIG(vulkan)
# include "qt_renderercommon.hpp"
# include "qt_vulkanrenderer.hpp"
class VulkanRenderer2;
class VulkanWindowRenderer : public QVulkanWindow, public RendererCommon {
Q_OBJECT
public:
VulkanWindowRenderer(QWidget *parent);
public slots:
void onBlit(int buf_idx, int x, int y, int w, int h);
signals:
void rendererInitialized();
void errorInitializing();
protected:
virtual std::vector<std::tuple<uint8_t *, std::atomic_flag *>> getBuffers() override;
void resizeEvent(QResizeEvent *) override;
bool event(QEvent *) override;
uint32_t getBytesPerRow() override;
private:
QVulkanInstance instance;
QVulkanWindowRenderer *createRenderer() override;
friend class VulkanRendererEmu;
friend class VulkanRenderer2;
VulkanRenderer2 *renderer;
};
#endif
#endif // VULKANWINDOWRENDERER_HPP
``` | /content/code_sandbox/src/qt/qt_vulkanwindowrenderer.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 237 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Try to load a support DLL.
*
*
*
* Authors: Fred N. van Kempen, <decwiz@yahoo.com>
*
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <windows.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/plat_dynld.h>
#ifdef ENABLE_DYNLD_LOG
int dynld_do_log = ENABLE_DYNLD_LOG;
static void
dynld_log(const char *fmt, ...)
{
va_list ap;
if (dynld_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define dynld_log(fmt, ...)
#endif
void *
dynld_module(const char *name, dllimp_t *table)
{
HMODULE h;
dllimp_t *imp;
void *func;
/* See if we can load the desired module. */
if ((h = LoadLibrary(name)) == NULL) {
dynld_log("DynLd(\"%s\"): library not found! (%08X)\n", name, GetLastError());
return (NULL);
}
/* Now load the desired function pointers. */
for (imp = table; imp->name != NULL; imp++) {
func = GetProcAddress(h, imp->name);
if (func == NULL) {
dynld_log("DynLd(\"%s\"): function '%s' not found! (%08X)\n",
name, imp->name, GetLastError());
FreeLibrary(h);
return (NULL);
}
/* To overcome typing issues.. */
*(char **) imp->func = (char *) func;
}
/* All good. */
dynld_log("loaded %s\n", name);
return ((void *) h);
}
void
dynld_close(void *handle)
{
if (handle != NULL)
FreeLibrary((HMODULE) handle);
}
``` | /content/code_sandbox/src/qt/win_dynld.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 507 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* xkbcommon Wayland keyboard input module.
*
* Heavily inspired by libxkbcommon interactive-wayland.c
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
extern "C" {
#include <sys/mman.h>
#include <unistd.h>
#include <xkbcommon/xkbcommon.h>
#include <86box/86box.h>
};
#include "xkbcommon_keyboard.hpp"
#include <wayland-client.h>
#include <wayland-util.h>
#include <qpa/qplatformnativeinterface.h>
#include <QtDebug>
#include <QGuiApplication>
typedef struct {
struct wl_seat *wl_seat;
struct wl_keyboard *wl_kbd;
uint32_t version;
struct xkb_keymap *keymap;
struct wl_list link;
} seat_t;
static bool wl_init_ok = false;
static struct wl_list seats;
static struct xkb_context *ctx;
static void
xkbcommon_wl_set_keymap()
{
/* Grab keymap from the first seat with one. */
seat_t *seat;
seat_t *tmp;
wl_list_for_each_safe(seat, tmp, &seats, link) {
if (seat->keymap) {
xkbcommon_init(seat->keymap);
return;
}
}
xkbcommon_close(); /* none found */
}
static void
kbd_keymap(void *data, struct wl_keyboard *wl_kbd, uint32_t format,
int fd, uint32_t size)
{
seat_t *seat = (seat_t *) data;
char *buf = (char *) mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
if (!buf) {
qWarning() << "XKB Keyboard: Failed to mmap keymap with error" << errno;
return;
}
if (seat->keymap) {
struct xkb_keymap *keymap = seat->keymap;
seat->keymap = NULL;
xkbcommon_wl_set_keymap();
xkb_keymap_unref(keymap);
}
seat->keymap = xkb_keymap_new_from_buffer(ctx, buf, size - 1,
XKB_KEYMAP_FORMAT_TEXT_V1,
XKB_KEYMAP_COMPILE_NO_FLAGS);
munmap(buf, size);
close(fd);
if (!seat->keymap)
qWarning() << "XKB Keyboard: Keymap compilation failed";
xkbcommon_wl_set_keymap();
}
static void
kbd_enter(void *data, struct wl_keyboard *wl_kbd, uint32_t serial,
struct wl_surface *surf, struct wl_array *keys)
{
}
static void
kbd_leave(void *data, struct wl_keyboard *wl_kbd, uint32_t serial,
struct wl_surface *surf)
{
}
static void
kbd_key(void *data, struct wl_keyboard *wl_kbd, uint32_t serial, uint32_t time,
uint32_t key, uint32_t state)
{
}
static void
kbd_modifiers(void *data, struct wl_keyboard *wl_kbd, uint32_t serial,
uint32_t mods_depressed, uint32_t mods_latched,
uint32_t mods_locked, uint32_t group)
{
}
static void
kbd_repeat_info(void *data, struct wl_keyboard *wl_kbd, int32_t rate,
int32_t delay)
{
}
static const struct wl_keyboard_listener kbd_listener = {
kbd_keymap,
kbd_enter,
kbd_leave,
kbd_key,
kbd_modifiers,
kbd_repeat_info
};
static void
seat_capabilities(void *data, struct wl_seat *wl_seat, uint32_t caps)
{
seat_t *seat = (seat_t *) data;
if (!seat->wl_kbd && (caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
seat->wl_kbd = wl_seat_get_keyboard(seat->wl_seat);
wl_keyboard_add_listener(seat->wl_kbd, &kbd_listener, seat);
} else if (seat->wl_kbd && !(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
if (seat->version >= WL_SEAT_RELEASE_SINCE_VERSION)
wl_keyboard_release(seat->wl_kbd);
else
wl_keyboard_destroy(seat->wl_kbd);
struct xkb_keymap *keymap = seat->keymap;
seat->keymap = NULL;
xkbcommon_wl_set_keymap();
xkb_keymap_unref(keymap);
seat->wl_kbd = NULL;
}
}
static void
seat_name(void *data, struct wl_seat *wl_seat, const char *name)
{
}
static const struct wl_seat_listener seat_listener = {
seat_capabilities,
seat_name
};
static void
display_handle_global(void *data, struct wl_registry *wl_registry, uint32_t id,
const char *interface, uint32_t version)
{
if (!strcmp(interface, "wl_seat")) {
seat_t *seat = (seat_t *) malloc(sizeof(seat_t));
memset(seat, 0, sizeof(seat_t));
seat->wl_seat = (wl_seat *) wl_registry_bind(wl_registry, id, &wl_seat_interface, MIN(version, 5));
wl_seat_add_listener(seat->wl_seat, &seat_listener, seat);
wl_list_insert(&seats, &seat->link);
}
}
static void
display_global_remove(void *data, struct wl_registry *wl_registry, uint32_t id)
{
xkbcommon_close();
seat_t *seat;
seat_t *tmp;
wl_list_for_each_safe(seat, tmp, &seats, link) {
if (seat->wl_kbd) {
if (seat->version >= WL_SEAT_RELEASE_SINCE_VERSION)
wl_keyboard_release(seat->wl_kbd);
else
wl_keyboard_destroy(seat->wl_kbd);
xkb_keymap_unref(seat->keymap);
}
if (seat->version >= WL_SEAT_RELEASE_SINCE_VERSION)
wl_seat_release(seat->wl_seat);
else
wl_seat_destroy(seat->wl_seat);
wl_list_remove(&seat->link);
free(seat);
}
}
static const struct wl_registry_listener registry_listener = {
display_handle_global,
display_global_remove
};
void
xkbcommon_wl_init()
{
if (wl_init_ok)
return;
wl_list_init(&seats);
ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
if (!ctx) {
qWarning() << "XKB Keyboard: XKB context creation failed";
return;
}
wl_display *display = (wl_display *) QGuiApplication::platformNativeInterface()->nativeResourceForIntegration("wl_display");
if (display) {
auto registry = wl_display_get_registry(display);
if (registry) {
wl_registry_add_listener(registry, ®istry_listener, nullptr);
wl_display_roundtrip(display);
wl_display_roundtrip(display);
} else {
goto err_ctx;
}
} else {
goto err_ctx;
}
wl_init_ok = true;
return;
err_ctx:
xkb_context_unref(ctx);
}
``` | /content/code_sandbox/src/qt/xkbcommon_wl_keyboard.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,609 |
```c++
#pragma once
/****************************************************************************
**
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
****************************************************************************/
#include <QVulkanWindow>
#include <QImage>
#if QT_CONFIG(vulkan)
# include "qt_vulkanwindowrenderer.hpp"
class VulkanRenderer2 : public QVulkanWindowRenderer {
public:
void *mappedPtr = nullptr;
size_t imagePitch = 2048 * 4;
VulkanRenderer2(QVulkanWindow *w);
void initResources() override;
void initSwapChainResources() override;
void releaseSwapChainResources() override;
void releaseResources() override;
void startNextFrame() override;
private:
VkShaderModule createShader(const QString &name);
bool createTexture();
bool createTextureImage(const QSize &size, VkImage *image, VkDeviceMemory *mem,
VkImageTiling tiling, VkImageUsageFlags usage, uint32_t memIndex);
bool writeLinearImage(const QImage &img, VkImage image, VkDeviceMemory memory);
void ensureTexture();
void updateSamplers();
QVulkanWindow *m_window;
QVulkanDeviceFunctions *m_devFuncs;
VkDeviceMemory m_bufMem = VK_NULL_HANDLE;
VkBuffer m_buf = VK_NULL_HANDLE;
VkDescriptorBufferInfo m_uniformBufInfo[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT];
VkDescriptorPool m_descPool = VK_NULL_HANDLE;
VkDescriptorSetLayout m_descSetLayout = VK_NULL_HANDLE;
VkDescriptorSet m_descSet[QVulkanWindow::MAX_CONCURRENT_FRAME_COUNT];
VkPipelineCache m_pipelineCache = VK_NULL_HANDLE;
VkPipelineLayout m_pipelineLayout = VK_NULL_HANDLE;
VkPipeline m_pipeline = VK_NULL_HANDLE;
VkSampler m_sampler = VK_NULL_HANDLE;
VkSampler m_linearSampler = VK_NULL_HANDLE;
VkImage m_texImage = VK_NULL_HANDLE;
VkDeviceMemory m_texMem = VK_NULL_HANDLE;
bool m_texLayoutPending = false;
VkImageView m_texView = VK_NULL_HANDLE;
VkImage m_texStaging = VK_NULL_HANDLE;
VkDeviceMemory m_texStagingMem = VK_NULL_HANDLE;
bool m_texStagingPending = false;
bool m_texStagingTransferLayout = false;
QSize m_texSize;
VkFormat m_texFormat;
QMatrix4x4 m_proj;
};
#endif
``` | /content/code_sandbox/src/qt/qt_vulkanrenderer.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 834 |
```c++
#ifndef QT_SETTINGS_HPP
#define QT_SETTINGS_HPP
#include <QDialog>
namespace Ui {
class Settings;
}
class SettingsMachine;
class SettingsDisplay;
class SettingsInput;
class SettingsSound;
class SettingsNetwork;
class SettingsPorts;
class SettingsStorageControllers;
class SettingsHarddisks;
class SettingsFloppyCDROM;
class SettingsOtherRemovable;
class SettingsOtherPeripherals;
class Settings : public QDialog {
Q_OBJECT
public:
explicit Settings(QWidget *parent = nullptr);
~Settings();
void save();
static Settings *settings;
protected slots:
void accept() override;
private:
Ui::Settings *ui;
SettingsMachine *machine;
SettingsDisplay *display;
SettingsInput *input;
SettingsSound *sound;
SettingsNetwork *network;
SettingsPorts *ports;
SettingsStorageControllers *storageControllers;
SettingsHarddisks *harddisks;
SettingsFloppyCDROM *floppyCdrom;
SettingsOtherRemovable *otherRemovable;
SettingsOtherPeripherals *otherPeripherals;
};
#endif // QT_SETTINGS_HPP
``` | /content/code_sandbox/src/qt/qt_settings.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 234 |
```c++
/****************************************************************************
**
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
****************************************************************************/
#include <QCoreApplication>
#include <QFile>
#include "qt_vulkanrenderer.hpp"
#if QT_CONFIG(vulkan)
# include <QVulkanFunctions>
extern "C" {
# include <86box/86box.h>
}
// Use a triangle strip to get a quad.
//
// Note that the vertex data and the projection matrix assume OpenGL. With
// Vulkan Y is negated in clip space and the near/far plane is at 0/1 instead
// of -1/1. These will be corrected for by an extra transformation when
// calculating the modelview-projection matrix.
static float vertexData[] = { // Y up, front = CW
// x, y, z, u, v
-1, -1, 0, 0, 1,
-1, 1, 0, 0, 0,
1, -1, 0, 1, 1,
1, 1, 0, 1, 0
};
static const int UNIFORM_DATA_SIZE = 16 * sizeof(float);
static inline VkDeviceSize
aligned(VkDeviceSize v, VkDeviceSize byteAlign)
{
return (v + byteAlign - 1) & ~(byteAlign - 1);
}
VulkanRenderer2::VulkanRenderer2(QVulkanWindow *w)
: m_window(w)
{
}
VkShaderModule
VulkanRenderer2::createShader(const QString &name)
{
QFile file(name);
if (!file.open(QIODevice::ReadOnly)) {
qWarning("Failed to read shader %s", qPrintable(name));
return VK_NULL_HANDLE;
}
QByteArray blob = file.readAll();
file.close();
VkShaderModuleCreateInfo shaderInfo;
memset(&shaderInfo, 0, sizeof(shaderInfo));
shaderInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shaderInfo.codeSize = blob.size();
shaderInfo.pCode = reinterpret_cast<const uint32_t *>(blob.constData());
VkShaderModule shaderModule;
VkResult err = m_devFuncs->vkCreateShaderModule(m_window->device(), &shaderInfo, nullptr, &shaderModule);
if (err != VK_SUCCESS) {
qWarning("Failed to create shader module: %d", err);
return VK_NULL_HANDLE;
}
return shaderModule;
}
bool
VulkanRenderer2::createTexture()
{
QImage img(2048, 2048, QImage::Format_RGBA8888_Premultiplied);
img.fill(QColor(0, 0, 0));
QVulkanFunctions *f = m_window->vulkanInstance()->functions();
VkDevice dev = m_window->device();
m_texFormat = VK_FORMAT_B8G8R8A8_UNORM;
// Now we can either map and copy the image data directly, or have to go
// through a staging buffer to copy and convert into the internal optimal
// tiling format.
VkFormatProperties props;
f->vkGetPhysicalDeviceFormatProperties(m_window->physicalDevice(), m_texFormat, &props);
const bool canSampleLinear = (props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT);
const bool canSampleOptimal = (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT);
if (!canSampleLinear && !canSampleOptimal) {
qWarning("Neither linear nor optimal image sampling is supported for RGBA8");
return false;
}
static bool alwaysStage = qEnvironmentVariableIntValue("QT_VK_FORCE_STAGE_TEX");
if (canSampleLinear && !alwaysStage) {
if (!createTextureImage(img.size(), &m_texImage, &m_texMem,
VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT,
m_window->hostVisibleMemoryIndex()))
return false;
if (!writeLinearImage(img, m_texImage, m_texMem))
return false;
m_texLayoutPending = true;
} else {
if (!createTextureImage(img.size(), &m_texStaging, &m_texStagingMem,
VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
m_window->hostVisibleMemoryIndex()))
return false;
if (!createTextureImage(img.size(), &m_texImage, &m_texMem,
VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
m_window->deviceLocalMemoryIndex()))
return false;
if (!writeLinearImage(img, m_texStaging, m_texStagingMem))
return false;
m_texStagingPending = true;
}
VkImageViewCreateInfo viewInfo;
memset(&viewInfo, 0, sizeof(viewInfo));
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = m_texImage;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = m_texFormat;
viewInfo.components.r = VK_COMPONENT_SWIZZLE_R;
viewInfo.components.g = VK_COMPONENT_SWIZZLE_G;
viewInfo.components.b = VK_COMPONENT_SWIZZLE_B;
viewInfo.components.a = VK_COMPONENT_SWIZZLE_A;
viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
viewInfo.subresourceRange.levelCount = viewInfo.subresourceRange.layerCount = 1;
VkResult err = m_devFuncs->vkCreateImageView(dev, &viewInfo, nullptr, &m_texView);
if (err != VK_SUCCESS) {
qWarning("Failed to create image view for texture: %d", err);
return false;
}
m_texSize = img.size();
return true;
}
bool
VulkanRenderer2::createTextureImage(const QSize &size, VkImage *image, VkDeviceMemory *mem,
VkImageTiling tiling, VkImageUsageFlags usage, uint32_t memIndex)
{
VkDevice dev = m_window->device();
VkImageCreateInfo imageInfo;
memset(&imageInfo, 0, sizeof(imageInfo));
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.format = m_texFormat;
imageInfo.extent.width = size.width();
imageInfo.extent.height = size.height();
imageInfo.extent.depth = 1;
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.tiling = tiling;
imageInfo.usage = usage;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
VkResult err = m_devFuncs->vkCreateImage(dev, &imageInfo, nullptr, image);
if (err != VK_SUCCESS) {
qWarning("Failed to create linear image for texture: %d", err);
return false;
}
VkMemoryRequirements memReq;
m_devFuncs->vkGetImageMemoryRequirements(dev, *image, &memReq);
if (!(memReq.memoryTypeBits & (1 << memIndex))) {
VkPhysicalDeviceMemoryProperties physDevMemProps;
m_window->vulkanInstance()->functions()->vkGetPhysicalDeviceMemoryProperties(m_window->physicalDevice(), &physDevMemProps);
for (uint32_t i = 0; i < physDevMemProps.memoryTypeCount; ++i) {
if (!(memReq.memoryTypeBits & (1 << i)))
continue;
memIndex = i;
}
}
VkMemoryAllocateInfo allocInfo = {
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
nullptr,
memReq.size,
memIndex
};
qDebug("allocating %u bytes for texture image", uint32_t(memReq.size));
err = m_devFuncs->vkAllocateMemory(dev, &allocInfo, nullptr, mem);
if (err != VK_SUCCESS) {
qWarning("Failed to allocate memory for linear image: %d", err);
return false;
}
err = m_devFuncs->vkBindImageMemory(dev, *image, *mem, 0);
if (err != VK_SUCCESS) {
qWarning("Failed to bind linear image memory: %d", err);
return false;
}
return true;
}
bool
VulkanRenderer2::writeLinearImage(const QImage &img, VkImage image, VkDeviceMemory memory)
{
VkDevice dev = m_window->device();
VkImageSubresource subres = {
VK_IMAGE_ASPECT_COLOR_BIT,
0, // mip level
0
};
VkSubresourceLayout layout;
m_devFuncs->vkGetImageSubresourceLayout(dev, image, &subres, &layout);
uchar *p;
VkResult err = m_devFuncs->vkMapMemory(dev, memory, layout.offset, layout.size, 0, reinterpret_cast<void **>(&p));
if (err != VK_SUCCESS) {
qWarning("Failed to map memory for linear image: %d", err);
return false;
}
for (int y = 0; y < img.height(); ++y) {
const uchar *line = img.constScanLine(y);
memcpy(p, line, img.width() * 4);
p += layout.rowPitch;
}
m_devFuncs->vkUnmapMemory(dev, memory);
return true;
}
void
VulkanRenderer2::ensureTexture()
{
if (!m_texLayoutPending && !m_texStagingPending)
return;
Q_ASSERT(m_texLayoutPending != m_texStagingPending);
VkCommandBuffer cb = m_window->currentCommandBuffer();
VkImageMemoryBarrier barrier;
memset(&barrier, 0, sizeof(barrier));
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.levelCount = barrier.subresourceRange.layerCount = 1;
if (m_texLayoutPending) {
m_texLayoutPending = false;
barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.image = m_texImage;
m_devFuncs->vkCmdPipelineBarrier(cb,
VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0, 0, nullptr, 0, nullptr,
1, &barrier);
VkDevice dev = m_window->device();
VkImageSubresource subres = {
VK_IMAGE_ASPECT_COLOR_BIT,
0, // mip level
0
};
VkSubresourceLayout layout;
m_devFuncs->vkGetImageSubresourceLayout(dev, m_texImage, &subres, &layout);
VkResult err = m_devFuncs->vkMapMemory(dev, m_texMem, layout.offset, layout.size, 0, reinterpret_cast<void **>(&mappedPtr));
if (err != VK_SUCCESS) {
qWarning("Failed to map memory for linear image: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
imagePitch = layout.rowPitch;
if (qobject_cast<VulkanWindowRenderer *>(m_window)) {
emit qobject_cast<VulkanWindowRenderer *>(m_window)->rendererInitialized();
}
} else {
m_texStagingPending = false;
if (!m_texStagingTransferLayout) {
barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barrier.image = m_texStaging;
m_devFuncs->vkCmdPipelineBarrier(cb,
VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, nullptr, 0, nullptr,
1, &barrier);
barrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.image = m_texImage;
m_devFuncs->vkCmdPipelineBarrier(cb,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, nullptr, 0, nullptr,
1, &barrier);
VkDevice dev = m_window->device();
VkImageSubresource subres = {
VK_IMAGE_ASPECT_COLOR_BIT,
0, // mip level
0
};
VkSubresourceLayout layout;
m_devFuncs->vkGetImageSubresourceLayout(dev, m_texStaging, &subres, &layout);
VkResult err = m_devFuncs->vkMapMemory(dev, m_texStagingMem, layout.offset, layout.size, 0, reinterpret_cast<void **>(&mappedPtr));
if (err != VK_SUCCESS) {
qWarning("Failed to map memory for linear image: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
imagePitch = layout.rowPitch;
if (qobject_cast<VulkanWindowRenderer *>(m_window)) {
emit qobject_cast<VulkanWindowRenderer *>(m_window)->rendererInitialized();
}
m_texStagingTransferLayout = true;
}
VkImageCopy copyInfo;
memset(©Info, 0, sizeof(copyInfo));
copyInfo.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyInfo.srcSubresource.layerCount = 1;
copyInfo.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyInfo.dstSubresource.layerCount = 1;
copyInfo.extent.width = m_texSize.width();
copyInfo.extent.height = m_texSize.height();
copyInfo.extent.depth = 1;
m_devFuncs->vkCmdCopyImage(cb, m_texStaging, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
m_texImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Info);
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.image = m_texImage;
m_devFuncs->vkCmdPipelineBarrier(cb,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0, 0, nullptr, 0, nullptr,
1, &barrier);
}
}
void
VulkanRenderer2::updateSamplers()
{
static int cur_video_filter_method = -1;
if (cur_video_filter_method != video_filter_method) {
cur_video_filter_method = video_filter_method;
m_devFuncs->vkDeviceWaitIdle(m_window->device());
VkDescriptorImageInfo descImageInfo = {
cur_video_filter_method == 1 ? m_linearSampler : m_sampler,
m_texView,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
};
for (int i = 0; i < m_window->concurrentFrameCount(); i++) {
VkWriteDescriptorSet descWrite[2];
memset(descWrite, 0, sizeof(descWrite));
descWrite[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descWrite[0].dstSet = m_descSet[i];
descWrite[0].dstBinding = 0;
descWrite[0].descriptorCount = 1;
descWrite[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descWrite[0].pBufferInfo = &m_uniformBufInfo[i];
descWrite[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descWrite[1].dstSet = m_descSet[i];
descWrite[1].dstBinding = 1;
descWrite[1].descriptorCount = 1;
descWrite[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descWrite[1].pImageInfo = &descImageInfo;
m_devFuncs->vkUpdateDescriptorSets(m_window->device(), 2, descWrite, 0, nullptr);
}
}
}
void
VulkanRenderer2::initResources()
{
qDebug("initResources");
VkDevice dev = m_window->device();
m_devFuncs = m_window->vulkanInstance()->deviceFunctions(dev);
// The setup is similar to hellovulkantriangle. The difference is the
// presence of a second vertex attribute (texcoord), a sampler, and that we
// need blending.
const int concurrentFrameCount = m_window->concurrentFrameCount();
const VkPhysicalDeviceLimits *pdevLimits = &m_window->physicalDeviceProperties()->limits;
const VkDeviceSize uniAlign = pdevLimits->minUniformBufferOffsetAlignment;
qDebug("uniform buffer offset alignment is %u", (uint) uniAlign);
VkBufferCreateInfo bufInfo;
memset(&bufInfo, 0, sizeof(bufInfo));
bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
// Our internal layout is vertex, uniform, uniform, ... with each uniform buffer start offset aligned to uniAlign.
const VkDeviceSize vertexAllocSize = aligned(sizeof(vertexData), uniAlign);
const VkDeviceSize uniformAllocSize = aligned(UNIFORM_DATA_SIZE, uniAlign);
bufInfo.size = vertexAllocSize + concurrentFrameCount * uniformAllocSize;
bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
VkResult err = m_devFuncs->vkCreateBuffer(dev, &bufInfo, nullptr, &m_buf);
if (err != VK_SUCCESS) {
qWarning("Failed to create buffer: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
VkMemoryRequirements memReq;
m_devFuncs->vkGetBufferMemoryRequirements(dev, m_buf, &memReq);
VkMemoryAllocateInfo memAllocInfo = {
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
nullptr,
memReq.size,
m_window->hostVisibleMemoryIndex()
};
err = m_devFuncs->vkAllocateMemory(dev, &memAllocInfo, nullptr, &m_bufMem);
if (err != VK_SUCCESS) {
qWarning("Failed to allocate memory: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
err = m_devFuncs->vkBindBufferMemory(dev, m_buf, m_bufMem, 0);
if (err != VK_SUCCESS) {
qWarning("Failed to bind buffer memory: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
quint8 *p;
err = m_devFuncs->vkMapMemory(dev, m_bufMem, 0, memReq.size, 0, reinterpret_cast<void **>(&p));
if (err != VK_SUCCESS) {
qWarning("Failed to map memory: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
memcpy(p, vertexData, sizeof(vertexData));
QMatrix4x4 ident;
memset(m_uniformBufInfo, 0, sizeof(m_uniformBufInfo));
for (int i = 0; i < concurrentFrameCount; ++i) {
const VkDeviceSize offset = vertexAllocSize + i * uniformAllocSize;
memcpy(p + offset, ident.constData(), 16 * sizeof(float));
m_uniformBufInfo[i].buffer = m_buf;
m_uniformBufInfo[i].offset = offset;
m_uniformBufInfo[i].range = uniformAllocSize;
}
m_devFuncs->vkUnmapMemory(dev, m_bufMem);
VkVertexInputBindingDescription vertexBindingDesc = {
0, // binding
5 * sizeof(float),
VK_VERTEX_INPUT_RATE_VERTEX
};
VkVertexInputAttributeDescription vertexAttrDesc[] = {
{// position
0, // location
0, // binding
VK_FORMAT_R32G32B32_SFLOAT,
0 },
{ // texcoord
1,
0,
VK_FORMAT_R32G32_SFLOAT,
3 * sizeof(float)}
};
VkPipelineVertexInputStateCreateInfo vertexInputInfo;
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.pNext = nullptr;
vertexInputInfo.flags = 0;
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.pVertexBindingDescriptions = &vertexBindingDesc;
vertexInputInfo.vertexAttributeDescriptionCount = 2;
vertexInputInfo.pVertexAttributeDescriptions = vertexAttrDesc;
// Sampler.
VkSamplerCreateInfo samplerInfo;
memset(&samplerInfo, 0, sizeof(samplerInfo));
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_NEAREST;
samplerInfo.minFilter = VK_FILTER_NEAREST;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.maxAnisotropy = 1.0f;
samplerInfo.maxLod = 0.25;
err = m_devFuncs->vkCreateSampler(dev, &samplerInfo, nullptr, &m_sampler);
if (err != VK_SUCCESS) {
qWarning("Failed to create sampler: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
err = m_devFuncs->vkCreateSampler(dev, &samplerInfo, nullptr, &m_linearSampler);
if (err != VK_SUCCESS) {
qWarning("Failed to create sampler: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
// Texture.
if (!createTexture()) {
qWarning("Failed to create texture");
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
// Set up descriptor set and its layout.
VkDescriptorPoolSize descPoolSizes[2] = {
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, uint32_t(concurrentFrameCount)},
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, uint32_t(concurrentFrameCount)}
};
VkDescriptorPoolCreateInfo descPoolInfo;
memset(&descPoolInfo, 0, sizeof(descPoolInfo));
descPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
descPoolInfo.maxSets = concurrentFrameCount;
descPoolInfo.poolSizeCount = 2;
descPoolInfo.pPoolSizes = descPoolSizes;
err = m_devFuncs->vkCreateDescriptorPool(dev, &descPoolInfo, nullptr, &m_descPool);
if (err != VK_SUCCESS) {
qWarning("Failed to create descriptor pool: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
VkDescriptorSetLayoutBinding layoutBinding[2] = {
{0, // binding
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1, // descriptorCount
VK_SHADER_STAGE_VERTEX_BIT,
nullptr},
{ 1, // binding
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1, // descriptorCount
VK_SHADER_STAGE_FRAGMENT_BIT,
nullptr}
};
VkDescriptorSetLayoutCreateInfo descLayoutInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
nullptr,
0,
2, // bindingCount
layoutBinding
};
err = m_devFuncs->vkCreateDescriptorSetLayout(dev, &descLayoutInfo, nullptr, &m_descSetLayout);
if (err != VK_SUCCESS) {
qWarning("Failed to create descriptor set layout: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
for (int i = 0; i < concurrentFrameCount; ++i) {
VkDescriptorSetAllocateInfo descSetAllocInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
nullptr,
m_descPool,
1,
&m_descSetLayout
};
err = m_devFuncs->vkAllocateDescriptorSets(dev, &descSetAllocInfo, &m_descSet[i]);
if (err != VK_SUCCESS) {
qWarning("Failed to allocate descriptor set: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
VkWriteDescriptorSet descWrite[2];
memset(descWrite, 0, sizeof(descWrite));
descWrite[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descWrite[0].dstSet = m_descSet[i];
descWrite[0].dstBinding = 0;
descWrite[0].descriptorCount = 1;
descWrite[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descWrite[0].pBufferInfo = &m_uniformBufInfo[i];
VkDescriptorImageInfo descImageInfo = {
video_filter_method == 1 ? m_linearSampler : m_sampler,
m_texView,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
};
descWrite[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descWrite[1].dstSet = m_descSet[i];
descWrite[1].dstBinding = 1;
descWrite[1].descriptorCount = 1;
descWrite[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descWrite[1].pImageInfo = &descImageInfo;
m_devFuncs->vkUpdateDescriptorSets(dev, 2, descWrite, 0, nullptr);
}
// Pipeline cache
VkPipelineCacheCreateInfo pipelineCacheInfo;
memset(&pipelineCacheInfo, 0, sizeof(pipelineCacheInfo));
pipelineCacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
err = m_devFuncs->vkCreatePipelineCache(dev, &pipelineCacheInfo, nullptr, &m_pipelineCache);
if (err != VK_SUCCESS) {
qWarning("Failed to create pipeline cache: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
// Pipeline layout
VkPipelineLayoutCreateInfo pipelineLayoutInfo;
memset(&pipelineLayoutInfo, 0, sizeof(pipelineLayoutInfo));
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &m_descSetLayout;
err = m_devFuncs->vkCreatePipelineLayout(dev, &pipelineLayoutInfo, nullptr, &m_pipelineLayout);
if (err != VK_SUCCESS) {
qWarning("Failed to create pipeline layout: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
// Shaders
#if 0
#version 440
layout(location = 0) in vec4 position;
layout(location = 1) in vec2 texcoord;
layout(location = 0) out vec2 v_texcoord;
layout(std140, binding = 0) uniform buf {
mat4 mvp;
} ubuf;
out gl_PerVertex { vec4 gl_Position; };
void main()
{
v_texcoord = texcoord;
gl_Position = ubuf.mvp * position;
}
#endif
VkShaderModule vertShaderModule = createShader(QStringLiteral(":/texture_vert.spv"));
#if 0
#version 440
layout(location = 0) in vec2 v_texcoord;
layout(location = 0) out vec4 fragColor;
layout(binding = 1) uniform sampler2D tex;
void main()
{
fragColor = texture(tex, v_texcoord);
}
#endif
VkShaderModule fragShaderModule = createShader(QStringLiteral(":/texture_frag.spv"));
// Graphics pipeline
VkGraphicsPipelineCreateInfo pipelineInfo;
memset(&pipelineInfo, 0, sizeof(pipelineInfo));
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
VkPipelineShaderStageCreateInfo shaderStages[2] = {
{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
nullptr,
0,
VK_SHADER_STAGE_VERTEX_BIT,
vertShaderModule,
"main",
nullptr
},
{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
nullptr,
0,
VK_SHADER_STAGE_FRAGMENT_BIT,
fragShaderModule,
"main",
nullptr
}
};
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages;
pipelineInfo.pVertexInputState = &vertexInputInfo;
VkPipelineInputAssemblyStateCreateInfo ia;
memset(&ia, 0, sizeof(ia));
ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
pipelineInfo.pInputAssemblyState = &ia;
// The viewport and scissor will be set dynamically via vkCmdSetViewport/Scissor.
// This way the pipeline does not need to be touched when resizing the window.
VkPipelineViewportStateCreateInfo vp;
memset(&vp, 0, sizeof(vp));
vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
vp.viewportCount = 1;
vp.scissorCount = 1;
pipelineInfo.pViewportState = &vp;
VkPipelineRasterizationStateCreateInfo rs;
memset(&rs, 0, sizeof(rs));
rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rs.polygonMode = VK_POLYGON_MODE_FILL;
rs.cullMode = VK_CULL_MODE_BACK_BIT;
rs.frontFace = VK_FRONT_FACE_CLOCKWISE;
rs.lineWidth = 1.0f;
pipelineInfo.pRasterizationState = &rs;
VkPipelineMultisampleStateCreateInfo ms;
memset(&ms, 0, sizeof(ms));
ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
pipelineInfo.pMultisampleState = &ms;
VkPipelineDepthStencilStateCreateInfo ds;
memset(&ds, 0, sizeof(ds));
ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
ds.depthTestEnable = VK_TRUE;
ds.depthWriteEnable = VK_TRUE;
ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
pipelineInfo.pDepthStencilState = &ds;
VkPipelineColorBlendStateCreateInfo cb;
memset(&cb, 0, sizeof(cb));
cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
// assume pre-multiplied alpha, blend, write out all of rgba
VkPipelineColorBlendAttachmentState att;
memset(&att, 0, sizeof(att));
att.colorWriteMask = 0xF;
att.blendEnable = VK_TRUE;
att.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
att.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
att.colorBlendOp = VK_BLEND_OP_ADD;
att.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
att.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
att.alphaBlendOp = VK_BLEND_OP_ADD;
cb.attachmentCount = 1;
cb.pAttachments = &att;
pipelineInfo.pColorBlendState = &cb;
VkDynamicState dynEnable[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dyn;
memset(&dyn, 0, sizeof(dyn));
dyn.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dyn.dynamicStateCount = sizeof(dynEnable) / sizeof(VkDynamicState);
dyn.pDynamicStates = dynEnable;
pipelineInfo.pDynamicState = &dyn;
pipelineInfo.layout = m_pipelineLayout;
pipelineInfo.renderPass = m_window->defaultRenderPass();
err = m_devFuncs->vkCreateGraphicsPipelines(dev, m_pipelineCache, 1, &pipelineInfo, nullptr, &m_pipeline);
if (err != VK_SUCCESS) {
qWarning("Failed to create graphics pipeline: %d", err);
return emit qobject_cast<VulkanWindowRenderer *>(m_window)->errorInitializing();
}
if (vertShaderModule)
m_devFuncs->vkDestroyShaderModule(dev, vertShaderModule, nullptr);
if (fragShaderModule)
m_devFuncs->vkDestroyShaderModule(dev, fragShaderModule, nullptr);
pclog("Vulkan device: %s\n", m_window->physicalDeviceProperties()->deviceName);
pclog("Vulkan API version: %d.%d.%d\n", VK_VERSION_MAJOR(m_window->physicalDeviceProperties()->apiVersion), VK_VERSION_MINOR(m_window->physicalDeviceProperties()->apiVersion), VK_VERSION_PATCH(m_window->physicalDeviceProperties()->apiVersion));
pclog("Vulkan driver version: %d.%d.%d\n", VK_VERSION_MAJOR(m_window->physicalDeviceProperties()->driverVersion), VK_VERSION_MINOR(m_window->physicalDeviceProperties()->driverVersion), VK_VERSION_PATCH(m_window->physicalDeviceProperties()->driverVersion));
}
void
VulkanRenderer2::initSwapChainResources()
{
qDebug("initSwapChainResources");
// Projection matrix
m_proj = m_window->clipCorrectionMatrix(); // adjust for Vulkan-OpenGL clip space differences
}
void
VulkanRenderer2::releaseSwapChainResources()
{
qDebug("releaseSwapChainResources");
}
void
VulkanRenderer2::releaseResources()
{
qDebug("releaseResources");
VkDevice dev = m_window->device();
if (m_sampler) {
m_devFuncs->vkDestroySampler(dev, m_sampler, nullptr);
m_sampler = VK_NULL_HANDLE;
}
if (m_linearSampler) {
m_devFuncs->vkDestroySampler(dev, m_linearSampler, nullptr);
m_linearSampler = VK_NULL_HANDLE;
}
if (m_texStaging) {
m_devFuncs->vkDestroyImage(dev, m_texStaging, nullptr);
m_texStaging = VK_NULL_HANDLE;
}
if (m_texStagingMem) {
m_devFuncs->vkFreeMemory(dev, m_texStagingMem, nullptr);
m_texStagingMem = VK_NULL_HANDLE;
}
if (m_texView) {
m_devFuncs->vkDestroyImageView(dev, m_texView, nullptr);
m_texView = VK_NULL_HANDLE;
}
if (m_texImage) {
m_devFuncs->vkDestroyImage(dev, m_texImage, nullptr);
m_texImage = VK_NULL_HANDLE;
}
if (m_texMem) {
m_devFuncs->vkFreeMemory(dev, m_texMem, nullptr);
m_texMem = VK_NULL_HANDLE;
}
if (m_pipeline) {
m_devFuncs->vkDestroyPipeline(dev, m_pipeline, nullptr);
m_pipeline = VK_NULL_HANDLE;
}
if (m_pipelineLayout) {
m_devFuncs->vkDestroyPipelineLayout(dev, m_pipelineLayout, nullptr);
m_pipelineLayout = VK_NULL_HANDLE;
}
if (m_pipelineCache) {
m_devFuncs->vkDestroyPipelineCache(dev, m_pipelineCache, nullptr);
m_pipelineCache = VK_NULL_HANDLE;
}
if (m_descSetLayout) {
m_devFuncs->vkDestroyDescriptorSetLayout(dev, m_descSetLayout, nullptr);
m_descSetLayout = VK_NULL_HANDLE;
}
if (m_descPool) {
m_devFuncs->vkDestroyDescriptorPool(dev, m_descPool, nullptr);
m_descPool = VK_NULL_HANDLE;
}
if (m_buf) {
m_devFuncs->vkDestroyBuffer(dev, m_buf, nullptr);
m_buf = VK_NULL_HANDLE;
}
if (m_bufMem) {
m_devFuncs->vkFreeMemory(dev, m_bufMem, nullptr);
m_bufMem = VK_NULL_HANDLE;
}
}
void
VulkanRenderer2::startNextFrame()
{
VkDevice dev = m_window->device();
VkCommandBuffer cb = m_window->currentCommandBuffer();
const QSize sz = m_window->swapChainImageSize();
updateSamplers();
// Add the necessary barriers and do the host-linear -> device-optimal copy, if not yet done.
ensureTexture();
VkClearColorValue clearColor = {
{0, 0, 0, 1}
};
VkClearDepthStencilValue clearDS = { 1, 0 };
VkClearValue clearValues[2];
memset(clearValues, 0, sizeof(clearValues));
clearValues[0].color = clearColor;
clearValues[1].depthStencil = clearDS;
VkRenderPassBeginInfo rpBeginInfo;
memset(&rpBeginInfo, 0, sizeof(rpBeginInfo));
rpBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
rpBeginInfo.renderPass = m_window->defaultRenderPass();
rpBeginInfo.framebuffer = m_window->currentFramebuffer();
rpBeginInfo.renderArea.extent.width = sz.width();
rpBeginInfo.renderArea.extent.height = sz.height();
rpBeginInfo.clearValueCount = 2;
rpBeginInfo.pClearValues = clearValues;
VkCommandBuffer cmdBuf = m_window->currentCommandBuffer();
m_devFuncs->vkCmdBeginRenderPass(cmdBuf, &rpBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
quint8 *p;
VkResult err = m_devFuncs->vkMapMemory(dev, m_bufMem, m_uniformBufInfo[m_window->currentFrame()].offset,
UNIFORM_DATA_SIZE, 0, reinterpret_cast<void **>(&p));
if (err != VK_SUCCESS)
qFatal("Failed to map memory: %d", err);
QMatrix4x4 m = m_proj;
memcpy(p, m.constData(), 16 * sizeof(float));
m_devFuncs->vkUnmapMemory(dev, m_bufMem);
p = nullptr;
// Second pass for texture coordinates.
err = m_devFuncs->vkMapMemory(dev, m_bufMem, 0,
sizeof(vertexData), 0, reinterpret_cast<void **>(&p));
if (err != VK_SUCCESS)
qFatal("Failed to map memory: %d", err);
float *floatData = (float *) p;
auto source = qobject_cast<VulkanWindowRenderer *>(m_window)->source;
auto destination = qobject_cast<VulkanWindowRenderer *>(m_window)->destination;
floatData[3] = (float) source.x() / 2048.f;
floatData[9] = (float) (source.y()) / 2048.f;
floatData[8] = (float) source.x() / 2048.f;
floatData[4] = (float) (source.y() + source.height()) / 2048.f;
floatData[13] = (float) (source.x() + source.width()) / 2048.f;
floatData[19] = (float) (source.y()) / 2048.f;
floatData[18] = (float) (source.x() + source.width()) / 2048.f;
floatData[14] = (float) (source.y() + source.height()) / 2048.f;
m_devFuncs->vkUnmapMemory(dev, m_bufMem);
m_devFuncs->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline);
m_devFuncs->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1,
&m_descSet[m_window->currentFrame()], 0, nullptr);
VkDeviceSize vbOffset = 0;
m_devFuncs->vkCmdBindVertexBuffers(cb, 0, 1, &m_buf, &vbOffset);
VkViewport viewport;
viewport.x = destination.x() * m_window->devicePixelRatio();
viewport.y = destination.y() * m_window->devicePixelRatio();
viewport.width = destination.width() * m_window->devicePixelRatio();
viewport.height = destination.height() * m_window->devicePixelRatio();
viewport.minDepth = 0;
viewport.maxDepth = 1;
m_devFuncs->vkCmdSetViewport(cb, 0, 1, &viewport);
VkRect2D scissor;
scissor.offset.x = viewport.x;
scissor.offset.y = viewport.y;
scissor.extent.width = viewport.width;
scissor.extent.height = viewport.height;
m_devFuncs->vkCmdSetScissor(cb, 0, 1, &scissor);
m_devFuncs->vkCmdDraw(cb, 4, 1, 0, 0);
m_devFuncs->vkCmdEndRenderPass(cmdBuf);
if (m_texStagingTransferLayout) {
VkImageMemoryBarrier barrier {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.levelCount = barrier.subresourceRange.layerCount = 1;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.image = m_texImage;
m_devFuncs->vkCmdPipelineBarrier(cb,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, nullptr, 0, nullptr,
1, &barrier);
m_texStagingPending = true;
}
m_window->frameReady();
m_window->requestUpdate(); // render continuously, throttled by the presentation rate
}
#endif
``` | /content/code_sandbox/src/qt/qt_vulkanrenderer.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 9,569 |
```c++
#ifdef EVDEV_INPUT
void evdev_init();
#endif
``` | /content/code_sandbox/src/qt/evdev_mouse.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 13 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Main window module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
* Teemu Korhonen
* dob205
*
*/
#include <QDebug>
#include "qt_mainwindow.hpp"
#include "ui_qt_mainwindow.h"
#include "qt_specifydimensions.h"
#include "qt_soundgain.hpp"
#include "qt_progsettings.hpp"
#include "qt_mcadevicelist.hpp"
#include "qt_rendererstack.hpp"
#include "qt_renderercommon.hpp"
extern "C" {
#include <86box/86box.h>
#include <86box/config.h>
#include <86box/keyboard.h>
#include <86box/plat.h>
#include <86box/ui.h>
#ifdef DISCORD
# include <86box/discord.h>
#endif
#include <86box/device.h>
#include <86box/video.h>
#include <86box/mouse.h>
#include <86box/machine.h>
#include <86box/vid_ega.h>
#include <86box/version.h>
#if 0
#include <86box/acpi.h> /* Requires timer.h include, which conflicts with Qt headers */
#endif
extern atomic_int acpi_pwrbut_pressed;
extern int acpi_enabled;
#ifdef USE_VNC
# include <86box/vnc.h>
#endif
extern int qt_nvr_save(void);
#ifdef MTR_ENABLED
# include <minitrace/minitrace.h>
#endif
};
#include <QGuiApplication>
#include <QWindow>
#include <QTimer>
#include <QThread>
#include <QKeyEvent>
#include <QShortcut>
#include <QMessageBox>
#include <QFocusEvent>
#include <QApplication>
#include <QPushButton>
#include <QDesktopServices>
#include <QUrl>
#include <QMenuBar>
#include <QCheckBox>
#include <QActionGroup>
#include <QOpenGLContext>
#include <QScreen>
#include <QString>
#include <QDir>
#include <QSysInfo>
#if QT_CONFIG(vulkan)
# include <QVulkanInstance>
# include <QVulkanFunctions>
#endif
#include <array>
#include <memory>
#include <unordered_map>
#include "qt_settings.hpp"
#include "qt_machinestatus.hpp"
#include "qt_mediamenu.hpp"
#include "qt_util.hpp"
#if defined __unix__ && !defined __HAIKU__
# ifndef Q_OS_MACOS
# include "evdev_keyboard.hpp"
# endif
# ifdef XKBCOMMON
# include "xkbcommon_keyboard.hpp"
# ifdef XKBCOMMON_X11
# include "xkbcommon_x11_keyboard.hpp"
# endif
# ifdef WAYLAND
# include "xkbcommon_wl_keyboard.hpp"
# endif
# endif
# include <X11/Xlib.h>
# include <X11/keysym.h>
# undef KeyPress
# undef KeyRelease
#endif
#if defined Q_OS_UNIX && !defined Q_OS_HAIKU && !defined Q_OS_MACOS
#include <qpa/qplatformwindow.h>
#include "x11_util.h"
#endif
#ifdef Q_OS_MACOS
# include "cocoa_keyboard.hpp"
// The namespace is required to avoid clashing typedefs; we only use this
// header for its #defines anyway.
namespace IOKit {
# include <IOKit/hidsystem/IOLLEvent.h>
}
#endif
#ifdef __HAIKU__
# include <os/AppKit.h>
# include <os/InterfaceKit.h>
# include "be_keyboard.hpp"
extern MainWindow *main_window;
filter_result
keyb_filter(BMessage *message, BHandler **target, BMessageFilter *filter)
{
if (message->what == B_KEY_DOWN || message->what == B_KEY_UP
|| message->what == B_UNMAPPED_KEY_DOWN || message->what == B_UNMAPPED_KEY_UP) {
int key_state = 0, key_scancode = 0;
key_state = message->what == B_KEY_DOWN || message->what == B_UNMAPPED_KEY_DOWN;
message->FindInt32("key", &key_scancode);
QGuiApplication::postEvent(main_window, new QKeyEvent(key_state ? QEvent::KeyPress : QEvent::KeyRelease, 0, QGuiApplication::keyboardModifiers(), key_scancode, 0, 0));
if (key_scancode == 0x68 && key_state) {
QGuiApplication::postEvent(main_window, new QKeyEvent(QEvent::KeyRelease, 0, QGuiApplication::keyboardModifiers(), key_scancode, 0, 0));
}
}
return B_DISPATCH_MESSAGE;
}
static BMessageFilter *filter;
#endif
extern void qt_mouse_capture(int);
extern "C" void qt_blit(int x, int y, int w, int h, int monitor_index);
extern MainWindow *main_window;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
mm = std::make_shared<MediaMenu>(this);
MediaMenu::ptr = mm;
status = std::make_unique<MachineStatus>(this);
#ifdef __HAIKU__
filter = new BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE, keyb_filter);
((BWindow *) this->winId())->AddFilter(filter);
#endif
setUnifiedTitleAndToolBarOnMac(true);
extern MainWindow *main_window;
main_window = this;
ui->setupUi(this);
ui->stackedWidget->setMouseTracking(true);
statusBar()->setVisible(!hide_status_bar);
statusBar()->setStyleSheet("QStatusBar::item {border: None; } QStatusBar QLabel { margin-right: 2px; margin-bottom: 1px; }");
this->centralWidget()->setStyleSheet("background-color: black;");
ui->toolBar->setVisible(!hide_tool_bar);
#ifdef _WIN32
ui->toolBar->setBackgroundRole(QPalette::Light);
#endif
renderers[0].reset(nullptr);
auto toolbar_spacer = new QWidget();
toolbar_spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->toolBar->addWidget(toolbar_spacer);
auto toolbar_label = new QLabel();
ui->toolBar->addWidget(toolbar_label);
this->setWindowFlag(Qt::MSWindowsFixedSizeDialogHint, vid_resize != 1);
this->setWindowFlag(Qt::WindowMaximizeButtonHint, vid_resize == 1);
QString vmname(vm_name);
if (vmname.at(vmname.size() - 1) == '"' || vmname.at(vmname.size() - 1) == '\'')
vmname.truncate(vmname.size() - 1);
this->setWindowTitle(QString("%1 - %2 %3").arg(vmname, EMU_NAME, EMU_VERSION_FULL));
connect(this, &MainWindow::hardResetCompleted, this, [this]() {
ui->actionMCA_devices->setVisible(machine_has_bus(machine, MACHINE_BUS_MCA));
while (QApplication::overrideCursor())
QApplication::restoreOverrideCursor();
#ifdef USE_WACOM
ui->menuTablet_tool->menuAction()->setVisible(mouse_input_mode >= 1);
#else
ui->menuTablet_tool->menuAction()->setVisible(false);
#endif
});
connect(this, &MainWindow::showMessageForNonQtThread, this, &MainWindow::showMessage_, Qt::QueuedConnection);
connect(this, &MainWindow::setTitle, this, [this, toolbar_label](const QString &title) {
if (dopause && !hide_tool_bar) {
toolbar_label->setText(toolbar_label->text() + tr(" - PAUSED"));
return;
}
if (!hide_tool_bar)
#ifdef _WIN32
toolbar_label->setText(title);
#else
{
/* get the percentage and mouse message, TODO: refactor ui_window_title() */
auto parts = title.split(" - ");
if (parts.size() >= 2) {
if (parts.size() < 5)
toolbar_label->setText(parts[1]);
else
toolbar_label->setText(QString("%1 - %2").arg(parts[1], parts.last()));
}
}
#endif
ui->actionPause->setChecked(false);
ui->actionPause->setCheckable(false);
});
connect(this, &MainWindow::getTitleForNonQtThread, this, &MainWindow::getTitle_, Qt::BlockingQueuedConnection);
connect(this, &MainWindow::updateMenuResizeOptions, [this]() {
ui->actionResizable_window->setEnabled(vid_resize != 2);
ui->actionResizable_window->setChecked(vid_resize == 1);
ui->menuWindow_scale_factor->setEnabled(vid_resize == 0);
});
connect(this, &MainWindow::updateWindowRememberOption, [this]() {
ui->actionRemember_size_and_position->setChecked(window_remember);
});
emit updateMenuResizeOptions();
connect(this, &MainWindow::setMouseCapture, this, [this](bool state) {
mouse_capture = state ? 1 : 0;
qt_mouse_capture(mouse_capture);
if (mouse_capture) {
this->grabKeyboard();
if (ui->stackedWidget->mouse_capture_func)
ui->stackedWidget->mouse_capture_func(this->windowHandle());
} else {
this->releaseKeyboard();
if (ui->stackedWidget->mouse_uncapture_func)
ui->stackedWidget->mouse_uncapture_func();
}
});
connect(qApp, &QGuiApplication::applicationStateChanged, [this](Qt::ApplicationState state) {
if (state == Qt::ApplicationState::ApplicationActive) {
if (auto_paused) {
plat_pause(0);
auto_paused = 0;
}
} else {
if (mouse_capture)
emit setMouseCapture(false);
if (do_auto_pause && !dopause) {
auto_paused = 1;
plat_pause(1);
}
}
});
connect(this, &MainWindow::resizeContents, this, [this](int w, int h) {
if (shownonce) {
if (resizableonce == false)
ui->stackedWidget->setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
resizableonce = true;
}
if (!QApplication::platformName().contains("eglfs") && vid_resize != 1) {
w = static_cast<int>(w / (!dpi_scale ? util::screenOfWidget(this)->devicePixelRatio() : 1.));
const int modifiedHeight =
static_cast<int>(h / (!dpi_scale ? util::screenOfWidget(this)->devicePixelRatio() : 1.))
+ menuBar()->height()
+ (statusBar()->height() * !hide_status_bar)
+ (ui->toolBar->height() * !hide_tool_bar);
ui->stackedWidget->resize(w, static_cast<int>(h / (!dpi_scale ? util::screenOfWidget(this)->devicePixelRatio() : 1.)));
setFixedSize(w, modifiedHeight);
}
});
connect(this, &MainWindow::resizeContentsMonitor, this, [this](int w, int h, int monitor_index) {
if (!QApplication::platformName().contains("eglfs") && vid_resize != 1) {
#ifdef QT_RESIZE_DEBUG
qDebug() << "Resize";
#endif
w = static_cast<int>(w / (!dpi_scale ? util::screenOfWidget(renderers[monitor_index].get())->devicePixelRatio() : 1.));
int modifiedHeight = static_cast<int>(h / (!dpi_scale ? util::screenOfWidget(renderers[monitor_index].get())->devicePixelRatio() : 1.));
renderers[monitor_index]->setFixedSize(w, modifiedHeight);
}
});
connect(ui->menubar, &QMenuBar::triggered, this, [this] {
config_save();
if (QApplication::activeWindow() == this) {
ui->stackedWidget->setFocusRenderer();
}
});
connect(this, &MainWindow::updateStatusBarPanes, this, [this] {
refreshMediaMenu();
});
connect(this, &MainWindow::updateStatusBarPanes, this, &MainWindow::refreshMediaMenu);
connect(this, &MainWindow::updateStatusBarTip, status.get(), &MachineStatus::updateTip);
connect(this, &MainWindow::statusBarMessage, status.get(), &MachineStatus::message, Qt::QueuedConnection);
ui->actionKeyboard_requires_capture->setChecked(kbd_req_capture);
ui->actionRight_CTRL_is_left_ALT->setChecked(rctrl_is_lalt);
ui->actionResizable_window->setChecked(vid_resize == 1);
ui->actionRemember_size_and_position->setChecked(window_remember);
ui->menuWindow_scale_factor->setEnabled(vid_resize == 0);
ui->actionHiDPI_scaling->setChecked(dpi_scale);
ui->actionHide_status_bar->setChecked(hide_status_bar);
ui->actionHide_tool_bar->setChecked(hide_tool_bar);
ui->actionShow_non_primary_monitors->setChecked(show_second_monitors);
ui->actionUpdate_status_bar_icons->setChecked(update_icons);
ui->actionEnable_Discord_integration->setChecked(enable_discord);
ui->actionApply_fullscreen_stretch_mode_when_maximized->setChecked(video_fullscreen_scale_maximized);
#ifndef DISCORD
ui->actionEnable_Discord_integration->setVisible(false);
#else
ui->actionEnable_Discord_integration->setEnabled(discord_loaded);
#endif
#if defined Q_OS_WINDOWS || defined Q_OS_MACOS
/* Make the option visible only if ANGLE is loaded. */
ui->actionHardware_Renderer_OpenGL_ES->setVisible(QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES);
if (QOpenGLContext::openGLModuleType() != QOpenGLContext::LibGLES && vid_api == 2)
vid_api = 1;
#endif
ui->actionHardware_Renderer_OpenGL->setVisible(QOpenGLContext::openGLModuleType() != QOpenGLContext::LibGLES);
if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES && vid_api == 1)
vid_api = 0;
if ((QApplication::platformName().contains("eglfs") || QApplication::platformName() == "haiku")) {
if (vid_api >= 1)
fprintf(stderr, "OpenGL renderers are unsupported on %s.\n", QApplication::platformName().toUtf8().data());
vid_api = 0;
ui->actionHardware_Renderer_OpenGL->setVisible(false);
ui->actionHardware_Renderer_OpenGL_ES->setVisible(false);
ui->actionVulkan->setVisible(false);
ui->actionOpenGL_3_0_Core->setVisible(false);
}
#ifndef USE_VNC
if (vid_api == 5)
vid_api = 0;
ui->actionVNC->setVisible(false);
#endif
#if QT_CONFIG(vulkan)
bool vulkanAvailable = false;
{
QVulkanInstance instance;
instance.setApiVersion(QVersionNumber(1, 0));
if (instance.create()) {
uint32_t physicalDevices = 0;
instance.functions()->vkEnumeratePhysicalDevices(instance.vkInstance(), &physicalDevices, nullptr);
if (physicalDevices != 0) {
vulkanAvailable = true;
}
}
}
if (!vulkanAvailable)
#endif
{
if (vid_api == 4)
vid_api = 0;
ui->actionVulkan->setVisible(false);
}
auto actGroup = new QActionGroup(this);
actGroup->addAction(ui->actionSoftware_Renderer);
actGroup->addAction(ui->actionHardware_Renderer_OpenGL);
actGroup->addAction(ui->actionHardware_Renderer_OpenGL_ES);
actGroup->addAction(ui->actionOpenGL_3_0_Core);
actGroup->addAction(ui->actionVulkan);
actGroup->addAction(ui->actionVNC);
actGroup->setExclusive(true);
connect(actGroup, &QActionGroup::triggered, [this](QAction *action) {
vid_api = action->property("vid_api").toInt();
#ifdef USE_VNC
if (vnc_enabled && vid_api != 5) {
startblit();
vnc_enabled = 0;
vnc_close();
video_setblit(qt_blit);
endblit();
}
#endif
RendererStack::Renderer newVidApi = RendererStack::Renderer::Software;
switch (vid_api) {
default:
break;
case 0:
newVidApi = RendererStack::Renderer::Software;
break;
case 1:
newVidApi = RendererStack::Renderer::OpenGL;
break;
case 2:
newVidApi = RendererStack::Renderer::OpenGLES;
break;
case 3:
newVidApi = RendererStack::Renderer::OpenGL3;
break;
case 4:
newVidApi = RendererStack::Renderer::Vulkan;
break;
#ifdef USE_VNC
case 5:
{
newVidApi = RendererStack::Renderer::Software;
startblit();
vnc_enabled = vnc_init(nullptr);
endblit();
}
#endif
}
ui->stackedWidget->switchRenderer(newVidApi);
if (!show_second_monitors)
return;
for (int i = 1; i < MONITORS_NUM; i++) {
if (renderers[i])
renderers[i]->switchRenderer(newVidApi);
}
});
connect(ui->stackedWidget, &RendererStack::rendererChanged, [this]() {
ui->actionRenderer_options->setVisible(ui->stackedWidget->hasOptions());
});
/* Trigger initial renderer switch */
for (const auto action : actGroup->actions())
if (action->property("vid_api").toInt() == vid_api) {
action->setChecked(true);
emit actGroup->triggered(action);
break;
}
switch (scale) {
default:
break;
case 0:
ui->action0_5x->setChecked(true);
break;
case 1:
ui->action1x->setChecked(true);
break;
case 2:
ui->action1_5x->setChecked(true);
break;
case 3:
ui->action2x->setChecked(true);
break;
case 4:
ui->action3x->setChecked(true);
break;
case 5:
ui->action4x->setChecked(true);
break;
case 6:
ui->action5x->setChecked(true);
break;
case 7:
ui->action6x->setChecked(true);
break;
case 8:
ui->action7x->setChecked(true);
break;
case 9:
ui->action8x->setChecked(true);
break;
}
actGroup = new QActionGroup(this);
actGroup->addAction(ui->action0_5x);
actGroup->addAction(ui->action1x);
actGroup->addAction(ui->action1_5x);
actGroup->addAction(ui->action2x);
actGroup->addAction(ui->action3x);
actGroup->addAction(ui->action4x);
actGroup->addAction(ui->action5x);
actGroup->addAction(ui->action6x);
actGroup->addAction(ui->action7x);
actGroup->addAction(ui->action8x);
switch (video_filter_method) {
default:
break;
case 0:
ui->actionNearest->setChecked(true);
break;
case 1:
ui->actionLinear->setChecked(true);
break;
}
actGroup = new QActionGroup(this);
actGroup->addAction(ui->actionNearest);
actGroup->addAction(ui->actionLinear);
switch (video_fullscreen_scale) {
default:
break;
case FULLSCR_SCALE_FULL:
ui->actionFullScreen_stretch->setChecked(true);
break;
case FULLSCR_SCALE_43:
ui->actionFullScreen_43->setChecked(true);
break;
case FULLSCR_SCALE_KEEPRATIO:
ui->actionFullScreen_keepRatio->setChecked(true);
break;
case FULLSCR_SCALE_INT:
ui->actionFullScreen_int->setChecked(true);
break;
case FULLSCR_SCALE_INT43:
ui->actionFullScreen_int43->setChecked(true);
break;
}
actGroup = new QActionGroup(this);
actGroup->addAction(ui->actionFullScreen_stretch);
actGroup->addAction(ui->actionFullScreen_43);
actGroup->addAction(ui->actionFullScreen_keepRatio);
actGroup->addAction(ui->actionFullScreen_int);
actGroup->addAction(ui->actionFullScreen_int43);
switch (video_grayscale) {
default:
break;
case 0:
ui->actionRGB_Color->setChecked(true);
break;
case 1:
ui->actionRGB_Grayscale->setChecked(true);
break;
case 2:
ui->actionAmber_monitor->setChecked(true);
break;
case 3:
ui->actionGreen_monitor->setChecked(true);
break;
case 4:
ui->actionWhite_monitor->setChecked(true);
break;
}
actGroup = new QActionGroup(this);
actGroup->addAction(ui->actionRGB_Grayscale);
actGroup->addAction(ui->actionAmber_monitor);
actGroup->addAction(ui->actionGreen_monitor);
actGroup->addAction(ui->actionWhite_monitor);
actGroup->addAction(ui->actionRGB_Color);
switch (video_graytype) {
default:
break;
case 0:
ui->actionBT601_NTSC_PAL->setChecked(true);
break;
case 1:
ui->actionBT709_HDTV->setChecked(true);
break;
case 2:
ui->actionAverage->setChecked(true);
break;
}
actGroup = new QActionGroup(this);
actGroup->addAction(ui->actionBT601_NTSC_PAL);
actGroup->addAction(ui->actionBT709_HDTV);
actGroup->addAction(ui->actionAverage);
if (force_43 > 0) {
ui->actionForce_4_3_display_ratio->setChecked(true);
}
if (enable_overscan > 0) {
ui->actionCGA_PCjr_Tandy_EGA_S_VGA_overscan->setChecked(true);
}
if (vid_cga_contrast > 0) {
ui->actionChange_contrast_for_monochrome_display->setChecked(true);
}
if (do_auto_pause > 0) {
ui->actionAuto_pause->setChecked(true);
}
#ifdef Q_OS_MACOS
ui->actionCtrl_Alt_Del->setShortcutVisibleInContextMenu(true);
ui->actionTake_screenshot->setShortcutVisibleInContextMenu(true);
#endif
if (!vnc_enabled)
video_setblit(qt_blit);
if (start_in_fullscreen) {
connect(ui->stackedWidget, &RendererStack::blitToRenderer, this, [this] () {
if (start_in_fullscreen) {
QTimer::singleShot(100, ui->actionFullscreen, &QAction::trigger);
start_in_fullscreen = 0;
}
});
}
#ifdef MTR_ENABLED
{
ui->actionBegin_trace->setVisible(true);
ui->actionEnd_trace->setVisible(true);
ui->actionBegin_trace->setShortcut(QKeySequence(Qt::Key_Control + Qt::Key_T));
ui->actionEnd_trace->setShortcut(QKeySequence(Qt::Key_Control + Qt::Key_T));
ui->actionEnd_trace->setDisabled(true);
static auto init_trace = [&] {
mtr_init("trace.json");
mtr_start();
};
static auto shutdown_trace = [&] {
mtr_stop();
mtr_shutdown();
};
# ifdef Q_OS_MACOS
ui->actionBegin_trace->setShortcutVisibleInContextMenu(true);
ui->actionEnd_trace->setShortcutVisibleInContextMenu(true);
# endif
static bool trace = false;
connect(ui->actionBegin_trace, &QAction::triggered, this, [this] {
if (trace)
return;
ui->actionBegin_trace->setDisabled(true);
ui->actionEnd_trace->setDisabled(false);
init_trace();
trace = true;
});
connect(ui->actionEnd_trace, &QAction::triggered, this, [this] {
if (!trace)
return;
ui->actionBegin_trace->setDisabled(false);
ui->actionEnd_trace->setDisabled(true);
shutdown_trace();
trace = false;
});
}
#endif
setContextMenuPolicy(Qt::PreventContextMenu);
/* Remove default Shift+F10 handler, which unfocuses keyboard input even with no context menu. */
connect(new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_F10), this), &QShortcut::activated, this, [](){});
connect(this, &MainWindow::initRendererMonitor, this, &MainWindow::initRendererMonitorSlot);
connect(this, &MainWindow::initRendererMonitorForNonQtThread, this, &MainWindow::initRendererMonitorSlot, Qt::BlockingQueuedConnection);
connect(this, &MainWindow::destroyRendererMonitor, this, &MainWindow::destroyRendererMonitorSlot);
connect(this, &MainWindow::destroyRendererMonitorForNonQtThread, this, &MainWindow::destroyRendererMonitorSlot, Qt::BlockingQueuedConnection);
#ifdef Q_OS_MACOS
QTimer::singleShot(0, this, [this]() {
for (auto curObj : this->menuBar()->children()) {
if (qobject_cast<QMenu *>(curObj)) {
auto menu = qobject_cast<QMenu *>(curObj);
menu->setSeparatorsCollapsible(false);
for (auto curObj2 : menu->children()) {
if (qobject_cast<QMenu *>(curObj2)) {
auto menu2 = qobject_cast<QMenu *>(curObj2);
menu2->setSeparatorsCollapsible(false);
}
}
}
}
});
#endif
actGroup = new QActionGroup(this);
actGroup->addAction(ui->actionCursor_Puck);
actGroup->addAction(ui->actionPen);
if (tablet_tool_type == 1) {
ui->actionPen->setChecked(true);
} else {
ui->actionCursor_Puck->setChecked(true);
}
#ifdef XKBCOMMON
# ifdef XKBCOMMON_X11
if (QApplication::platformName().contains("xcb"))
xkbcommon_x11_init();
else
# endif
# ifdef WAYLAND
if (QApplication::platformName().contains("wayland"))
xkbcommon_wl_init();
else
# endif
{}
#endif
#if defined Q_OS_UNIX && !defined Q_OS_MACOS && !defined Q_OS_HAIKU
if (QApplication::platformName().contains("xcb")) {
QTimer::singleShot(0, this, [this] {
auto whandle = windowHandle();
if (! whandle) {
qWarning() << "No window handle";
} else {
QPlatformWindow *window = whandle->handle();
set_wm_class(window->winId(), vm_name);
}
});
}
#endif
}
void
MainWindow::closeEvent(QCloseEvent *event)
{
if (mouse_capture) {
event->ignore();
return;
}
if (confirm_exit && confirm_exit_cmdl && cpu_thread_run) {
QMessageBox questionbox(QMessageBox::Icon::Question, "86Box", tr("Are you sure you want to exit 86Box?"), QMessageBox::Yes | QMessageBox::No, this);
auto chkbox = new QCheckBox(tr("Don't show this message again"));
questionbox.setCheckBox(chkbox);
chkbox->setChecked(!confirm_exit);
QObject::connect(chkbox, &QCheckBox::stateChanged, [](int state) {
confirm_exit = (state == Qt::CheckState::Unchecked);
});
questionbox.exec();
if (questionbox.result() == QMessageBox::No) {
confirm_exit = true;
event->ignore();
return;
}
}
if (window_remember) {
window_w = ui->stackedWidget->width();
window_h = ui->stackedWidget->height();
if (!QApplication::platformName().contains("wayland")) {
window_x = this->geometry().x();
window_y = this->geometry().y();
}
for (int i = 1; i < MONITORS_NUM; i++) {
if (renderers[i]) {
monitor_settings[i].mon_window_w = renderers[i]->geometry().width();
monitor_settings[i].mon_window_h = renderers[i]->geometry().height();
if (QApplication::platformName().contains("wayland"))
continue;
monitor_settings[i].mon_window_x = renderers[i]->geometry().x();
monitor_settings[i].mon_window_y = renderers[i]->geometry().y();
}
}
}
if (ui->stackedWidget->mouse_exit_func)
ui->stackedWidget->mouse_exit_func();
ui->stackedWidget->switchRenderer(RendererStack::Renderer::Software);
qt_nvr_save();
config_save();
QApplication::processEvents();
cpu_thread_run = 0;
event->accept();
}
void
MainWindow::initRendererMonitorSlot(int monitor_index)
{
auto &secondaryRenderer = this->renderers[monitor_index];
secondaryRenderer = std::make_unique<RendererStack>(nullptr, monitor_index);
if (secondaryRenderer) {
connect(secondaryRenderer.get(), &RendererStack::rendererChanged, this, [this, monitor_index] {
this->renderers[monitor_index]->show();
});
secondaryRenderer->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
secondaryRenderer->setWindowTitle(QObject::tr("86Box Monitor #") + QString::number(monitor_index + 1));
if (vid_resize == 2)
secondaryRenderer->setFixedSize(fixed_size_x, fixed_size_y);
secondaryRenderer->setWindowIcon(this->windowIcon());
if (show_second_monitors) {
secondaryRenderer->show();
if (window_remember) {
secondaryRenderer->setGeometry(monitor_settings[monitor_index].mon_window_x < 120 ? 120 : monitor_settings[monitor_index].mon_window_x,
monitor_settings[monitor_index].mon_window_y < 120 ? 120 : monitor_settings[monitor_index].mon_window_y,
monitor_settings[monitor_index].mon_window_w > 2048 ? 2048 : monitor_settings[monitor_index].mon_window_w,
monitor_settings[monitor_index].mon_window_h > 2048 ? 2048 : monitor_settings[monitor_index].mon_window_h);
}
if (monitor_settings[monitor_index].mon_window_maximized)
secondaryRenderer->showMaximized();
secondaryRenderer->switchRenderer((RendererStack::Renderer) vid_api);
secondaryRenderer->setMouseTracking(true);
if (monitor_settings[monitor_index].mon_window_maximized) {
if (renderers[monitor_index])
renderers[monitor_index]->onResize(renderers[monitor_index]->width(),
renderers[monitor_index]->height());
device_force_redraw();
}
}
}
}
void
MainWindow::destroyRendererMonitorSlot(int monitor_index)
{
if (this->renderers[monitor_index]) {
if (window_remember) {
monitor_settings[monitor_index].mon_window_w = renderers[monitor_index]->geometry().width();
monitor_settings[monitor_index].mon_window_h = renderers[monitor_index]->geometry().height();
monitor_settings[monitor_index].mon_window_x = renderers[monitor_index]->geometry().x();
monitor_settings[monitor_index].mon_window_y = renderers[monitor_index]->geometry().y();
}
config_save();
this->renderers[monitor_index].release()->deleteLater();
ui->stackedWidget->switchRenderer((RendererStack::Renderer) vid_api);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void
MainWindow::showEvent(QShowEvent *event)
{
if (shownonce)
return;
shownonce = true;
if (window_remember) {
if (window_w == 0)
window_w = 320;
if (window_h == 0)
window_h = 200;
}
if (window_remember && !QApplication::platformName().contains("wayland")) {
setGeometry(window_x, window_y, window_w, window_h + menuBar()->height() + (hide_status_bar ? 0 : statusBar()->height()) + (hide_tool_bar ? 0 : ui->toolBar->height()));
}
if (vid_resize == 2) {
setFixedSize(fixed_size_x, fixed_size_y + menuBar()->height() + (hide_status_bar ? 0 : statusBar()->height()) + (hide_tool_bar ? 0 : ui->toolBar->height()));
monitors[0].mon_scrnsz_x = fixed_size_x;
monitors[0].mon_scrnsz_y = fixed_size_y;
}
if (window_remember && vid_resize == 1) {
ui->stackedWidget->setFixedSize(window_w, window_h);
QApplication::processEvents();
this->adjustSize();
}
}
void
MainWindow::on_actionKeyboard_requires_capture_triggered()
{
kbd_req_capture ^= 1;
}
void
MainWindow::on_actionRight_CTRL_is_left_ALT_triggered()
{
rctrl_is_lalt ^= 1;
}
void
MainWindow::on_actionHard_Reset_triggered()
{
if (confirm_reset) {
QMessageBox questionbox(QMessageBox::Icon::Question, "86Box", tr("Are you sure you want to hard reset the emulated machine?"), QMessageBox::NoButton, this);
questionbox.addButton(tr("Reset"), QMessageBox::AcceptRole);
questionbox.addButton(tr("Don't reset"), QMessageBox::RejectRole);
const auto chkbox = new QCheckBox(tr("Don't show this message again"));
questionbox.setCheckBox(chkbox);
chkbox->setChecked(!confirm_reset);
QObject::connect(chkbox, &QCheckBox::stateChanged, [](int state) {
confirm_reset = (state == Qt::CheckState::Unchecked);
});
questionbox.exec();
if (questionbox.result() == QDialog::Accepted) {
confirm_reset = true;
return;
}
}
config_changed = 2;
pc_reset_hard();
}
void
MainWindow::on_actionCtrl_Alt_Del_triggered()
{
pc_send_cad();
}
void
MainWindow::on_actionCtrl_Alt_Esc_triggered()
{
pc_send_cae();
}
void
MainWindow::on_actionPause_triggered()
{
plat_pause(dopause ^ 1);
}
void
MainWindow::on_actionExit_triggered()
{
close();
}
void
MainWindow::on_actionSettings_triggered()
{
const int currentPause = dopause;
plat_pause(1);
Settings settings(this);
settings.setModal(true);
settings.setWindowModality(Qt::WindowModal);
settings.setWindowFlag(Qt::CustomizeWindowHint, true);
settings.setWindowFlag(Qt::WindowTitleHint, true);
settings.setWindowFlag(Qt::WindowSystemMenuHint, false);
settings.exec();
switch (settings.result()) {
default:
break;
case QDialog::Accepted:
pc_reset_hard_close();
settings.save();
config_changed = 2;
pc_reset_hard_init();
break;
case QDialog::Rejected:
break;
}
plat_pause(currentPause);
}
void
MainWindow::processKeyboardInput(bool down, uint32_t keycode)
{
#if defined(Q_OS_WINDOWS) /* non-raw input */
keycode &= 0xffff;
#elif defined(Q_OS_MACOS)
keycode = (keycode < 127) ? cocoa_keycodes[keycode] : 0;
#elif defined(__HAIKU__)
keycode = be_keycodes[keycode];
#else
# ifdef XKBCOMMON
if (xkbcommon_keymap)
keycode = xkbcommon_translate(keycode);
else
# endif
# ifdef EVDEV_KEYBOARD_HPP
keycode = evdev_translate(keycode - 8);
# else
keycode = 0;
# endif
#endif
/* Apply special cases. */
switch (keycode) {
default:
break;
case 0x54: /* Alt + Print Screen (special case, i.e. evdev SELECTIVE_SCREENSHOT) */
/* Send Alt as well. */
if (down) {
keyboard_input(down, 0x38);
} else {
keyboard_input(down, keycode);
keycode = 0x38;
}
break;
case 0x80 ... 0xff: /* regular break codes */
case 0x10b: /* Microsoft scroll up normal */
case 0x180 ... 0x1ff: /* E0 break codes (including Microsoft scroll down normal) */
/* This key uses a break code as make. Send it manually, only on press. */
if (down && (mouse_capture || !kbd_req_capture || video_fullscreen)) {
if (keycode & 0x100)
keyboard_send(0xe0);
keyboard_send(keycode & 0xff);
}
return;
case 0x11d: /* Right Ctrl */
if (rctrl_is_lalt)
keycode = 0x38; /* map to Left Alt */
break;
case 0x137: /* Print Screen */
if (keyboard_recv_ui(0x38) || keyboard_recv_ui(0x138)) { /* Alt+ */
keycode = 0x54;
} else if (down) {
keyboard_input(down, 0x12a);
} else {
keyboard_input(down, keycode);
keycode = 0x12a;
}
break;
case 0x145: /* Pause */
if (keyboard_recv_ui(0x1d) || keyboard_recv_ui(0x11d)) { /* Ctrl+ */
keycode = 0x146;
} else {
keyboard_input(down, 0xe11d);
keycode &= 0x00ff;
}
break;
}
keyboard_input(down, keycode);
}
#ifdef Q_OS_MACOS
// These modifiers are listed as "device-dependent" in IOLLEvent.h, but
// that's followed up with "(really?)". It's the only way to distinguish
// left and right modifiers with Qt 6 on macOS, so let's just roll with it.
static std::unordered_map<uint32_t, uint16_t> mac_modifiers_to_xt = {
{NX_DEVICELCTLKEYMASK, 0x1D },
{ NX_DEVICELSHIFTKEYMASK, 0x2A },
{ NX_DEVICERSHIFTKEYMASK, 0x36 },
{ NX_DEVICELCMDKEYMASK, 0x15B},
{ NX_DEVICERCMDKEYMASK, 0x15C},
{ NX_DEVICELALTKEYMASK, 0x38 },
{ NX_DEVICERALTKEYMASK, 0x138},
{ NX_DEVICE_ALPHASHIFT_STATELESS_MASK, 0x3A },
{ NX_DEVICERCTLKEYMASK, 0x11D},
};
static bool mac_iso_swap = false;
void
MainWindow::processMacKeyboardInput(bool down, const QKeyEvent *event)
{
// Per QTBUG-69608 (path_to_url
// QKeyEvents QKeyEvents for presses/releases of modifiers on macOS give
// nativeVirtualKey() == 0 (at least in Qt 6). Handle this by manually
// processing the nativeModifiers(). We need to check whether the key() is
// a known modifier because because kVK_ANSI_A is also 0, so the
// nativeVirtualKey() == 0 condition is ambiguous...
if (event->nativeVirtualKey() == 0
&& (event->key() == Qt::Key_Shift
|| event->key() == Qt::Key_Control
|| event->key() == Qt::Key_Meta
|| event->key() == Qt::Key_Alt
|| event->key() == Qt::Key_AltGr
|| event->key() == Qt::Key_CapsLock)) {
// We only process one modifier at a time since events from Qt seem to
// always be non-coalesced (NX_NONCOALESCEDMASK is always set).
uint32_t changed_modifiers = last_modifiers ^ event->nativeModifiers();
for (auto const &pair : mac_modifiers_to_xt) {
if (changed_modifiers & pair.first) {
last_modifiers ^= pair.first;
keyboard_input(down, pair.second);
return;
}
}
// Caps Lock seems to be delivered as a single key press event when
// enabled and a single key release event when disabled, so we can't
// detect Caps Lock being held down; just send an infinitesimally-long
// press and release as a compromise.
//
// The event also doesn't get delivered if you turn Caps Lock off after
// turning it on when the window isn't focused. Doing better than this
// probably requires bypassing Qt input processing.
//
// It's possible that other lock keys get delivered in this way, but
// standard Apple keyboards don't have them, so this is untested.
if (event->key() == Qt::Key_CapsLock) {
keyboard_input(1, 0x3a);
keyboard_input(0, 0x3a);
}
} else {
/* Apple ISO keyboards are notorious for swapping ISO_Section and ANSI_Grave
on *some* layouts and/or models. While macOS can sort this mess out at
keymap level, it still provides applications with unfiltered, ambiguous
keycodes, so we have to disambiguate them by making some bold assumptions
about the user's keyboard layout based on the OS-provided key mappings. */
auto nvk = event->nativeVirtualKey();
if ((nvk == 0x0a) || (nvk == 0x32)) {
/* Flaws:
- Layouts with `~ on ISO_Section are partially detected due to a conflict with ANSI
- Czech and Slovak are not detected as they have <> ANSI_Grave and \| ISO_Section (differing from PC actually)
- Italian is partially detected due to \| conflicting with Brazilian
- Romanian third level ANSI_Grave is unknown
- Russian clusters <>, plusminus and paragraph into a four-level ANSI_Grave, with the aforementioned `~ on ISO_Section */
auto key = event->key();
if ((nvk == 0x32) && ( /* system reports ANSI_Grave for ISO_Section keys: */
(key == Qt::Key_Less) || (key == Qt::Key_Greater) || /* Croatian, French, German, Icelandic, Italian, Norwegian, Portuguese, Spanish, Spanish Latin America, Turkish Q */
(key == Qt::Key_Ugrave) || /* French Canadian */
(key == Qt::Key_Icircumflex) || /* Romanian */
(key == Qt::Key_Iacute) || /* Hungarian */
(key == Qt::Key_BracketLeft) || (key == Qt::Key_BracketRight) || /* Russian upper two levels */
(key == Qt::Key_W) /* Turkish F */
))
mac_iso_swap = true;
else if ((nvk == 0x0a) && ( /* system reports ISO_Section for ANSI_Grave keys: */
(key == Qt::Key_paragraph) || (key == Qt::Key_plusminus) || /* Arabic, British, Bulgarian, Danish shifted, Dutch, Greek, Hebrew, Hungarian shifted, International English, Norwegian shifted, Portuguese, Russian lower two levels, Swiss unshifted, Swedish unshifted, Turkish F */
(key == Qt::Key_At) || (key == Qt::Key_NumberSign) || /* Belgian, French */
(key == Qt::Key_Apostrophe) || /* Brazilian unshifted */
(key == Qt::Key_QuoteDbl) || /* Brazilian shifted, Turkish Q unshifted */
(key == Qt::Key_QuoteLeft) || /* Croatian (right quote unknown) */
(key == Qt::Key_Dollar) || /* Danish unshifted */
(key == Qt::Key_AsciiCircum) || (key == 0x1ffffff) || /* German unshifted (0x1ffffff according to one tester), Polish unshifted */
(key == Qt::Key_degree) || /* German shifted, Icelandic unshifted, Spanish Latin America shifted, Swiss shifted, Swedish shifted */
(key == Qt::Key_0) || /* Hungarian unshifted */
(key == Qt::Key_diaeresis) || /* Icelandic shifted */
(key == Qt::Key_acute) || /* Norwegian unshifted */
(key == Qt::Key_Asterisk) || /* Polish shifted */
(key == Qt::Key_masculine) || (key == Qt::Key_ordfeminine) || /* Spanish (masculine unconfirmed) */
(key == Qt::Key_Eacute) || /* Turkish Q shifted */
(key == Qt::Key_Slash) /* French Canadian unshifted, Ukrainian shifted */
))
mac_iso_swap = true;
#if 0
if (down) {
QMessageBox questionbox(QMessageBox::Icon::Information, QString("Mac key swap test"), QString("nativeVirtualKey 0x%1\nnativeScanCode 0x%2\nkey 0x%3\nmac_iso_swap %4").arg(nvk, 0, 16).arg(event->nativeScanCode(), 0, 16).arg(key, 0, 16).arg(mac_iso_swap ? "yes" : "no"), QMessageBox::Ok, this);
questionbox.exec();
}
#endif
if (mac_iso_swap)
nvk = (nvk == 0x0a) ? 0x32 : 0x0a;
}
// Special case for command + forward delete to send insert.
if ((event->nativeModifiers() & NSEventModifierFlagCommand) &&
((event->nativeVirtualKey() == nvk_Delete) || event->key() == Qt::Key_Delete)) {
nvk = nvk_Insert; // Qt::Key_Help according to event->key()
}
processKeyboardInput(down, nvk);
}
}
#endif
void
MainWindow::on_actionFullscreen_triggered()
{
if (video_fullscreen > 0) {
showNormal();
ui->menubar->show();
if (!hide_status_bar)
ui->statusbar->show();
if (!hide_tool_bar)
ui->toolBar->show();
video_fullscreen = 0;
if (vid_resize != 1) {
emit resizeContents(vid_resize == 2 ? fixed_size_x : monitors[0].mon_scrnsz_x, vid_resize == 2 ? fixed_size_y : monitors[0].mon_scrnsz_y);
}
} else {
if (video_fullscreen_first) {
bool wasCaptured = mouse_capture == 1;
QMessageBox questionbox(QMessageBox::Icon::Information, tr("Entering fullscreen mode"), tr("Press Ctrl+Alt+PgDn to return to windowed mode."), QMessageBox::Ok, this);
QCheckBox *chkbox = new QCheckBox(tr("Don't show this message again"));
questionbox.setCheckBox(chkbox);
chkbox->setChecked(!video_fullscreen_first);
QObject::connect(chkbox, &QCheckBox::stateChanged, [](int state) {
video_fullscreen_first = (state == Qt::CheckState::Unchecked);
});
questionbox.exec();
config_save();
/* (re-capture mouse after dialog). */
if (wasCaptured)
emit setMouseCapture(true);
}
video_fullscreen = 1;
setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
ui->menubar->hide();
ui->statusbar->hide();
ui->toolBar->hide();
ui->stackedWidget->setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
showFullScreen();
}
fs_on_signal = false;
fs_off_signal = false;
ui->stackedWidget->onResize(width(), height());
}
void
MainWindow::getTitle_(wchar_t *title)
{
this->windowTitle().toWCharArray(title);
}
void
MainWindow::getTitle(wchar_t *title)
{
if (QThread::currentThread() == this->thread()) {
getTitle_(title);
} else {
emit getTitleForNonQtThread(title);
}
}
bool
MainWindow::eventFilter(QObject *receiver, QEvent *event)
{
if (!dopause) {
if (event->type() == QEvent::Shortcut) {
auto shortcutEvent = (QShortcutEvent *) event;
if (shortcutEvent->key() == ui->actionExit->shortcut()) {
event->accept();
return true;
}
}
if (event->type() == QEvent::KeyPress) {
event->accept();
this->keyPressEvent((QKeyEvent *) event);
return true;
}
if (event->type() == QEvent::KeyRelease) {
event->accept();
this->keyReleaseEvent((QKeyEvent *) event);
return true;
}
}
if (receiver == this) {
static auto curdopause = dopause;
if (event->type() == QEvent::WindowBlocked) {
curdopause = dopause;
plat_pause(1);
emit setMouseCapture(false);
} else if (event->type() == QEvent::WindowUnblocked) {
plat_pause(curdopause);
}
}
return QMainWindow::eventFilter(receiver, event);
}
void
MainWindow::refreshMediaMenu()
{
mm->refresh(ui->menuMedia);
status->refresh(ui->statusbar);
ui->actionMCA_devices->setVisible(machine_has_bus(machine, MACHINE_BUS_MCA));
ui->actionACPI_Shutdown->setEnabled(!!acpi_enabled);
}
void
MainWindow::showMessage(int flags, const QString &header, const QString &message)
{
if (QThread::currentThread() == this->thread()) {
showMessage_(flags, header, message);
} else {
std::atomic_bool done = false;
emit showMessageForNonQtThread(flags, header, message, &done);
while (!done) {
QThread::msleep(1);
}
}
}
void
MainWindow::showMessage_(int flags, const QString &header, const QString &message, std::atomic_bool *done)
{
if (done) {
*done = false;
}
QMessageBox box(QMessageBox::Warning, header, message, QMessageBox::NoButton, this);
if (flags & (MBX_FATAL)) {
box.setIcon(QMessageBox::Critical);
} else if (!(flags & (MBX_ERROR | MBX_WARNING))) {
box.setIcon(QMessageBox::Warning);
}
box.setTextFormat(Qt::TextFormat::RichText);
box.exec();
if (done) {
*done = true;
}
if (cpu_thread_run == 0)
QApplication::exit(-1);
}
void
MainWindow::keyPressEvent(QKeyEvent *event)
{
if (send_keyboard_input) {
#ifdef Q_OS_MACOS
processMacKeyboardInput(true, event);
#else
processKeyboardInput(true, event->nativeScanCode());
#endif
}
checkFullscreenHotkey();
if (keyboard_ismsexit())
plat_mouse_capture(0);
if ((video_fullscreen > 0) && (keyboard_recv_ui(0x1D) || keyboard_recv_ui(0x11D))) {
if (keyboard_recv_ui(0x57))
ui->actionTake_screenshot->trigger();
else if (keyboard_recv_ui(0x58))
pc_send_cad();
}
event->accept();
}
void
MainWindow::blitToWidget(int x, int y, int w, int h, int monitor_index)
{
if (monitor_index >= 1) {
if (renderers[monitor_index] && renderers[monitor_index]->isVisible())
renderers[monitor_index]->blit(x, y, w, h);
else
video_blit_complete_monitor(monitor_index);
} else
ui->stackedWidget->blit(x, y, w, h);
}
void
MainWindow::keyReleaseEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Pause) {
if (keyboard_recv_ui(0x38) && keyboard_recv_ui(0x138)) {
plat_pause(dopause ^ 1);
}
}
if (send_keyboard_input && !event->isAutoRepeat()) {
#ifdef Q_OS_MACOS
processMacKeyboardInput(false, event);
#else
processKeyboardInput(false, event->nativeScanCode());
#endif
}
checkFullscreenHotkey();
}
void
MainWindow::checkFullscreenHotkey()
{
if (!fs_off_signal && video_fullscreen && keyboard_isfsexit()) {
/* Signal "exit fullscreen mode". */
fs_off_signal = true;
} else if (fs_off_signal && video_fullscreen && keyboard_isfsexit_up()) {
ui->actionFullscreen->trigger();
fs_off_signal = false;
}
if (!fs_on_signal && !video_fullscreen && keyboard_isfsenter()) {
/* Signal "enter fullscreen mode". */
fs_on_signal = true;
} else if (fs_on_signal && !video_fullscreen && keyboard_isfsenter_up()) {
ui->actionFullscreen->trigger();
fs_on_signal = false;
}
}
QSize
MainWindow::getRenderWidgetSize()
{
return ui->stackedWidget->size();
}
void
MainWindow::focusInEvent(QFocusEvent *event)
{
this->grabKeyboard();
}
void
MainWindow::focusOutEvent(QFocusEvent *event)
{
this->releaseKeyboard();
}
void
MainWindow::on_actionResizable_window_triggered(bool checked)
{
if (checked) {
vid_resize = 1;
setWindowFlag(Qt::WindowMaximizeButtonHint, true);
setWindowFlag(Qt::MSWindowsFixedSizeDialogHint, false);
setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
for (int i = 1; i < MONITORS_NUM; i++) {
if (monitors[i].target_buffer) {
renderers[i]->setWindowFlag(Qt::WindowMaximizeButtonHint, true);
renderers[i]->setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
}
}
} else {
vid_resize = 0;
setWindowFlag(Qt::WindowMaximizeButtonHint, false);
setWindowFlag(Qt::MSWindowsFixedSizeDialogHint);
for (int i = 1; i < MONITORS_NUM; i++) {
if (monitors[i].target_buffer) {
renderers[i]->setWindowFlag(Qt::WindowMaximizeButtonHint, false);
emit resizeContentsMonitor(monitors[i].mon_scrnsz_x, monitors[i].mon_scrnsz_y, i);
}
}
}
show();
ui->menuWindow_scale_factor->setEnabled(!checked);
emit resizeContents(monitors[0].mon_scrnsz_x, monitors[0].mon_scrnsz_y);
ui->stackedWidget->switchRenderer((RendererStack::Renderer) vid_api);
for (int i = 1; i < MONITORS_NUM; i++) {
if (monitors[i].target_buffer && show_second_monitors) {
renderers[i]->show();
renderers[i]->switchRenderer((RendererStack::Renderer) vid_api);
QApplication::processEvents();
}
}
}
static void
video_toggle_option(QAction *action, int *val)
{
startblit();
*val ^= 1;
video_copy = (video_grayscale || invert_display) ? video_transform_copy : memcpy;
action->setChecked(*val > 0 ? true : false);
endblit();
config_save();
reset_screen_size();
device_force_redraw();
for (int i = 0; i < MONITORS_NUM; i++) {
if (monitors[i].target_buffer)
video_force_resize_set_monitor(1, i);
}
}
void
MainWindow::on_actionInverted_VGA_monitor_triggered()
{
video_toggle_option(ui->actionInverted_VGA_monitor, &invert_display);
}
static void
update_scaled_checkboxes(Ui::MainWindow *ui, QAction *selected)
{
ui->action0_5x->setChecked(ui->action0_5x == selected);
ui->action1x->setChecked(ui->action1x == selected);
ui->action1_5x->setChecked(ui->action1_5x == selected);
ui->action2x->setChecked(ui->action2x == selected);
ui->action3x->setChecked(ui->action3x == selected);
ui->action4x->setChecked(ui->action4x == selected);
ui->action5x->setChecked(ui->action5x == selected);
ui->action6x->setChecked(ui->action6x == selected);
ui->action7x->setChecked(ui->action7x == selected);
ui->action8x->setChecked(ui->action8x == selected);
reset_screen_size();
device_force_redraw();
for (int i = 0; i < MONITORS_NUM; i++) {
if (monitors[i].target_buffer)
video_force_resize_set_monitor(1, i);
}
config_save();
}
void
MainWindow::on_action0_5x_triggered()
{
scale = 0;
update_scaled_checkboxes(ui, ui->action0_5x);
}
void
MainWindow::on_action1x_triggered()
{
scale = 1;
update_scaled_checkboxes(ui, ui->action1x);
}
void
MainWindow::on_action1_5x_triggered()
{
scale = 2;
update_scaled_checkboxes(ui, ui->action1_5x);
}
void
MainWindow::on_action2x_triggered()
{
scale = 3;
update_scaled_checkboxes(ui, ui->action2x);
}
void
MainWindow::on_action3x_triggered()
{
scale = 4;
update_scaled_checkboxes(ui, ui->action3x);
}
void
MainWindow::on_action4x_triggered()
{
scale = 5;
update_scaled_checkboxes(ui, ui->action4x);
}
void
MainWindow::on_action5x_triggered()
{
scale = 6;
update_scaled_checkboxes(ui, ui->action5x);
}
void
MainWindow::on_action6x_triggered()
{
scale = 7;
update_scaled_checkboxes(ui, ui->action6x);
}
void
MainWindow::on_action7x_triggered()
{
scale = 8;
update_scaled_checkboxes(ui, ui->action7x);
}
void
MainWindow::on_action8x_triggered()
{
scale = 9;
update_scaled_checkboxes(ui, ui->action8x);
}
void
MainWindow::on_actionNearest_triggered()
{
video_filter_method = 0;
ui->actionLinear->setChecked(false);
}
void
MainWindow::on_actionLinear_triggered()
{
video_filter_method = 1;
ui->actionNearest->setChecked(false);
}
static void
update_fullscreen_scale_checkboxes(Ui::MainWindow *ui, QAction *selected)
{
ui->actionFullScreen_stretch->setChecked(selected == ui->actionFullScreen_stretch);
ui->actionFullScreen_43->setChecked(selected == ui->actionFullScreen_43);
ui->actionFullScreen_keepRatio->setChecked(selected == ui->actionFullScreen_keepRatio);
ui->actionFullScreen_int->setChecked(selected == ui->actionFullScreen_int);
ui->actionFullScreen_int43->setChecked(selected == ui->actionFullScreen_int43);
{
auto widget = ui->stackedWidget->currentWidget();
ui->stackedWidget->onResize(widget->width(), widget->height());
}
for (int i = 1; i < MONITORS_NUM; i++) {
if (main_window->renderers[i])
main_window->renderers[i]->onResize(main_window->renderers[i]->width(),
main_window->renderers[i]->height());
}
device_force_redraw();
config_save();
}
void
MainWindow::on_actionFullScreen_stretch_triggered()
{
video_fullscreen_scale = FULLSCR_SCALE_FULL;
update_fullscreen_scale_checkboxes(ui, ui->actionFullScreen_stretch);
}
void
MainWindow::on_actionFullScreen_43_triggered()
{
video_fullscreen_scale = FULLSCR_SCALE_43;
update_fullscreen_scale_checkboxes(ui, ui->actionFullScreen_43);
}
void
MainWindow::on_actionFullScreen_keepRatio_triggered()
{
video_fullscreen_scale = FULLSCR_SCALE_KEEPRATIO;
update_fullscreen_scale_checkboxes(ui, ui->actionFullScreen_keepRatio);
}
void
MainWindow::on_actionFullScreen_int_triggered()
{
video_fullscreen_scale = FULLSCR_SCALE_INT;
update_fullscreen_scale_checkboxes(ui, ui->actionFullScreen_int);
}
void
MainWindow::on_actionFullScreen_int43_triggered()
{
video_fullscreen_scale = FULLSCR_SCALE_INT43;
update_fullscreen_scale_checkboxes(ui, ui->actionFullScreen_int43);
}
static void
update_greyscale_checkboxes(Ui::MainWindow *ui, QAction *selected, int value)
{
ui->actionRGB_Color->setChecked(ui->actionRGB_Color == selected);
ui->actionRGB_Grayscale->setChecked(ui->actionRGB_Grayscale == selected);
ui->actionAmber_monitor->setChecked(ui->actionAmber_monitor == selected);
ui->actionGreen_monitor->setChecked(ui->actionGreen_monitor == selected);
ui->actionWhite_monitor->setChecked(ui->actionWhite_monitor == selected);
startblit();
video_grayscale = value;
video_copy = (video_grayscale || invert_display) ? video_transform_copy : memcpy;
endblit();
device_force_redraw();
config_save();
}
void
MainWindow::on_actionRGB_Color_triggered()
{
update_greyscale_checkboxes(ui, ui->actionRGB_Color, 0);
}
void
MainWindow::on_actionRGB_Grayscale_triggered()
{
update_greyscale_checkboxes(ui, ui->actionRGB_Grayscale, 1);
}
void
MainWindow::on_actionAmber_monitor_triggered()
{
update_greyscale_checkboxes(ui, ui->actionAmber_monitor, 2);
}
void
MainWindow::on_actionGreen_monitor_triggered()
{
update_greyscale_checkboxes(ui, ui->actionGreen_monitor, 3);
}
void
MainWindow::on_actionWhite_monitor_triggered()
{
update_greyscale_checkboxes(ui, ui->actionWhite_monitor, 4);
}
static void
update_greyscale_type_checkboxes(Ui::MainWindow *ui, QAction *selected, int value)
{
ui->actionBT601_NTSC_PAL->setChecked(ui->actionBT601_NTSC_PAL == selected);
ui->actionBT709_HDTV->setChecked(ui->actionBT709_HDTV == selected);
ui->actionAverage->setChecked(ui->actionAverage == selected);
video_graytype = value;
device_force_redraw();
config_save();
}
void
MainWindow::on_actionBT601_NTSC_PAL_triggered()
{
update_greyscale_type_checkboxes(ui, ui->actionBT601_NTSC_PAL, 0);
}
void
MainWindow::on_actionBT709_HDTV_triggered()
{
update_greyscale_type_checkboxes(ui, ui->actionBT709_HDTV, 1);
}
void
MainWindow::on_actionAverage_triggered()
{
update_greyscale_type_checkboxes(ui, ui->actionAverage, 2);
}
void
MainWindow::on_actionAbout_Qt_triggered()
{
QApplication::aboutQt();
}
void
MainWindow::on_actionAbout_86Box_triggered()
{
QMessageBox msgBox;
msgBox.setTextFormat(Qt::RichText);
QString versioninfo;
#ifdef EMU_GIT_HASH
versioninfo = QString(" [%1]").arg(EMU_GIT_HASH);
#endif
#ifdef USE_DYNAREC
# ifdef USE_NEW_DYNAREC
# define DYNAREC_STR "new dynarec"
# else
# define DYNAREC_STR "old dynarec"
# endif
#else
# define DYNAREC_STR "no dynarec"
#endif
versioninfo.append(QString(" [%1, %2]").arg(QSysInfo::buildCpuArchitecture(), tr(DYNAREC_STR)));
msgBox.setText(QString("<b>%3%1%2</b>").arg(EMU_VERSION_FULL, versioninfo, tr("86Box v")));
msgBox.setWindowTitle("About 86Box");
msgBox.addButton("OK", QMessageBox::ButtonRole::AcceptRole);
const auto webSiteButton = msgBox.addButton(EMU_SITE, QMessageBox::ButtonRole::HelpRole);
webSiteButton->connect(webSiteButton, &QPushButton::released, []() {
QDesktopServices::openUrl(QUrl("https://" EMU_SITE));
});
#ifdef RELEASE_BUILD
msgBox.setIconPixmap(QIcon(":/settings/qt/icons/86Box-green.ico").pixmap(32, 32));
#elif defined ALPHA_BUILD
msgBox.setIconPixmap(QIcon(":/settings/qt/icons/86Box-red.ico").pixmap(32, 32));
#elif defined BETA_BUILD
msgBox.setIconPixmap(QIcon(":/settings/qt/icons/86Box-yellow.ico").pixmap(32, 32));
#else
msgBox.setIconPixmap(QIcon(":/settings/qt/icons/86Box-gray.ico").pixmap(32, 32));
#endif
msgBox.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
msgBox.exec();
}
void
MainWindow::on_actionDocumentation_triggered()
{
QDesktopServices::openUrl(QUrl(EMU_DOCS_URL));
}
void
MainWindow::on_actionCGA_PCjr_Tandy_EGA_S_VGA_overscan_triggered()
{
update_overscan = 1;
video_toggle_option(ui->actionCGA_PCjr_Tandy_EGA_S_VGA_overscan, &enable_overscan);
}
void
MainWindow::on_actionChange_contrast_for_monochrome_display_triggered()
{
vid_cga_contrast ^= 1;
cgapal_rebuild();
config_save();
}
void
MainWindow::on_actionForce_4_3_display_ratio_triggered()
{
video_toggle_option(ui->actionForce_4_3_display_ratio, &force_43);
}
void
MainWindow::on_actionAuto_pause_triggered()
{
do_auto_pause ^= 1;
ui->actionAuto_pause->setChecked(do_auto_pause > 0 ? true : false);
}
void
MainWindow::on_actionRemember_size_and_position_triggered()
{
window_remember ^= 1;
if (!video_fullscreen) {
window_w = ui->stackedWidget->width();
window_h = ui->stackedWidget->height();
if (!QApplication::platformName().contains("wayland")) {
window_x = geometry().x();
window_y = geometry().y();
}
for (int i = 1; i < MONITORS_NUM; i++) {
if (window_remember && renderers[i]) {
monitor_settings[i].mon_window_w = renderers[i]->geometry().width();
monitor_settings[i].mon_window_h = renderers[i]->geometry().height();
monitor_settings[i].mon_window_x = renderers[i]->geometry().x();
monitor_settings[i].mon_window_y = renderers[i]->geometry().y();
}
}
}
ui->actionRemember_size_and_position->setChecked(window_remember);
}
void
MainWindow::on_actionSpecify_dimensions_triggered()
{
SpecifyDimensions dialog(this);
dialog.setWindowModality(Qt::WindowModal);
dialog.exec();
}
void
MainWindow::on_actionHiDPI_scaling_triggered()
{
dpi_scale ^= 1;
ui->actionHiDPI_scaling->setChecked(dpi_scale);
emit resizeContents(monitors[0].mon_scrnsz_x, monitors[0].mon_scrnsz_y);
for (int i = 1; i < MONITORS_NUM; i++) {
if (renderers[i])
emit resizeContentsMonitor(monitors[i].mon_scrnsz_x, monitors[i].mon_scrnsz_y, i);
}
}
void
MainWindow::on_actionHide_status_bar_triggered()
{
auto w = ui->stackedWidget->width();
auto h = ui->stackedWidget->height();
hide_status_bar ^= 1;
ui->actionHide_status_bar->setChecked(hide_status_bar);
statusBar()->setVisible(!hide_status_bar);
if (vid_resize >= 2) {
setFixedSize(fixed_size_x, fixed_size_y + menuBar()->height() + (hide_status_bar ? 0 : statusBar()->height()) + (hide_tool_bar ? 0 : ui->toolBar->height()));
} else {
int vid_resize_orig = vid_resize;
vid_resize = 0;
emit resizeContents(w, h);
vid_resize = vid_resize_orig;
if (vid_resize == 1)
setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
}
}
void
MainWindow::on_actionHide_tool_bar_triggered()
{
auto w = ui->stackedWidget->width();
auto h = ui->stackedWidget->height();
hide_tool_bar ^= 1;
ui->actionHide_tool_bar->setChecked(hide_tool_bar);
ui->toolBar->setVisible(!hide_tool_bar);
if (vid_resize >= 2) {
setFixedSize(fixed_size_x, fixed_size_y + menuBar()->height() + (hide_status_bar ? 0 : statusBar()->height()) + (hide_tool_bar ? 0 : ui->toolBar->height()));
} else {
int vid_resize_orig = vid_resize;
vid_resize = 0;
emit resizeContents(w, h);
vid_resize = vid_resize_orig;
if (vid_resize == 1)
setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
}
}
void
MainWindow::on_actionUpdate_status_bar_icons_triggered()
{
update_icons ^= 1;
ui->actionUpdate_status_bar_icons->setChecked(update_icons);
/* Prevent icons staying when disabled during activity. */
status->clearActivity();
}
void
MainWindow::on_actionTake_screenshot_triggered()
{
startblit();
for (auto & monitor : monitors)
++monitor.mon_screenshots;
endblit();
device_force_redraw();
}
void
MainWindow::on_actionSound_gain_triggered()
{
SoundGain gain(this);
gain.exec();
}
void
MainWindow::setSendKeyboardInput(bool enabled)
{
send_keyboard_input = enabled;
}
void
MainWindow::updateUiPauseState()
{
const auto pause_icon = dopause ? QIcon(":/menuicons/qt/icons/run.ico") :
QIcon(":/menuicons/qt/icons/pause.ico");
const auto tooltip_text = dopause ? QString(tr("Resume execution")) :
QString(tr("Pause execution"));
ui->actionPause->setIcon(pause_icon);
ui->actionPause->setToolTip(tooltip_text);
}
void
MainWindow::on_actionPreferences_triggered()
{
ProgSettings progsettings(this);
progsettings.exec();
}
void
MainWindow::on_actionEnable_Discord_integration_triggered(bool checked)
{
enable_discord = checked;
#ifdef DISCORD
if (enable_discord) {
discord_init();
discord_update_activity(dopause);
} else
discord_close();
#endif
}
void
MainWindow::showSettings()
{
if (findChild<Settings *>() == nullptr)
ui->actionSettings->trigger();
}
void
MainWindow::hardReset()
{
ui->actionHard_Reset->trigger();
}
void
MainWindow::togglePause()
{
ui->actionPause->trigger();
}
void
MainWindow::changeEvent(QEvent *event)
{
#ifdef Q_OS_WINDOWS
if (event->type() == QEvent::LanguageChange) {
QApplication::setFont(QFont(ProgSettings::getFontName(lang_id), 9));
}
#endif
QWidget::changeEvent(event);
if (isVisible()) {
monitor_settings[0].mon_window_maximized = isMaximized();
config_save();
}
}
void
MainWindow::on_actionRenderer_options_triggered()
{
if (const auto dlg = ui->stackedWidget->getOptions(this)) {
if (dlg->exec() == QDialog::Accepted) {
for (int i = 1; i < MONITORS_NUM; i++) {
if (renderers[i] && renderers[i]->hasOptions())
renderers[i]->reloadOptions();
}
}
}
}
void
MainWindow::on_actionMCA_devices_triggered()
{
if (const auto dlg = new MCADeviceList(this))
dlg->exec();
}
void
MainWindow::on_actionShow_non_primary_monitors_triggered()
{
show_second_monitors = static_cast<int>(ui->actionShow_non_primary_monitors->isChecked());
if (show_second_monitors) {
for (int monitor_index = 1; monitor_index < MONITORS_NUM; monitor_index++) {
const auto &secondaryRenderer = renderers[monitor_index];
if (!renderers[monitor_index])
continue;
secondaryRenderer->show();
if (window_remember) {
secondaryRenderer->setGeometry(monitor_settings[monitor_index].mon_window_x < 120 ? 120 : monitor_settings[monitor_index].mon_window_x,
monitor_settings[monitor_index].mon_window_y < 120 ? 120 : monitor_settings[monitor_index].mon_window_y,
monitor_settings[monitor_index].mon_window_w > 2048 ? 2048 : monitor_settings[monitor_index].mon_window_w,
monitor_settings[monitor_index].mon_window_h > 2048 ? 2048 : monitor_settings[monitor_index].mon_window_h);
}
secondaryRenderer->switchRenderer(static_cast<RendererStack::Renderer>(vid_api));
ui->stackedWidget->switchRenderer(static_cast<RendererStack::Renderer>(vid_api));
}
} else {
for (int monitor_index = 1; monitor_index < MONITORS_NUM; monitor_index++) {
auto &secondaryRenderer = renderers[monitor_index];
if (!renderers[monitor_index])
continue;
secondaryRenderer->hide();
if (window_remember && renderers[monitor_index]) {
monitor_settings[monitor_index].mon_window_w = renderers[monitor_index]->geometry().width();
monitor_settings[monitor_index].mon_window_h = renderers[monitor_index]->geometry().height();
monitor_settings[monitor_index].mon_window_x = renderers[monitor_index]->geometry().x();
monitor_settings[monitor_index].mon_window_y = renderers[monitor_index]->geometry().y();
}
}
}
}
void
MainWindow::on_actionOpen_screenshots_folder_triggered()
{
static_cast<void>(QDir(QString(usr_path) + QString("/screenshots/")).mkpath("."));
QDesktopServices::openUrl(QUrl(QString("file:///") + usr_path + QString("/screenshots/")));
}
void
MainWindow::on_actionApply_fullscreen_stretch_mode_when_maximized_triggered(bool checked)
{
video_fullscreen_scale_maximized = checked;
const auto widget = ui->stackedWidget->currentWidget();
ui->stackedWidget->onResize(widget->width(), widget->height());
for (int i = 1; i < MONITORS_NUM; i++) {
if (renderers[i])
renderers[i]->onResize(renderers[i]->width(), renderers[i]->height());
}
device_force_redraw();
config_save();
}
void MainWindow::on_actionCursor_Puck_triggered()
{
tablet_tool_type = 0;
config_save();
}
void MainWindow::on_actionPen_triggered()
{
tablet_tool_type = 1;
config_save();
}
void MainWindow::on_actionACPI_Shutdown_triggered()
{
acpi_pwrbut_pressed = 1;
}
``` | /content/code_sandbox/src/qt/qt_mainwindow.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 16,519 |
```c++
#ifndef QT_SETTINGSOTHERPERIPHERALS_HPP
#define QT_SETTINGSOTHERPERIPHERALS_HPP
#include <QWidget>
namespace Ui {
class SettingsOtherPeripherals;
}
class SettingsOtherPeripherals : public QWidget {
Q_OBJECT
public:
explicit SettingsOtherPeripherals(QWidget *parent = nullptr);
~SettingsOtherPeripherals();
void save();
public slots:
void onCurrentMachineChanged(int machineId);
private slots:
void on_pushButtonConfigureCard4_clicked();
void on_comboBoxCard4_currentIndexChanged(int index);
void on_pushButtonConfigureCard3_clicked();
void on_comboBoxCard3_currentIndexChanged(int index);
void on_pushButtonConfigureCard2_clicked();
void on_comboBoxCard2_currentIndexChanged(int index);
void on_pushButtonConfigureCard1_clicked();
void on_comboBoxCard1_currentIndexChanged(int index);
void on_pushButtonConfigureRTC_clicked();
void on_comboBoxRTC_currentIndexChanged(int index);
void on_checkBoxUnitTester_stateChanged(int arg1);
void on_pushButtonConfigureUT_clicked();
void on_pushButtonConfigureKeyCard_clicked();
void on_checkBoxKeyCard_stateChanged(int arg1);
private:
Ui::SettingsOtherPeripherals *ui;
int machineId { 0 };
};
#endif // QT_SETTINGSOTHERPERIPHERALS_HPP
``` | /content/code_sandbox/src/qt/qt_settingsotherperipherals.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 265 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Header file for Windows VM-managers native messages filter
*
*
*
* Authors: Teemu Korhonen
*
*/
#ifndef QT_WINDOWSMANAGERFILTER_HPP
#define QT_WINDOWSMANAGERFILTER_HPP
#include <QObject>
#include <QAbstractNativeEventFilter>
#include <QByteArray>
#include <QEvent>
#if QT_VERSION_MAJOR >= 6
# define result_t qintptr
#else
# define result_t long
#endif
/*
* Filters native events for messages from VM-manager and
* window blocked events to notify about open modal dialogs.
*/
class WindowsManagerFilter : public QObject, public QAbstractNativeEventFilter {
Q_OBJECT
public:
bool nativeEventFilter(const QByteArray &eventType, void *message, result_t *result) override;
signals:
void pause();
void ctrlaltdel();
void showsettings();
void reset();
void request_shutdown();
void force_shutdown();
void dialogstatus(bool open);
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
};
#endif
``` | /content/code_sandbox/src/qt/qt_winmanagerfilter.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 290 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Program settings UI module.
*
*
*
* Authors: Miran Grca <mgrca8@gmail.com>
* Cacodemon345
*
*/
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "86box/hdd.h"
#include "86box/scsi.h"
#include "qt_settings_bus_tracking.hpp"
SettingsBusTracking::SettingsBusTracking()
{
mfm_tracking = 0x0000000000000000ULL;
esdi_tracking = 0x0000000000000000ULL;
xta_tracking = 0x0000000000000000ULL;
for (uint8_t i = 0; i < 4; i++)
ide_tracking[i] = 0x0000000000000000ULL;
for (uint8_t i = 0; i < 32; i++)
scsi_tracking[i] = 0x0000000000000000ULL;
}
uint8_t
SettingsBusTracking::next_free_mfm_channel()
{
if ((mfm_tracking & 0xff00ULL) && !(mfm_tracking & 0x00ffULL))
return 1;
if (!(mfm_tracking & 0xff00ULL) && (mfm_tracking & 0x00ffULL))
return 0;
return CHANNEL_NONE;
}
uint8_t
SettingsBusTracking::next_free_esdi_channel()
{
if ((esdi_tracking & 0xff00ULL) && !(esdi_tracking & 0x00ffULL))
return 1;
if (!(esdi_tracking & 0xff00ULL) && (esdi_tracking & 0x00ffULL))
return 0;
return CHANNEL_NONE;
}
uint8_t
SettingsBusTracking::next_free_xta_channel()
{
if ((xta_tracking & 0xff00ULL) && !(xta_tracking & 0x00ffULL))
return 1;
if (!(xta_tracking & 0xff00ULL) && (xta_tracking & 0x00ffULL))
return 0;
return CHANNEL_NONE;
}
uint8_t
SettingsBusTracking::next_free_ide_channel()
{
int element;
uint64_t mask;
uint8_t ret = CHANNEL_NONE;
for (uint8_t i = 0; i < 32; i++) {
element = ((i << 3) >> 6);
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (!(ide_tracking[element] & mask)) {
ret = (uint8_t) i;
break;
}
}
return ret;
}
uint8_t
SettingsBusTracking::next_free_scsi_id()
{
int element;
uint64_t mask;
uint8_t ret = CHANNEL_NONE;
for (uint8_t i = 0; i < (SCSI_BUS_MAX * SCSI_ID_MAX); i++) {
element = ((i << 3) >> 6);
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (!(scsi_tracking[element] & mask)) {
ret = (uint8_t) i;
break;
}
}
return ret;
}
int
SettingsBusTracking::mfm_bus_full()
{
uint64_t mask;
uint8_t count = 0;
for (uint8_t i = 0; i < 2; i++) {
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (mfm_tracking & mask)
count++;
}
return (count == 2);
}
int
SettingsBusTracking::esdi_bus_full()
{
uint64_t mask;
uint8_t count = 0;
for (uint8_t i = 0; i < 2; i++) {
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (esdi_tracking & mask)
count++;
}
return (count == 2);
}
int
SettingsBusTracking::xta_bus_full()
{
uint64_t mask;
uint8_t count = 0;
for (uint8_t i = 0; i < 2; i++) {
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (xta_tracking & mask)
count++;
}
return (count == 2);
}
int
SettingsBusTracking::ide_bus_full()
{
int element;
uint64_t mask;
uint8_t count = 0;
for (uint8_t i = 0; i < 32; i++) {
element = ((i << 3) >> 6);
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (ide_tracking[element] & mask)
count++;
}
return (count == 32);
}
int
SettingsBusTracking::scsi_bus_full()
{
int element;
uint64_t mask;
uint8_t count = 0;
for (uint8_t i = 0; i < (SCSI_BUS_MAX * SCSI_ID_MAX); i++) {
element = ((i << 3) >> 6);
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (scsi_tracking[element] & mask)
count++;
}
return (count == 64);
}
QList<int> SettingsBusTracking::busChannelsInUse(const int bus) {
QList<int> channelsInUse;
int element;
uint64_t mask;
switch (bus) {
case HDD_BUS_MFM:
for (uint8_t i = 0; i < 32; i++) {
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (mfm_tracking & mask)
channelsInUse.append(i);
}
break;
case HDD_BUS_ESDI:
for (uint8_t i = 0; i < 32; i++) {
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (esdi_tracking & mask)
channelsInUse.append(i);
}
break;
case HDD_BUS_XTA:
for (uint8_t i = 0; i < 32; i++) {
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (xta_tracking & mask)
channelsInUse.append(i);
}
break;
case HDD_BUS_IDE:
for (uint8_t i = 0; i < 32; i++) {
element = ((i << 3) >> 6);
mask = ((uint64_t) 0xffULL) << ((uint64_t) ((i << 3) & 0x3f));
if (ide_tracking[element] & mask)
channelsInUse.append(i);
}
break;
case HDD_BUS_ATAPI:
for (uint8_t i = 0; i < 32; i++) {
element = ((i << 3) >> 6);
mask = ((uint64_t) 0xffULL) << ((uint64_t) ((i << 3) & 0x3f));
if (ide_tracking[element] & mask)
channelsInUse.append(i);
}
break;
case HDD_BUS_SCSI:
for (uint8_t i = 0; i < (SCSI_BUS_MAX * SCSI_ID_MAX); i++) {
element = ((i << 3) >> 6);
mask = 0xffULL << ((uint64_t) ((i << 3) & 0x3f));
if (scsi_tracking[element] & mask)
channelsInUse.append(i);
}
break;
default:
break;
}
return channelsInUse;
}
void
SettingsBusTracking::device_track(int set, uint8_t dev_type, int bus, int channel)
{
int element;
uint64_t mask;
switch (bus) {
case HDD_BUS_MFM:
mask = ((uint64_t) dev_type) << ((uint64_t) ((channel << 3) & 0x3f));
if (set)
mfm_tracking |= mask;
else
mfm_tracking &= ~mask;
break;
case HDD_BUS_ESDI:
mask = ((uint64_t) dev_type) << ((uint64_t) ((channel << 3) & 0x3f));
if (set)
esdi_tracking |= mask;
else
esdi_tracking &= ~mask;
break;
case HDD_BUS_XTA:
mask = ((uint64_t) dev_type) << ((uint64_t) ((channel << 3) & 0x3f));
if (set)
xta_tracking |= mask;
else
xta_tracking &= ~mask;
break;
case HDD_BUS_IDE:
case HDD_BUS_ATAPI:
element = ((channel << 3) >> 6);
mask = ((uint64_t) dev_type) << ((uint64_t) ((channel << 3) & 0x3f));
if (set)
ide_tracking[element] |= mask;
else
ide_tracking[element] &= ~mask;
break;
case HDD_BUS_SCSI:
element = ((channel << 3) >> 6);
mask = ((uint64_t) dev_type) << ((uint64_t) ((channel << 3) & 0x3f));
if (set)
scsi_tracking[element] |= mask;
else
scsi_tracking[element] &= ~mask;
break;
}
}
``` | /content/code_sandbox/src/qt/qt_settings_bus_tracking.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,277 |
```c++
#include "qt_mcadevicelist.hpp"
#include "ui_qt_mcadevicelist.h"
extern "C" {
#include <86box/86box.h>
#include <86box/video.h>
#include <86box/mca.h>
#include <86box/plat.h>
}
MCADeviceList::MCADeviceList(QWidget *parent)
: QDialog(parent)
, ui(new Ui::MCADeviceList)
{
ui->setupUi(this);
startblit();
if (mca_get_nr_cards() == 0) {
ui->listWidget->addItem(QObject::tr("No MCA devices."));
ui->listWidget->setDisabled(true);
} else {
for (int i = 0; i < mca_get_nr_cards(); i++) {
uint32_t deviceId = (mca_read_index(0x00, i) | (mca_read_index(0x01, i) << 8));
if (deviceId != 0xFFFF) {
QString hexRepresentation = QString::asprintf("%04X", deviceId);
ui->listWidget->addItem(QString("Slot %1: 0x%2 (@%3.ADF)").arg(i + 1).arg(hexRepresentation, hexRepresentation));
}
}
}
endblit();
}
MCADeviceList::~MCADeviceList()
{
delete ui;
}
``` | /content/code_sandbox/src/qt/qt_mcadevicelist.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 290 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Joystick configuration UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
*
*/
#include "qt_machinestatus.hpp"
extern "C" {
#define EMU_CPU_H // superhack - don't want timer.h to include cpu.h here, and some combo is preventing a compile
extern uint64_t tsc;
#include <86box/hdd.h>
#include <86box/timer.h>
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/cartridge.h>
#include <86box/cassette.h>
#include <86box/cdrom.h>
#include <86box/cdrom_interface.h>
#include <86box/fdd.h>
#include <86box/hdc.h>
#include <86box/scsi.h>
#include <86box/scsi_device.h>
#include <86box/zip.h>
#include <86box/mo.h>
#include <86box/plat.h>
#include <86box/machine.h>
#include <86box/thread.h>
#include <86box/network.h>
#include <86box/ui.h>
#include <86box/machine_status.h>
};
#include <QIcon>
#include <QPicture>
#include <QLabel>
#include <QTimer>
#include <QStatusBar>
#include <QMenu>
#include <QScreen>
#include "qt_mediamenu.hpp"
#include "qt_mainwindow.hpp"
#include "qt_soundgain.hpp"
#include "qt_progsettings.hpp"
#include <array>
extern MainWindow *main_window;
namespace {
struct PixmapSetActive {
QPixmap normal;
QPixmap active;
void load(const QString &basePath);
};
struct PixmapSetEmpty {
QPixmap normal;
QPixmap empty;
void load(const QString &basePath);
};
struct PixmapSetEmptyActive {
QPixmap normal;
QPixmap active;
QPixmap empty;
QPixmap empty_active;
void load(QString basePath);
};
struct Pixmaps {
PixmapSetEmpty cartridge;
PixmapSetEmptyActive cassette;
PixmapSetEmptyActive floppy_disabled;
PixmapSetEmptyActive floppy_525;
PixmapSetEmptyActive floppy_35;
PixmapSetEmptyActive cdrom;
PixmapSetEmptyActive zip;
PixmapSetEmptyActive mo;
PixmapSetActive hd;
PixmapSetEmptyActive net;
QPixmap sound;
};
struct StateActive {
std::unique_ptr<QLabel> label;
PixmapSetActive *pixmaps = nullptr;
bool active = false;
void setActive(bool b)
{
if (!label || b == active)
return;
active = b;
refresh();
}
void refresh()
{
if (!label)
return;
label->setPixmap(active ? pixmaps->active : pixmaps->normal);
}
};
struct StateEmpty {
std::unique_ptr<QLabel> label;
PixmapSetEmpty *pixmaps = nullptr;
bool empty = false;
void setEmpty(bool e)
{
if (!label || e == empty)
return;
empty = e;
refresh();
}
void refresh()
{
if (!label)
return;
label->setPixmap(empty ? pixmaps->empty : pixmaps->normal);
}
};
struct StateEmptyActive {
std::unique_ptr<QLabel> label;
PixmapSetEmptyActive *pixmaps = nullptr;
bool empty = false;
bool active = false;
void setActive(bool b)
{
if (!label || b == active)
return;
active = b;
refresh();
}
void setEmpty(bool b)
{
if (!label || b == empty)
return;
empty = b;
refresh();
}
void refresh()
{
if (!label)
return;
if (empty) {
label->setPixmap(active ? pixmaps->empty_active : pixmaps->empty);
} else {
label->setPixmap(active ? pixmaps->active : pixmaps->normal);
}
}
};
static QSize pixmap_size(16, 16);
static const QString pixmap_empty = QStringLiteral("_empty");
static const QString pixmap_active = QStringLiteral("_active");
static const QString pixmap_empty_active = QStringLiteral("_empty_active");
void
PixmapSetEmpty::load(const QString &basePath)
{
normal = ProgSettings::loadIcon(basePath.arg(QStringLiteral(""))).pixmap(pixmap_size);
empty = ProgSettings::loadIcon(basePath.arg(pixmap_empty)).pixmap(pixmap_size);
}
void
PixmapSetActive::load(const QString &basePath)
{
normal = ProgSettings::loadIcon(basePath.arg(QStringLiteral(""))).pixmap(pixmap_size);
active = ProgSettings::loadIcon(basePath.arg(pixmap_active)).pixmap(pixmap_size);
}
void
PixmapSetEmptyActive::load(QString basePath)
{
normal = ProgSettings::loadIcon(basePath.arg(QStringLiteral(""))).pixmap(pixmap_size);
active = ProgSettings::loadIcon(basePath.arg(pixmap_active)).pixmap(pixmap_size);
empty = ProgSettings::loadIcon(basePath.arg(pixmap_empty)).pixmap(pixmap_size);
empty_active = ProgSettings::loadIcon(basePath.arg(pixmap_empty_active)).pixmap(pixmap_size);
}
}
struct MachineStatus::States {
Pixmaps pixmaps;
States(QObject *parent)
{
pixmaps.cartridge.load("/cartridge%1.ico");
pixmaps.cassette.load("/cassette%1.ico");
pixmaps.floppy_disabled.normal = ProgSettings::loadIcon(QStringLiteral("/floppy_disabled.ico")).pixmap(pixmap_size);
pixmaps.floppy_disabled.active = pixmaps.floppy_disabled.normal;
pixmaps.floppy_disabled.empty = pixmaps.floppy_disabled.normal;
pixmaps.floppy_disabled.empty_active = pixmaps.floppy_disabled.normal;
pixmaps.floppy_525.load("/floppy_525%1.ico");
pixmaps.floppy_35.load("/floppy_35%1.ico");
pixmaps.cdrom.load("/cdrom%1.ico");
pixmaps.zip.load("/zip%1.ico");
pixmaps.mo.load("/mo%1.ico");
pixmaps.hd.load("/hard_disk%1.ico");
pixmaps.net.load("/network%1.ico");
pixmaps.sound = ProgSettings::loadIcon("/sound.ico").pixmap(pixmap_size);
cartridge[0].pixmaps = &pixmaps.cartridge;
cartridge[1].pixmaps = &pixmaps.cartridge;
cassette.pixmaps = &pixmaps.cassette;
for (auto &f : fdd) {
f.pixmaps = &pixmaps.floppy_disabled;
}
for (auto &c : cdrom) {
c.pixmaps = &pixmaps.cdrom;
}
for (auto &z : zip) {
z.pixmaps = &pixmaps.zip;
}
for (auto &m : mo) {
m.pixmaps = &pixmaps.mo;
}
for (auto &h : hdds) {
h.pixmaps = &pixmaps.hd;
}
for (auto &n : net) {
n.pixmaps = &pixmaps.net;
}
}
std::array<StateEmpty, 2> cartridge;
StateEmptyActive cassette;
std::array<StateEmptyActive, FDD_NUM> fdd;
std::array<StateEmptyActive, CDROM_NUM> cdrom;
std::array<StateEmptyActive, ZIP_NUM> zip;
std::array<StateEmptyActive, MO_NUM> mo;
std::array<StateActive, HDD_BUS_USB> hdds;
std::array<StateEmptyActive, NET_CARD_MAX> net;
std::unique_ptr<ClickableLabel> sound;
std::unique_ptr<QLabel> text;
};
MachineStatus::MachineStatus(QObject *parent)
: QObject(parent)
, refreshTimer(new QTimer(this))
{
d = std::make_unique<MachineStatus::States>(this);
connect(refreshTimer, &QTimer::timeout, this, &MachineStatus::refreshIcons);
refreshTimer->start(75);
}
MachineStatus::~MachineStatus() = default;
bool
MachineStatus::hasCassette()
{
return cassette_enable > 0 ? true : false;
}
bool
MachineStatus::hasIDE()
{
return (machine_has_flags(machine, MACHINE_IDE_QUAD) > 0) || other_ide_present;
}
bool
MachineStatus::hasSCSI()
{
return (machine_has_flags(machine, MACHINE_SCSI) > 0) || other_scsi_present;
}
void
MachineStatus::iterateFDD(const std::function<void(int)> &cb)
{
for (int i = 0; i < FDD_NUM; ++i) {
if (fdd_get_type(i) != 0) {
cb(i);
}
}
}
void
MachineStatus::iterateCDROM(const std::function<void(int)> &cb)
{
auto hdc_name = QString(hdc_get_internal_name(hdc_current[0]));
for (size_t i = 0; i < CDROM_NUM; i++) {
/* Could be Internal or External IDE.. */
if ((cdrom[i].bus_type == CDROM_BUS_ATAPI) && !hasIDE() &&
(hdc_name.left(3) != QStringLiteral("ide")) &&
(hdc_name.left(5) != QStringLiteral("xtide")) &&
(hdc_name.left(5) != QStringLiteral("mcide")))
continue;
if ((cdrom[i].bus_type == CDROM_BUS_SCSI) && !hasSCSI() &&
(scsi_card_current[0] == 0) && (scsi_card_current[1] == 0) &&
(scsi_card_current[2] == 0) && (scsi_card_current[3] == 0))
continue;
if ((cdrom[i].bus_type == CDROM_BUS_MITSUMI) && (cdrom_interface_current == 0))
continue;
if (cdrom[i].bus_type != 0) {
cb(i);
}
}
}
void
MachineStatus::iterateZIP(const std::function<void(int)> &cb)
{
auto hdc_name = QString(hdc_get_internal_name(hdc_current[0]));
for (size_t i = 0; i < ZIP_NUM; i++) {
/* Could be Internal or External IDE.. */
if ((zip_drives[i].bus_type == ZIP_BUS_ATAPI) && !hasIDE() &&
(hdc_name.left(3) != QStringLiteral("ide")) &&
(hdc_name.left(5) != QStringLiteral("xtide")) &&
(hdc_name.left(5) != QStringLiteral("mcide")))
continue;
if ((zip_drives[i].bus_type == ZIP_BUS_SCSI) && !hasSCSI() &&
(scsi_card_current[0] == 0) && (scsi_card_current[1] == 0) &&
(scsi_card_current[2] == 0) && (scsi_card_current[3] == 0))
continue;
if (zip_drives[i].bus_type != 0) {
cb(i);
}
}
}
void
MachineStatus::iterateMO(const std::function<void(int)> &cb)
{
auto hdc_name = QString(hdc_get_internal_name(hdc_current[0]));
for (size_t i = 0; i < MO_NUM; i++) {
/* Could be Internal or External IDE.. */
if ((mo_drives[i].bus_type == MO_BUS_ATAPI) && !hasIDE() &&
(hdc_name.left(3) != QStringLiteral("ide")) &&
(hdc_name.left(5) != QStringLiteral("xtide")) &&
(hdc_name.left(5) != QStringLiteral("mcide")))
continue;
if ((mo_drives[i].bus_type == MO_BUS_SCSI) && !hasSCSI() &&
(scsi_card_current[0] == 0) && (scsi_card_current[1] == 0) &&
(scsi_card_current[2] == 0) && (scsi_card_current[3] == 0))
continue;
if (mo_drives[i].bus_type != 0) {
cb(i);
}
}
}
void
MachineStatus::iterateNIC(const std::function<void(int)> &cb)
{
for (int i = 0; i < NET_CARD_MAX; i++) {
if (network_dev_available(i)) {
cb(i);
}
}
}
static int
hdd_count(int bus)
{
int c = 0;
for (uint8_t i = 0; i < HDD_NUM; i++) {
if (hdd[i].bus == bus) {
c++;
}
}
return c;
}
void
MachineStatus::refreshIcons()
{
/* Check if icons should show activity. */
if (!update_icons)
return;
for (size_t i = 0; i < FDD_NUM; ++i) {
d->fdd[i].setActive(machine_status.fdd[i].active);
d->fdd[i].setEmpty(machine_status.fdd[i].empty);
}
for (size_t i = 0; i < CDROM_NUM; ++i) {
d->cdrom[i].setActive(machine_status.cdrom[i].active);
if (machine_status.cdrom[i].active)
ui_sb_update_icon(SB_CDROM | i, 0);
d->cdrom[i].setEmpty(machine_status.cdrom[i].empty);
}
for (size_t i = 0; i < ZIP_NUM; i++) {
d->zip[i].setActive(machine_status.zip[i].active);
if (machine_status.zip[i].active)
ui_sb_update_icon(SB_ZIP | i, 0);
d->zip[i].setEmpty(machine_status.zip[i].empty);
}
for (size_t i = 0; i < MO_NUM; i++) {
d->mo[i].setActive(machine_status.mo[i].active);
if (machine_status.mo[i].active)
ui_sb_update_icon(SB_MO | i, 0);
d->mo[i].setEmpty(machine_status.mo[i].empty);
}
d->cassette.setEmpty(machine_status.cassette.empty);
for (size_t i = 0; i < HDD_BUS_USB; i++) {
d->hdds[i].setActive(machine_status.hdd[i].active);
if (machine_status.hdd[i].active)
ui_sb_update_icon(SB_HDD | i, 0);
}
for (size_t i = 0; i < NET_CARD_MAX; i++) {
d->net[i].setActive(machine_status.net[i].active);
d->net[i].setEmpty(machine_status.net[i].empty);
}
for (int i = 0; i < 2; ++i) {
d->cartridge[i].setEmpty(machine_status.cartridge[i].empty);
}
}
void
MachineStatus::clearActivity()
{
for (auto &fdd : d->fdd)
fdd.setActive(false);
for (auto &cdrom : d->cdrom)
cdrom.setActive(false);
for (auto &zip : d->zip)
zip.setActive(false);
for (auto &mo : d->mo)
mo.setActive(false);
for (auto &hdd : d->hdds)
hdd.setActive(false);
for (auto &net : d->net)
net.setActive(false);
}
void
MachineStatus::refresh(QStatusBar *sbar)
{
bool has_mfm = machine_has_flags(machine, MACHINE_MFM) > 0;
bool has_xta = machine_has_flags(machine, MACHINE_XTA) > 0;
bool has_esdi = machine_has_flags(machine, MACHINE_ESDI) > 0;
int c_mfm = hdd_count(HDD_BUS_MFM);
int c_esdi = hdd_count(HDD_BUS_ESDI);
int c_xta = hdd_count(HDD_BUS_XTA);
int c_ide = hdd_count(HDD_BUS_IDE);
int c_atapi = hdd_count(HDD_BUS_ATAPI);
int c_scsi = hdd_count(HDD_BUS_SCSI);
sbar->removeWidget(d->cassette.label.get());
for (int i = 0; i < 2; ++i) {
sbar->removeWidget(d->cartridge[i].label.get());
}
for (size_t i = 0; i < FDD_NUM; ++i) {
sbar->removeWidget(d->fdd[i].label.get());
}
for (size_t i = 0; i < CDROM_NUM; i++) {
sbar->removeWidget(d->cdrom[i].label.get());
}
for (size_t i = 0; i < ZIP_NUM; i++) {
sbar->removeWidget(d->zip[i].label.get());
}
for (size_t i = 0; i < MO_NUM; i++) {
sbar->removeWidget(d->mo[i].label.get());
}
for (size_t i = 0; i < HDD_BUS_USB; i++) {
sbar->removeWidget(d->hdds[i].label.get());
}
for (size_t i = 0; i < NET_CARD_MAX; i++) {
sbar->removeWidget(d->net[i].label.get());
}
sbar->removeWidget(d->sound.get());
if (cassette_enable) {
d->cassette.label = std::make_unique<ClickableLabel>();
d->cassette.setEmpty(QString(cassette_fname).isEmpty());
d->cassette.refresh();
connect((ClickableLabel *) d->cassette.label.get(), &ClickableLabel::clicked, [](QPoint pos) {
MediaMenu::ptr->cassetteMenu->popup(pos - QPoint(0, MediaMenu::ptr->cassetteMenu->sizeHint().height()));
});
connect((ClickableLabel *) d->cassette.label.get(), &ClickableLabel::dropped, [](QString str) {
MediaMenu::ptr->cassetteMount(str, false);
});
d->cassette.label->setToolTip(MediaMenu::ptr->cassetteMenu->title());
d->cassette.label->setAcceptDrops(true);
sbar->addWidget(d->cassette.label.get());
}
if (machine_has_cartridge(machine)) {
for (int i = 0; i < 2; ++i) {
d->cartridge[i].label = std::make_unique<ClickableLabel>();
d->cartridge[i].setEmpty(QString(cart_fns[i]).isEmpty());
d->cartridge[i].refresh();
connect((ClickableLabel *) d->cartridge[i].label.get(), &ClickableLabel::clicked, [i](QPoint pos) {
MediaMenu::ptr->cartridgeMenus[i]->popup(pos - QPoint(0, MediaMenu::ptr->cartridgeMenus[i]->sizeHint().height()));
});
connect((ClickableLabel *) d->cartridge[i].label.get(), &ClickableLabel::dropped, [i](QString str) {
MediaMenu::ptr->cartridgeMount(i, str);
});
d->cartridge[i].label->setToolTip(MediaMenu::ptr->cartridgeMenus[i]->title());
d->cartridge[i].label->setAcceptDrops(true);
sbar->addWidget(d->cartridge[i].label.get());
}
}
iterateFDD([this, sbar](int i) {
int t = fdd_get_type(i);
if (t == 0) {
d->fdd[i].pixmaps = &d->pixmaps.floppy_disabled;
} else if (t >= 1 && t <= 6) {
d->fdd[i].pixmaps = &d->pixmaps.floppy_525;
} else {
d->fdd[i].pixmaps = &d->pixmaps.floppy_35;
}
d->fdd[i].label = std::make_unique<ClickableLabel>();
d->fdd[i].setEmpty(QString(floppyfns[i]).isEmpty());
d->fdd[i].setActive(false);
d->fdd[i].refresh();
connect((ClickableLabel *) d->fdd[i].label.get(), &ClickableLabel::clicked, [i](QPoint pos) {
MediaMenu::ptr->floppyMenus[i]->popup(pos - QPoint(0, MediaMenu::ptr->floppyMenus[i]->sizeHint().height()));
});
connect((ClickableLabel *) d->fdd[i].label.get(), &ClickableLabel::dropped, [i](QString str) {
MediaMenu::ptr->floppyMount(i, str, false);
});
d->fdd[i].label->setToolTip(MediaMenu::ptr->floppyMenus[i]->title());
d->fdd[i].label->setAcceptDrops(true);
sbar->addWidget(d->fdd[i].label.get());
});
iterateCDROM([this, sbar](int i) {
d->cdrom[i].label = std::make_unique<ClickableLabel>();
d->cdrom[i].setEmpty(QString(cdrom[i].image_path).isEmpty());
d->cdrom[i].setActive(false);
d->cdrom[i].refresh();
connect((ClickableLabel *) d->cdrom[i].label.get(), &ClickableLabel::clicked, [i](QPoint pos) {
MediaMenu::ptr->cdromMenus[i]->popup(pos - QPoint(0, MediaMenu::ptr->cdromMenus[i]->sizeHint().height()));
});
connect((ClickableLabel *) d->cdrom[i].label.get(), &ClickableLabel::dropped, [i](QString str) {
MediaMenu::ptr->cdromMount(i, str);
});
d->cdrom[i].label->setToolTip(MediaMenu::ptr->cdromMenus[i]->title());
d->cdrom[i].label->setAcceptDrops(true);
sbar->addWidget(d->cdrom[i].label.get());
});
iterateZIP([this, sbar](int i) {
d->zip[i].label = std::make_unique<ClickableLabel>();
d->zip[i].setEmpty(QString(zip_drives[i].image_path).isEmpty());
d->zip[i].setActive(false);
d->zip[i].refresh();
connect((ClickableLabel *) d->zip[i].label.get(), &ClickableLabel::clicked, [i](QPoint pos) {
MediaMenu::ptr->zipMenus[i]->popup(pos - QPoint(0, MediaMenu::ptr->zipMenus[i]->sizeHint().height()));
});
connect((ClickableLabel *) d->zip[i].label.get(), &ClickableLabel::dropped, [i](QString str) {
MediaMenu::ptr->zipMount(i, str, false);
});
d->zip[i].label->setToolTip(MediaMenu::ptr->zipMenus[i]->title());
d->zip[i].label->setAcceptDrops(true);
sbar->addWidget(d->zip[i].label.get());
});
iterateMO([this, sbar](int i) {
d->mo[i].label = std::make_unique<ClickableLabel>();
d->mo[i].setEmpty(QString(mo_drives[i].image_path).isEmpty());
d->mo[i].setActive(false);
d->mo[i].refresh();
connect((ClickableLabel *) d->mo[i].label.get(), &ClickableLabel::clicked, [i](QPoint pos) {
MediaMenu::ptr->moMenus[i]->popup(pos - QPoint(0, MediaMenu::ptr->moMenus[i]->sizeHint().height()));
});
connect((ClickableLabel *) d->mo[i].label.get(), &ClickableLabel::dropped, [i](QString str) {
MediaMenu::ptr->moMount(i, str, false);
});
d->mo[i].label->setToolTip(MediaMenu::ptr->moMenus[i]->title());
d->mo[i].label->setAcceptDrops(true);
sbar->addWidget(d->mo[i].label.get());
});
iterateNIC([this, sbar](int i) {
d->net[i].label = std::make_unique<ClickableLabel>();
d->net[i].setEmpty(!network_is_connected(i));
d->net[i].setActive(false);
d->net[i].refresh();
d->net[i].label->setToolTip(MediaMenu::ptr->netMenus[i]->title());
connect((ClickableLabel *) d->net[i].label.get(), &ClickableLabel::clicked, [i](QPoint pos) {
MediaMenu::ptr->netMenus[i]->popup(pos - QPoint(0, MediaMenu::ptr->netMenus[i]->sizeHint().height()));
});
sbar->addWidget(d->net[i].label.get());
});
auto hdc_name = QString(hdc_get_internal_name(hdc_current[0]));
if ((has_mfm || (hdc_name.left(5) == QStringLiteral("st506"))) && (c_mfm > 0)) {
d->hdds[HDD_BUS_MFM].label = std::make_unique<QLabel>();
d->hdds[HDD_BUS_MFM].setActive(false);
d->hdds[HDD_BUS_MFM].refresh();
d->hdds[HDD_BUS_MFM].label->setToolTip(tr("Hard disk (%1)").arg("MFM/RLL"));
sbar->addWidget(d->hdds[HDD_BUS_MFM].label.get());
}
if ((has_esdi || (hdc_name.left(4) == QStringLiteral("esdi"))) && (c_esdi > 0)) {
d->hdds[HDD_BUS_ESDI].label = std::make_unique<QLabel>();
d->hdds[HDD_BUS_ESDI].setActive(false);
d->hdds[HDD_BUS_ESDI].refresh();
d->hdds[HDD_BUS_ESDI].label->setToolTip(tr("Hard disk (%1)").arg("ESDI"));
sbar->addWidget(d->hdds[HDD_BUS_ESDI].label.get());
}
if ((has_xta || (hdc_name.left(3) == QStringLiteral("xta"))) && (c_xta > 0)) {
d->hdds[HDD_BUS_XTA].label = std::make_unique<QLabel>();
d->hdds[HDD_BUS_XTA].setActive(false);
d->hdds[HDD_BUS_XTA].refresh();
d->hdds[HDD_BUS_XTA].label->setToolTip(tr("Hard disk (%1)").arg("XTA"));
sbar->addWidget(d->hdds[HDD_BUS_XTA].label.get());
}
if (hasIDE() || (hdc_name.left(5) == QStringLiteral("xtide")) ||
(hdc_name.left(5) == QStringLiteral("mcide")) ||
(hdc_name.left(3) == QStringLiteral("ide"))) {
if (c_ide > 0) {
d->hdds[HDD_BUS_IDE].label = std::make_unique<QLabel>();
d->hdds[HDD_BUS_IDE].setActive(false);
d->hdds[HDD_BUS_IDE].refresh();
d->hdds[HDD_BUS_IDE].label->setToolTip(tr("Hard disk (%1)").arg("IDE"));
sbar->addWidget(d->hdds[HDD_BUS_IDE].label.get());
}
if (c_atapi > 0) {
d->hdds[HDD_BUS_ATAPI].label = std::make_unique<QLabel>();
d->hdds[HDD_BUS_ATAPI].setActive(false);
d->hdds[HDD_BUS_ATAPI].refresh();
d->hdds[HDD_BUS_ATAPI].label->setToolTip(tr("Hard disk (%1)").arg("ATAPI"));
sbar->addWidget(d->hdds[HDD_BUS_ATAPI].label.get());
}
}
if ((hasSCSI() ||
(scsi_card_current[0] != 0) || (scsi_card_current[1] != 0) ||
(scsi_card_current[2] != 0) || (scsi_card_current[3] != 0)) &&
(c_scsi > 0)) {
d->hdds[HDD_BUS_SCSI].label = std::make_unique<QLabel>();
d->hdds[HDD_BUS_SCSI].setActive(false);
d->hdds[HDD_BUS_SCSI].refresh();
d->hdds[HDD_BUS_SCSI].label->setToolTip(tr("Hard disk (%1)").arg("SCSI"));
sbar->addWidget(d->hdds[HDD_BUS_SCSI].label.get());
}
d->sound = std::make_unique<ClickableLabel>();
d->sound->setPixmap(d->pixmaps.sound);
connect(d->sound.get(), &ClickableLabel::doubleClicked, d->sound.get(), [](QPoint pos) {
SoundGain gain(main_window);
gain.exec();
});
d->sound->setToolTip(tr("Sound"));
sbar->addWidget(d->sound.get());
d->text = std::make_unique<QLabel>();
sbar->addWidget(d->text.get());
}
void
MachineStatus::message(const QString &msg)
{
d->text->setText(msg);
}
QString
MachineStatus::getMessage()
{
return d->text->text();
}
void
MachineStatus::updateTip(int tag)
{
int category = tag & 0xfffffff0;
int item = tag & 0xf;
if (!MediaMenu::ptr)
return;
switch (category) {
case SB_CASSETTE:
if (d->cassette.label && MediaMenu::ptr->cassetteMenu)
d->cassette.label->setToolTip(MediaMenu::ptr->cassetteMenu->title());
break;
case SB_CARTRIDGE:
if (d->cartridge[item].label && MediaMenu::ptr->cartridgeMenus[item])
d->cartridge[item].label->setToolTip(MediaMenu::ptr->cartridgeMenus[item]->title());
break;
case SB_FLOPPY:
if (d->fdd[item].label && MediaMenu::ptr->floppyMenus[item])
d->fdd[item].label->setToolTip(MediaMenu::ptr->floppyMenus[item]->title());
break;
case SB_CDROM:
if (d->cdrom[item].label && MediaMenu::ptr->cdromMenus[item])
d->cdrom[item].label->setToolTip(MediaMenu::ptr->cdromMenus[item]->title());
break;
case SB_ZIP:
if (d->zip[item].label && MediaMenu::ptr->zipMenus[item])
d->zip[item].label->setToolTip(MediaMenu::ptr->zipMenus[item]->title());
break;
case SB_MO:
if (d->mo[item].label && MediaMenu::ptr->moMenus[item])
d->mo[item].label->setToolTip(MediaMenu::ptr->moMenus[item]->title());
break;
case SB_HDD:
break;
case SB_NETWORK:
break;
case SB_SOUND:
break;
case SB_TEXT:
break;
}
}
``` | /content/code_sandbox/src/qt/qt_machinestatus.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 6,879 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Floppy/CD-ROM devices configuration UI module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
*
*/
#include "qt_settingsfloppycdrom.hpp"
#include "ui_qt_settingsfloppycdrom.h"
extern "C" {
#include <inttypes.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/timer.h>
#include <86box/fdd.h>
#include <86box/cdrom.h>
}
#include <QStandardItemModel>
#include "qt_models_common.hpp"
#include "qt_harddrive_common.hpp"
#include "qt_settings_bus_tracking.hpp"
#include "qt_progsettings.hpp"
static void
setFloppyType(QAbstractItemModel *model, const QModelIndex &idx, int type)
{
QIcon icon;
if (type == 0)
icon = ProgSettings::loadIcon("/floppy_disabled.ico");
else if (type >= 1 && type <= 6)
icon = ProgSettings::loadIcon("/floppy_525.ico");
else
icon = ProgSettings::loadIcon("/floppy_35.ico");
model->setData(idx, QObject::tr(fdd_getname(type)));
model->setData(idx, type, Qt::UserRole);
model->setData(idx, icon, Qt::DecorationRole);
}
static void
setCDROMBus(QAbstractItemModel *model, const QModelIndex &idx, uint8_t bus, uint8_t channel)
{
QIcon icon;
switch (bus) {
case CDROM_BUS_DISABLED:
icon = ProgSettings::loadIcon("/cdrom_disabled.ico");
break;
case CDROM_BUS_ATAPI:
case CDROM_BUS_SCSI:
case CDROM_BUS_MITSUMI:
icon = ProgSettings::loadIcon("/cdrom.ico");
break;
}
auto i = idx.siblingAtColumn(0);
model->setData(i, Harddrives::BusChannelName(bus, channel));
model->setData(i, bus, Qt::UserRole);
model->setData(i, channel, Qt::UserRole + 1);
model->setData(i, icon, Qt::DecorationRole);
}
static void
setCDROMSpeed(QAbstractItemModel *model, const QModelIndex &idx, uint8_t speed)
{
if (!speed)
speed = 8;
auto i = idx.siblingAtColumn(1);
model->setData(i, QString("%1x").arg(speed));
model->setData(i, speed, Qt::UserRole);
}
static void
setCDROMType(QAbstractItemModel *model, const QModelIndex &idx, int type)
{
auto i = idx.siblingAtColumn(2);
if (idx.siblingAtColumn(0).data(Qt::UserRole).toUInt() == CDROM_BUS_DISABLED)
model->setData(i, QCoreApplication::translate("", "None"));
else if (idx.siblingAtColumn(0).data(Qt::UserRole).toUInt() != CDROM_BUS_MITSUMI)
model->setData(i, QObject::tr(cdrom_getname(type)));
model->setData(i, type, Qt::UserRole);
}
SettingsFloppyCDROM::SettingsFloppyCDROM(QWidget *parent)
: QWidget(parent)
, ui(new Ui::SettingsFloppyCDROM)
{
ui->setupUi(this);
auto *model = ui->comboBoxFloppyType->model();
int i = 0;
while (true) {
QString name = tr(fdd_getname(i));
if (name.isEmpty())
break;
Models::AddEntry(model, name, i);
++i;
}
model = new QStandardItemModel(0, 3, this);
ui->tableViewFloppy->setModel(model);
model->setHeaderData(0, Qt::Horizontal, tr("Type"));
model->setHeaderData(1, Qt::Horizontal, tr("Turbo"));
model->setHeaderData(2, Qt::Horizontal, tr("Check BPB"));
model->insertRows(0, FDD_NUM);
/* Floppy drives category */
for (int i = 0; i < FDD_NUM; i++) {
auto idx = model->index(i, 0);
int type = fdd_get_type(i);
setFloppyType(model, idx, type);
model->setData(idx.siblingAtColumn(1), fdd_get_turbo(i) > 0 ? tr("On") : tr("Off"));
model->setData(idx.siblingAtColumn(2), fdd_get_check_bpb(i) > 0 ? tr("On") : tr("Off"));
}
ui->tableViewFloppy->resizeColumnsToContents();
ui->tableViewFloppy->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
connect(ui->tableViewFloppy->selectionModel(), &QItemSelectionModel::currentRowChanged,
this, &SettingsFloppyCDROM::onFloppyRowChanged);
ui->tableViewFloppy->setCurrentIndex(model->index(0, 0));
Harddrives::populateRemovableBuses(ui->comboBoxBus->model());
model = ui->comboBoxSpeed->model();
for (int i = 0; i < 72; i++)
Models::AddEntry(model, QString("%1x").arg(i + 1), i + 1);
model = new QStandardItemModel(0, 3, this);
ui->tableViewCDROM->setModel(model);
model->setHeaderData(0, Qt::Horizontal, tr("Bus"));
model->setHeaderData(1, Qt::Horizontal, tr("Speed"));
model->setHeaderData(2, Qt::Horizontal, tr("Type"));
model->insertRows(0, CDROM_NUM);
for (int i = 0; i < CDROM_NUM; i++) {
auto idx = model->index(i, 0);
int type = cdrom_get_type(i);
setCDROMBus(model, idx, cdrom[i].bus_type, cdrom[i].res);
setCDROMSpeed(model, idx.siblingAtColumn(1), cdrom[i].speed);
setCDROMType(model, idx.siblingAtColumn(2), type);
if (cdrom[i].bus_type == CDROM_BUS_ATAPI)
Harddrives::busTrackClass->device_track(1, DEV_CDROM, cdrom[i].bus_type, cdrom[i].ide_channel);
else if (cdrom[i].bus_type == CDROM_BUS_SCSI)
Harddrives::busTrackClass->device_track(1, DEV_CDROM, cdrom[i].bus_type,
cdrom[i].scsi_device_id);
else if (cdrom[i].bus_type == CDROM_BUS_MITSUMI)
Harddrives::busTrackClass->device_track(1, DEV_CDROM, cdrom[i].bus_type, 0);
}
ui->tableViewCDROM->resizeColumnsToContents();
ui->tableViewCDROM->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
connect(ui->tableViewCDROM->selectionModel(), &QItemSelectionModel::currentRowChanged,
this, &SettingsFloppyCDROM::onCDROMRowChanged);
ui->tableViewCDROM->setCurrentIndex(model->index(0, 0));
uint8_t bus_type = ui->comboBoxBus->currentData().toUInt();
int cdromIdx = ui->tableViewCDROM->selectionModel()->currentIndex().data().toInt();
auto *modelType = ui->comboBoxCDROMType->model();
int removeRows = modelType->rowCount();
uint32_t j = 0;
int selectedTypeRow = 0;
int eligibleRows = 0;
while (cdrom_drive_types[j].bus_type != BUS_TYPE_NONE) {
if (((bus_type == CDROM_BUS_ATAPI) || (bus_type == CDROM_BUS_SCSI)) &&
((cdrom_drive_types[j].bus_type == bus_type) ||
(cdrom_drive_types[j].bus_type == BUS_TYPE_BOTH))) {
QString name = tr(cdrom_getname(j));
Models::AddEntry(modelType, name, j);
if ((cdrom[cdromIdx].bus_type == bus_type) && (cdrom[cdromIdx].type == j))
selectedTypeRow = eligibleRows;
++eligibleRows;
}
++j;
}
modelType->removeRows(0, removeRows);
ui->comboBoxCDROMType->setEnabled(eligibleRows > 1);
ui->comboBoxCDROMType->setCurrentIndex(-1);
ui->comboBoxCDROMType->setCurrentIndex(selectedTypeRow);
}
SettingsFloppyCDROM::~SettingsFloppyCDROM()
{
delete ui;
}
void
SettingsFloppyCDROM::save()
{
auto *model = ui->tableViewFloppy->model();
for (int i = 0; i < FDD_NUM; i++) {
fdd_set_type(i, model->index(i, 0).data(Qt::UserRole).toInt());
fdd_set_turbo(i, model->index(i, 1).data() == tr("On") ? 1 : 0);
fdd_set_check_bpb(i, model->index(i, 2).data() == tr("On") ? 1 : 0);
}
/* Removable devices category */
model = ui->tableViewCDROM->model();
for (int i = 0; i < CDROM_NUM; i++) {
cdrom[i].priv = NULL;
cdrom[i].ops = NULL;
cdrom[i].image = NULL;
cdrom[i].insert = NULL;
cdrom[i].close = NULL;
cdrom[i].get_volume = NULL;
cdrom[i].get_channel = NULL;
cdrom[i].bus_type = model->index(i, 0).data(Qt::UserRole).toUInt();
cdrom[i].res = model->index(i, 0).data(Qt::UserRole + 1).toUInt();
cdrom[i].speed = model->index(i, 1).data(Qt::UserRole).toUInt();
cdrom_set_type(i, model->index(i, 2).data(Qt::UserRole).toInt());
}
}
void
SettingsFloppyCDROM::onFloppyRowChanged(const QModelIndex ¤t)
{
int type = current.siblingAtColumn(0).data(Qt::UserRole).toInt();
ui->comboBoxFloppyType->setCurrentIndex(type);
ui->checkBoxTurboTimings->setChecked(current.siblingAtColumn(1).data() == tr("On"));
ui->checkBoxCheckBPB->setChecked(current.siblingAtColumn(2).data() == tr("On"));
}
void
SettingsFloppyCDROM::onCDROMRowChanged(const QModelIndex ¤t)
{
uint8_t bus = current.siblingAtColumn(0).data(Qt::UserRole).toUInt();
uint8_t channel = current.siblingAtColumn(0).data(Qt::UserRole + 1).toUInt();
uint8_t speed = current.siblingAtColumn(1).data(Qt::UserRole).toUInt();
int type = current.siblingAtColumn(2).data(Qt::UserRole).toInt();
ui->comboBoxBus->setCurrentIndex(-1);
auto* model = ui->comboBoxBus->model();
auto match = model->match(model->index(0, 0), Qt::UserRole, bus);
if (! match.isEmpty())
ui->comboBoxBus->setCurrentIndex(match.first().row());
model = ui->comboBoxChannel->model();
match = model->match(model->index(0, 0), Qt::UserRole, channel);
if (!match.isEmpty())
ui->comboBoxChannel->setCurrentIndex(match.first().row());
ui->comboBoxSpeed->setCurrentIndex(speed == 0 ? 7 : speed - 1);
ui->comboBoxCDROMType->setCurrentIndex(type);
enableCurrentlySelectedChannel();
}
void
SettingsFloppyCDROM::on_checkBoxTurboTimings_stateChanged(int arg1)
{
auto idx = ui->tableViewFloppy->selectionModel()->currentIndex();
ui->tableViewFloppy->model()->setData(idx.siblingAtColumn(1), arg1 == Qt::Checked ?
tr("On") : tr("Off"));
}
void
SettingsFloppyCDROM::on_checkBoxCheckBPB_stateChanged(int arg1)
{
auto idx = ui->tableViewFloppy->selectionModel()->currentIndex();
ui->tableViewFloppy->model()->setData(idx.siblingAtColumn(2), arg1 == Qt::Checked ?
tr("On") : tr("Off"));
}
void
SettingsFloppyCDROM::on_comboBoxFloppyType_activated(int index)
{
setFloppyType(ui->tableViewFloppy->model(),
ui->tableViewFloppy->selectionModel()->currentIndex(), index);
}
void SettingsFloppyCDROM::reloadBusChannels() {
auto selected = ui->comboBoxChannel->currentIndex();
Harddrives::populateBusChannels(ui->comboBoxChannel->model(), ui->comboBoxBus->currentData().toInt(), Harddrives::busTrackClass);
ui->comboBoxChannel->setCurrentIndex(selected);
enableCurrentlySelectedChannel();
}
void
SettingsFloppyCDROM::on_comboBoxBus_currentIndexChanged(int index)
{
if (index >= 0) {
int bus = ui->comboBoxBus->currentData().toInt();
bool enabled = (bus != CDROM_BUS_DISABLED);
ui->comboBoxChannel->setEnabled((bus == CDROM_BUS_MITSUMI) ? 0 : enabled);
ui->comboBoxSpeed->setEnabled((bus == CDROM_BUS_MITSUMI) ? 0 : enabled);
ui->comboBoxCDROMType->setEnabled((bus == CDROM_BUS_MITSUMI) ? 0 : enabled);
Harddrives::populateBusChannels(ui->comboBoxChannel->model(), bus, Harddrives::busTrackClass);
}
}
void
SettingsFloppyCDROM::on_comboBoxSpeed_activated(int index)
{
auto idx = ui->tableViewCDROM->selectionModel()->currentIndex();
setCDROMSpeed(ui->tableViewCDROM->model(), idx.siblingAtColumn(1), index + 1);
}
void
SettingsFloppyCDROM::on_comboBoxBus_activated(int)
{
auto i = ui->tableViewCDROM->selectionModel()->currentIndex().siblingAtColumn(0);
uint8_t bus_type = ui->comboBoxBus->currentData().toUInt();
int cdromIdx = ui->tableViewCDROM->selectionModel()->currentIndex().data().toInt();
Harddrives::busTrackClass->device_track(0, DEV_CDROM, ui->tableViewCDROM->model()->data(i,
Qt::UserRole).toInt(), ui->tableViewCDROM->model()->data(i,
Qt::UserRole + 1).toInt());
if (bus_type == CDROM_BUS_ATAPI)
ui->comboBoxChannel->setCurrentIndex(Harddrives::busTrackClass->next_free_ide_channel());
else if (bus_type == CDROM_BUS_SCSI)
ui->comboBoxChannel->setCurrentIndex(Harddrives::busTrackClass->next_free_scsi_id());
else if (bus_type == CDROM_BUS_MITSUMI)
ui->comboBoxChannel->setCurrentIndex(0);
setCDROMBus(ui->tableViewCDROM->model(),
ui->tableViewCDROM->selectionModel()->currentIndex(),
bus_type,
ui->comboBoxChannel->currentData().toUInt());
Harddrives::busTrackClass->device_track(1, DEV_CDROM, ui->tableViewCDROM->model()->data(i,
Qt::UserRole).toInt(), ui->tableViewCDROM->model()->data(i,
Qt::UserRole + 1).toInt());
auto *modelType = ui->comboBoxCDROMType->model();
int removeRows = modelType->rowCount();
uint32_t j = 0;
int selectedTypeRow = 0;
int eligibleRows = 0;
while (cdrom_drive_types[j].bus_type != BUS_TYPE_NONE) {
if (((bus_type == CDROM_BUS_ATAPI) || (bus_type == CDROM_BUS_SCSI)) &&
((cdrom_drive_types[j].bus_type == bus_type) ||
(cdrom_drive_types[j].bus_type == BUS_TYPE_BOTH))) {
QString name = tr(cdrom_getname(j));
Models::AddEntry(modelType, name, j);
if ((cdrom[cdromIdx].bus_type == bus_type) && (cdrom[cdromIdx].type == j))
selectedTypeRow = eligibleRows;
++eligibleRows;
}
++j;
}
modelType->removeRows(0, removeRows);
ui->comboBoxCDROMType->setEnabled(eligibleRows > 1);
ui->comboBoxCDROMType->setCurrentIndex(-1);
ui->comboBoxCDROMType->setCurrentIndex(selectedTypeRow);
setCDROMType(ui->tableViewCDROM->model(),
ui->tableViewCDROM->selectionModel()->currentIndex(),
ui->comboBoxCDROMType->currentData().toUInt());
emit cdromChannelChanged();
}
void
SettingsFloppyCDROM::enableCurrentlySelectedChannel()
{
const auto *item_model = qobject_cast<QStandardItemModel*>(ui->comboBoxChannel->model());
const auto index = ui->comboBoxChannel->currentIndex();
auto *item = item_model->item(index);
if(item) {
item->setEnabled(true);
}
}
void
SettingsFloppyCDROM::on_comboBoxChannel_activated(int)
{
auto i = ui->tableViewCDROM->selectionModel()->currentIndex().siblingAtColumn(0);
Harddrives::busTrackClass->device_track(0, DEV_CDROM, ui->tableViewCDROM->model()->data(i,
Qt::UserRole).toInt(), ui->tableViewCDROM->model()->data(i,
Qt::UserRole + 1).toInt());
setCDROMBus(ui->tableViewCDROM->model(),
ui->tableViewCDROM->selectionModel()->currentIndex(),
ui->comboBoxBus->currentData().toUInt(),
ui->comboBoxChannel->currentData().toUInt());
Harddrives::busTrackClass->device_track(1, DEV_CDROM, ui->tableViewCDROM->model()->data(i,
Qt::UserRole).toInt(), ui->tableViewCDROM->model()->data(i,
Qt::UserRole + 1).toInt());
emit cdromChannelChanged();
}
void
SettingsFloppyCDROM::on_comboBoxCDROMType_activated(int)
{
setCDROMType(ui->tableViewCDROM->model(),
ui->tableViewCDROM->selectionModel()->currentIndex(),
ui->comboBoxCDROMType->currentData().toUInt());
ui->tableViewCDROM->resizeColumnsToContents();
ui->tableViewCDROM->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
}
``` | /content/code_sandbox/src/qt/qt_settingsfloppycdrom.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,197 |
```c++
#ifndef QT_SETTINGSHARDDISKS_HPP
#define QT_SETTINGSHARDDISKS_HPP
#include <QWidget>
namespace Ui {
class SettingsHarddisks;
}
class SettingsHarddisks : public QWidget {
Q_OBJECT
public:
explicit SettingsHarddisks(QWidget *parent = nullptr);
~SettingsHarddisks();
void reloadBusChannels();
void save();
signals:
void driveChannelChanged();
private slots:
void on_comboBoxChannel_currentIndexChanged(int index);
void on_comboBoxSpeed_currentIndexChanged(int index);
private slots:
void on_pushButtonRemove_clicked();
void on_pushButtonExisting_clicked();
void on_pushButtonNew_clicked();
void on_comboBoxBus_currentIndexChanged(int index);
void onTableRowChanged(const QModelIndex ¤t);
private:
Ui::SettingsHarddisks *ui;
void enableCurrentlySelectedChannel();
bool buschangeinprogress = false;
};
#endif // QT_SETTINGSHARDDISKS_HPP
``` | /content/code_sandbox/src/qt/qt_settingsharddisks.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 199 |
```c++
#ifndef QT_UTIL_HPP
#define QT_UTIL_HPP
#include <QString>
#include <QWidget>
#include <initializer_list>
class QScreen;
namespace util {
static constexpr auto UUID_MIN_LENGTH = 36;
/* Creates extension list for qt filedialog */
QString DlgFilter(std::initializer_list<QString> extensions, bool last = false);
/* Returns screen the widget is on */
QScreen *screenOfWidget(QWidget *widget);
QString currentUuid();
void storeCurrentUuid();
bool compareUuid();
void generateNewMacAdresses();
bool hasConfiguredNICs();
};
#endif
``` | /content/code_sandbox/src/qt/qt_util.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 115 |
```c++
#ifndef SOFTWARERENDERER_HPP
#define SOFTWARERENDERER_HPP
#include <QWidget>
#include <QRasterWindow>
#include <QPaintDevice>
#include <array>
#include <atomic>
#include "qt_renderercommon.hpp"
class SoftwareRenderer :
#ifdef __HAIKU__
public QWidget,
#else
public QRasterWindow,
#endif
public RendererCommon {
Q_OBJECT
public:
explicit SoftwareRenderer(QWidget *parent = nullptr);
void paintEvent(QPaintEvent *event) override;
std::vector<std::tuple<uint8_t *, std::atomic_flag *>> getBuffers() override;
public slots:
void onBlit(int buf_idx, int x, int y, int w, int h);
protected:
std::array<std::unique_ptr<QImage>, 2> images;
int cur_image = -1;
void onPaint(QPaintDevice *device);
void resizeEvent(QResizeEvent *event) override;
bool event(QEvent *event) override;
};
#endif // SOFTWARERENDERER_HPP
``` | /content/code_sandbox/src/qt/qt_softwarerenderer.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 224 |
```c++
#ifndef QT_SETTINGSNETWORK_HPP
#define QT_SETTINGSNETWORK_HPP
#include <QWidget>
namespace Ui {
class SettingsNetwork;
}
class SettingsNetwork : public QWidget {
Q_OBJECT
public:
explicit SettingsNetwork(QWidget *parent = nullptr);
~SettingsNetwork();
void save();
public slots:
void onCurrentMachineChanged(int machineId);
private slots:
void on_pushButtonConf1_clicked();
void on_pushButtonConf2_clicked();
void on_pushButtonConf3_clicked();
void on_pushButtonConf4_clicked();
void on_comboIndexChanged(int index);
void enableElements(Ui::SettingsNetwork *ui);
private:
Ui::SettingsNetwork *ui;
int machineId = 0;
};
#endif // QT_SETTINGSNETWORK_HPP
``` | /content/code_sandbox/src/qt/qt_settingsnetwork.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 152 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Device configuration UI code.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
*
*/
#include "qt_deviceconfig.hpp"
#include "ui_qt_deviceconfig.h"
#include "qt_settings.hpp"
#include <QDebug>
#include <QComboBox>
#include <QPushButton>
#include <QFormLayout>
#include <QSpinBox>
#include <QCheckBox>
#include <QFrame>
#include <QLineEdit>
#include <QLabel>
#include <QDir>
#include <QSettings>
extern "C" {
#include <86box/86box.h>
#include <86box/ini.h>
#include <86box/config.h>
#include <86box/device.h>
#include <86box/midi_rtmidi.h>
#include <86box/mem.h>
#include <86box/random.h>
#include <86box/rom.h>
}
#include "qt_filefield.hpp"
#include "qt_models_common.hpp"
#ifdef Q_OS_LINUX
# include <sys/stat.h>
# include <sys/sysmacros.h>
#endif
#ifdef Q_OS_WINDOWS
#include <windows.h>
#endif
DeviceConfig::DeviceConfig(QWidget *parent)
: QDialog(parent)
, ui(new Ui::DeviceConfig)
{
ui->setupUi(this);
}
DeviceConfig::~DeviceConfig()
{
delete ui;
}
static QStringList
EnumerateSerialDevices()
{
QStringList serialDevices;
QStringList ttyEntries;
QByteArray devstr(1024, 0);
#ifdef Q_OS_LINUX
QDir class_dir("/sys/class/tty/");
QDir dev_dir("/dev/");
ttyEntries = class_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::System, QDir::SortFlag::Name);
for (int i = 0; i < ttyEntries.size(); i++) {
if (class_dir.exists(ttyEntries[i] + "/device/driver/") && dev_dir.exists(ttyEntries[i])
&& QFileInfo(dev_dir.canonicalPath() + '/' + ttyEntries[i]).isReadable()
&& QFileInfo(dev_dir.canonicalPath() + '/' + ttyEntries[i]).isWritable()) {
serialDevices.push_back("/dev/" + ttyEntries[i]);
}
}
#endif
#ifdef Q_OS_WINDOWS
for (int i = 1; i < 256; i++) {
devstr[0] = 0;
snprintf(devstr.data(), 1024, R"(\\.\COM%d)", i);
const auto handle = CreateFileA(devstr.data(),
GENERIC_READ | GENERIC_WRITE, 0,
nullptr, OPEN_EXISTING,
0, nullptr);
const auto dwError = GetLastError();
if ((handle != INVALID_HANDLE_VALUE) || (dwError == ERROR_ACCESS_DENIED) ||
(dwError == ERROR_GEN_FAILURE) || (dwError == ERROR_SHARING_VIOLATION) ||
(dwError == ERROR_SEM_TIMEOUT)) {
if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
serialDevices.push_back(QString(devstr));
}
}
#endif
#ifdef Q_OS_MACOS
QDir dev_dir("/dev/");
dev_dir.setNameFilters({ "tty.*", "cu.*" });
QDir::Filters serial_dev_flags = QDir::Files | QDir::NoSymLinks | QDir::Readable | QDir::Writable | QDir::NoDotAndDotDot | QDir::System;
for (const auto &device : dev_dir.entryInfoList(serial_dev_flags, QDir::SortFlag::Name)) {
serialDevices.push_back(device.canonicalFilePath());
}
#endif
return serialDevices;
}
void
DeviceConfig::ProcessConfig(void *dc, const void *c, const bool is_dep)
{
auto * device_context = static_cast<device_context_t *>(dc);
const auto * config = static_cast<const _device_config_ *>(c);
const QString blank = "";
int p;
int q;
if (config == NULL)
return;
while (config->type != -1) {
const int config_type = config->type & CONFIG_TYPE_MASK;
/* Ignore options of the wrong class. */
if (!!(config->type & CONFIG_DEP) != is_dep)
continue;
/* If this is a BIOS-dependent option and it's BIOS, ignore it. */
if (!!(config->type & CONFIG_DEP) && (config_type == CONFIG_BIOS))
continue;
const int config_major_type = (config_type >> CONFIG_SHIFT) << CONFIG_SHIFT;
int value = 0;
auto selected = blank;
switch (config_major_type) {
default:
break;
case CONFIG_TYPE_INT:
value = config_get_int(device_context->name, const_cast<char *>(config->name),
config->default_int);
break;
case CONFIG_TYPE_HEX16:
value = config_get_hex16(device_context->name, const_cast<char *>(config->name),
config->default_int);
break;
case CONFIG_TYPE_HEX20:
value = config_get_hex20(device_context->name, const_cast<char *>(config->name),
config->default_int);
break;
case CONFIG_TYPE_STRING:
selected = config_get_string(device_context->name, const_cast<char *>(config->name),
const_cast<char *>(config->default_string));
break;
}
switch (config->type) {
default:
break;
case CONFIG_BINARY:
{
auto *cbox = new QCheckBox();
cbox->setObjectName(config->name);
cbox->setChecked(value > 0);
this->ui->formLayout->addRow(config->description, cbox);
break;
}
#ifdef USE_RTMIDI
case CONFIG_MIDI_OUT:
{
auto *cbox = new QComboBox();
cbox->setObjectName(config->name);
cbox->setMaxVisibleItems(30);
auto *model = cbox->model();
int currentIndex = -1;
for (int i = 0; i < rtmidi_out_get_num_devs(); i++) {
char midiName[512] = { 0 };
rtmidi_out_get_dev_name(i, midiName);
Models::AddEntry(model, midiName, i);
if (i == value)
currentIndex = i;
}
this->ui->formLayout->addRow(config->description, cbox);
cbox->setCurrentIndex(currentIndex);
break;
}
case CONFIG_MIDI_IN:
{
auto *cbox = new QComboBox();
cbox->setObjectName(config->name);
cbox->setMaxVisibleItems(30);
auto *model = cbox->model();
int currentIndex = -1;
for (int i = 0; i < rtmidi_in_get_num_devs(); i++) {
char midiName[512] = { 0 };
rtmidi_in_get_dev_name(i, midiName);
Models::AddEntry(model, midiName, i);
if (i == value)
currentIndex = i;
}
this->ui->formLayout->addRow(config->description, cbox);
cbox->setCurrentIndex(currentIndex);
break;
}
#endif
case CONFIG_INT:
case CONFIG_SELECTION:
case CONFIG_HEX16:
case CONFIG_HEX20:
{
auto *cbox = new QComboBox();
cbox->setObjectName(config->name);
cbox->setMaxVisibleItems(30);
auto *model = cbox->model();
int currentIndex = -1;
for (auto *sel = config->selection; (sel != nullptr) && (sel->description != nullptr) &&
(strlen(sel->description) > 0); ++sel) {
int row = Models::AddEntry(model, sel->description, sel->value);
if (sel->value == value)
currentIndex = row;
}
this->ui->formLayout->addRow(config->description, cbox);
cbox->setCurrentIndex(currentIndex);
break;
}
case CONFIG_BIOS:
{
auto *cbox = new QComboBox();
cbox->setObjectName(config->name);
cbox->setMaxVisibleItems(30);
auto *model = cbox->model();
int currentIndex = -1;
q = 0;
for (auto *bios = config->bios; (bios != nullptr) && (bios->name != nullptr) &&
(strlen(bios->name) > 0); ++bios) {
p = 0;
for (int d = 0; d < bios->files_no; d++)
p += !!rom_present(const_cast<char *>(bios->files[d]));
if (p == bios->files_no) {
const int row = Models::AddEntry(model, bios->name, q);
if (!strcmp(selected.toUtf8().constData(), bios->internal_name))
currentIndex = row;
}
q++;
}
this->ui->formLayout->addRow(config->description, cbox);
cbox->setCurrentIndex(currentIndex);
break;
}
case CONFIG_SPINNER:
{
auto *spinBox = new QSpinBox();
spinBox->setObjectName(config->name);
spinBox->setMaximum(config->spinner.max);
spinBox->setMinimum(config->spinner.min);
if (config->spinner.step > 0)
spinBox->setSingleStep(config->spinner.step);
spinBox->setValue(value);
this->ui->formLayout->addRow(config->description, spinBox);
break;
}
case CONFIG_FNAME:
{
auto *fileField = new FileField();
fileField->setObjectName(config->name);
fileField->setFileName(selected);
fileField->setFilter(QString(config->file_filter).left(static_cast<int>(strcspn(config->file_filter,
"|"))));
this->ui->formLayout->addRow(config->description, fileField);
break;
}
case CONFIG_STRING:
{
const auto lineEdit = new QLineEdit;
lineEdit->setObjectName(config->name);
lineEdit->setCursor(Qt::IBeamCursor);
lineEdit->setText(selected);
this->ui->formLayout->addRow(config->description, lineEdit);
break;
}
case CONFIG_SERPORT:
{
auto *cbox = new QComboBox();
cbox->setObjectName(config->name);
cbox->setMaxVisibleItems(30);
auto *model = cbox->model();
int currentIndex = 0;
auto serialDevices = EnumerateSerialDevices();
Models::AddEntry(model, tr("None"), -1);
for (int i = 0; i < serialDevices.size(); i++) {
const int row = Models::AddEntry(model, serialDevices[i], i);
if (selected == serialDevices[i])
currentIndex = row;
}
this->ui->formLayout->addRow(config->description, cbox);
cbox->setCurrentIndex(currentIndex);
break;
}
case CONFIG_MAC:
{
// QHBoxLayout for the line edit widget and the generate button
const auto hboxLayout = new QHBoxLayout();
const auto generateButton = new QPushButton(tr("Generate"));
const auto lineEdit = new QLineEdit;
// Allow the line edit to expand and fill available space
lineEdit->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Preferred);
lineEdit->setInputMask("HH:HH:HH;0");
lineEdit->setObjectName(config->name);
// Display the current or generated MAC in uppercase
// When stored it will be converted to lowercase
if (config_get_mac(device_context->name, config->name,
config->default_int) & 0xFF000000) {
lineEdit->setText(QString::asprintf("%02X:%02X:%02X", random_generate(),
random_generate(), random_generate()));
} else {
auto current_mac = QString(config_get_string(device_context->name, config->name,
const_cast<char *>(config->default_string)));
lineEdit->setText(current_mac.toUpper());
}
// Action for the generate button
connect(generateButton, &QPushButton::clicked, [lineEdit] {
lineEdit->setText(QString::asprintf("%02X:%02X:%02X", random_generate(),
random_generate(), random_generate()));
});
hboxLayout->addWidget(lineEdit);
hboxLayout->addWidget(generateButton);
this->ui->formLayout->addRow(config->description, hboxLayout);
break;
}
}
++config;
}
}
void
DeviceConfig::ConfigureDevice(const _device_ *device, int instance, Settings *settings)
{
DeviceConfig dc(settings);
dc.setWindowTitle(QString("%1 Device Configuration").arg(device->name));
device_context_t device_context;
device_set_context(&device_context, device, instance);
const auto device_label = new QLabel(device->name);
device_label->setAlignment(Qt::AlignCenter);
dc.ui->formLayout->addRow(device_label);
const auto line = new QFrame;
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
dc.ui->formLayout->addRow(line);
const _device_config_ *config = device->config;
dc.ProcessConfig(&device_context, config, false);
dc.setFixedSize(dc.minimumSizeHint());
if (dc.exec() == QDialog::Accepted) {
if (config == NULL)
return;
config = device->config;
while (config->type != -1) {
switch (config->type) {
default:
break;
case CONFIG_BINARY:
{
const auto *cbox = dc.findChild<QCheckBox *>(config->name);
config_set_int(device_context.name, const_cast<char *>(config->name), cbox->isChecked() ? 1 : 0);
break;
}
case CONFIG_MIDI_OUT:
case CONFIG_MIDI_IN:
case CONFIG_SELECTION:
{
auto *cbox = dc.findChild<QComboBox *>(config->name);
config_set_int(device_context.name, const_cast<char *>(config->name), cbox->currentData().toInt());
break;
}
case CONFIG_BIOS:
{
auto *cbox = dc.findChild<QComboBox *>(config->name);
int idx = cbox->currentData().toInt();
config_set_string(device_context.name, const_cast<char *>(config->name), const_cast<char *>(config->bios[idx].internal_name));
break;
}
case CONFIG_SERPORT:
{
auto *cbox = dc.findChild<QComboBox *>(config->name);
auto path = cbox->currentText().toUtf8();
if (cbox->currentData().toInt() == -1)
path = "";
config_set_string(device_context.name, const_cast<char *>(config->name), path);
break;
}
case CONFIG_STRING:
{
auto *lineEdit = dc.findChild<QLineEdit *>(config->name);
config_set_string(device_context.name, const_cast<char *>(config->name), lineEdit->text().toUtf8());
break;
}
case CONFIG_HEX16:
{
auto *cbox = dc.findChild<QComboBox *>(config->name);
config_set_hex16(device_context.name, const_cast<char *>(config->name), cbox->currentData().toInt());
break;
}
case CONFIG_HEX20:
{
auto *cbox = dc.findChild<QComboBox *>(config->name);
config_set_hex20(device_context.name, const_cast<char *>(config->name), cbox->currentData().toInt());
break;
}
case CONFIG_FNAME:
{
auto *fbox = dc.findChild<FileField *>(config->name);
auto fileName = fbox->fileName().toUtf8();
config_set_string(device_context.name, const_cast<char *>(config->name), fileName.data());
break;
}
case CONFIG_SPINNER:
{
auto *spinBox = dc.findChild<QSpinBox *>(config->name);
config_set_int(device_context.name, const_cast<char *>(config->name), spinBox->value());
break;
}
case CONFIG_MAC:
{
const auto *lineEdit = dc.findChild<QLineEdit *>(config->name);
// Store the mac address as lowercase
auto macText = lineEdit->displayText().toLower();
config_set_string(device_context.name, config->name, macText.toUtf8().constData());
break;
}
}
config++;
}
}
}
QString
DeviceConfig::DeviceName(const _device_ *device, const char *internalName, const int bus)
{
if (QStringLiteral("none") == internalName)
return tr("None");
else if (QStringLiteral("internal") == internalName)
return tr("Internal controller");
else if (device == nullptr)
return "";
else {
char temp[512];
device_get_name(device, bus, temp);
return tr(temp, nullptr, 512);
}
}
``` | /content/code_sandbox/src/qt/qt_deviceconfig.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,735 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Definitions for xkbcommon keyboard input module.
*
*
*
* Authors: RichardG, <richardg867@gmail.com>
*
*/
extern void *xkbcommon_keymap;
void xkbcommon_init(struct xkb_keymap *keymap);
void xkbcommon_close();
uint16_t xkbcommon_translate(uint32_t keycode);
``` | /content/code_sandbox/src/qt/xkbcommon_keyboard.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 142 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Win32 CD-ROM support via IOCTL.
*
*
*
* Authors: TheCollector1995, <mariogplayer@gmail.com>,
* Miran Grca, <mgrca8@gmail.com>
*
*/
#define UNICODE
#define BITMAP WINDOWS_BITMAP
#include <windows.h>
#include <windowsx.h>
#undef BITMAP
#include <inttypes.h>
#include <io.h>
#include "ntddcdrm.h"
#include "ntddscsi.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include <86box/scsi_device.h>
#include <86box/cdrom.h>
#include <86box/plat_unused.h>
#include <86box/plat_cdrom.h>
/* The addresses sent from the guest are absolute, ie. a LBA of 0 corresponds to a MSF of 00:00:00. Otherwise, the counter displayed by the guest is wrong:
there is a seeming 2 seconds in which audio plays but counter does not move, while a data track before audio jumps to 2 seconds before the actual start
of the audio while audio still plays. With an absolute conversion, the counter is fine. */
#define MSFtoLBA(m, s, f) ((((m * 60) + s) * 75) + f)
static int toc_valid = 0;
static CDROM_TOC cur_toc = { 0 };
static HANDLE handle = NULL;
static WCHAR ioctl_path[256] = { 0 };
static WCHAR old_ioctl_path[256] = { 0 };
#ifdef ENABLE_WIN_CDROM_IOCTL_LOG
int win_cdrom_ioctl_do_log = ENABLE_WIN_CDROM_IOCTL_LOG;
void
win_cdrom_ioctl_log(const char *fmt, ...)
{
va_list ap;
if (win_cdrom_ioctl_do_log) {
va_start(ap, fmt);
pclog_ex(fmt, ap);
va_end(ap);
}
}
#else
# define win_cdrom_ioctl_log(fmt, ...)
#endif
static int
plat_cdrom_open(void)
{
plat_cdrom_close();
handle = CreateFileW((LPCWSTR)ioctl_path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
win_cdrom_ioctl_log("handle=%p, error=%x\n", handle, (unsigned int) GetLastError());
return (handle != INVALID_HANDLE_VALUE);
}
static int
plat_cdrom_load(void)
{
plat_cdrom_close();
handle = CreateFileW((LPCWSTR)ioctl_path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
win_cdrom_ioctl_log("handle=%p, error=%x\n", handle, (unsigned int) GetLastError());
if (handle != INVALID_HANDLE_VALUE) {
long size;
DeviceIoControl(handle, IOCTL_STORAGE_LOAD_MEDIA, NULL, 0, NULL, 0, (LPDWORD)&size, NULL);
return 1;
}
return 0;
}
static void
plat_cdrom_read_toc(void)
{
long size = 0;
if (!toc_valid) {
toc_valid = 1;
plat_cdrom_open();
DeviceIoControl(handle, IOCTL_CDROM_READ_TOC, NULL, 0, &cur_toc, sizeof(cur_toc), (LPDWORD)&size, NULL);
plat_cdrom_close();
}
}
int
plat_cdrom_is_track_audio(uint32_t sector)
{
int control = 0;
uint32_t track_addr = 0;
uint32_t next_track_addr = 0;
plat_cdrom_read_toc();
for (int c = 0; cur_toc.TrackData[c].TrackNumber != 0xaa; c++) {
track_addr = MSFtoLBA(cur_toc.TrackData[c].Address[1], cur_toc.TrackData[c].Address[2], cur_toc.TrackData[c].Address[3]) - 150;
next_track_addr = MSFtoLBA(cur_toc.TrackData[c + 1].Address[1], cur_toc.TrackData[c + 1].Address[2], cur_toc.TrackData[c + 1].Address[3]) - 150;
win_cdrom_ioctl_log("F: %i, L: %i, C: %i (%i), c: %02X, A: %08X, S: %08X\n",
cur_toc.FirstTrack, cur_toc.LastTrack,
cur_toc.TrackData[c].TrackNumber, c,
cur_toc.TrackData[c].Control, track_addr, sector);
if ((cur_toc.TrackData[c].TrackNumber >= cur_toc.FirstTrack) && (cur_toc.TrackData[c].TrackNumber <= cur_toc.LastTrack) &&
(sector >= track_addr) && (sector < next_track_addr)) {
control = cur_toc.TrackData[c].Control;
break;
}
}
const int ret = !(control & 0x04);
win_cdrom_ioctl_log("plat_cdrom_is_track_audio(%08X): %i\n", sector, ret);
return ret;
}
int
plat_cdrom_is_track_pre(uint32_t sector)
{
int control = 0;
uint32_t track_addr = 0;
uint32_t next_track_addr = 0;
plat_cdrom_read_toc();
for (int c = 0; cur_toc.TrackData[c].TrackNumber != 0xaa; c++) {
track_addr = MSFtoLBA(cur_toc.TrackData[c].Address[1], cur_toc.TrackData[c].Address[2], cur_toc.TrackData[c].Address[3]) - 150;
next_track_addr = MSFtoLBA(cur_toc.TrackData[c + 1].Address[1], cur_toc.TrackData[c + 1].Address[2], cur_toc.TrackData[c + 1].Address[3]) - 150;
win_cdrom_ioctl_log("F: %i, L: %i, C: %i (%i), c: %02X, A: %08X, S: %08X\n",
cur_toc.FirstTrack, cur_toc.LastTrack,
cur_toc.TrackData[c].TrackNumber, c,
cur_toc.TrackData[c].Control, track_addr, sector);
if ((cur_toc.TrackData[c].TrackNumber >= cur_toc.FirstTrack) && (cur_toc.TrackData[c].TrackNumber <= cur_toc.LastTrack) &&
(sector >= track_addr) && (sector < next_track_addr)) {
control = cur_toc.TrackData[c].Control;
break;
}
}
const int ret = (control & 0x01);
win_cdrom_ioctl_log("plat_cdrom_is_track_audio(%08X): %i\n", sector, ret);
return ret;
}
uint32_t
plat_cdrom_get_track_start(uint32_t sector, uint8_t *attr, uint8_t *track)
{
uint32_t track_addr = 0;
uint32_t next_track_addr = 0;
plat_cdrom_read_toc();
for (int c = 0; cur_toc.TrackData[c].TrackNumber != 0xaa; c++) {
track_addr = MSFtoLBA(cur_toc.TrackData[c].Address[1], cur_toc.TrackData[c].Address[2], cur_toc.TrackData[c].Address[3]) - 150;
next_track_addr = MSFtoLBA(cur_toc.TrackData[c + 1].Address[1], cur_toc.TrackData[c + 1].Address[2], cur_toc.TrackData[c + 1].Address[3]) - 150;
win_cdrom_ioctl_log("F: %i, L: %i, C: %i (%i), c: %02X, a: %02X, A: %08X, S: %08X\n",
cur_toc.FirstTrack, cur_toc.LastTrack,
cur_toc.TrackData[c].TrackNumber, c,
cur_toc.TrackData[c].Control, cur_toc.TrackData[c].Adr,
track_addr, sector);
if ((cur_toc.TrackData[c].TrackNumber >= cur_toc.FirstTrack) && (cur_toc.TrackData[c].TrackNumber <= cur_toc.LastTrack) &&
(sector >= track_addr) && (sector < next_track_addr)) {
*track = cur_toc.TrackData[c].TrackNumber;
*attr = cur_toc.TrackData[c].Control;
*attr |= ((cur_toc.TrackData[c].Adr << 4) & 0xf0);
break;
}
}
win_cdrom_ioctl_log("plat_cdrom_get_track_start(%08X): %i\n", sector, track_addr);
return track_addr;
}
uint32_t
plat_cdrom_get_last_block(void)
{
uint32_t lb = 0;
uint32_t address = 0;
plat_cdrom_read_toc();
for (int c = 0; c <= cur_toc.LastTrack; c++) {
address = MSFtoLBA(cur_toc.TrackData[c].Address[1], cur_toc.TrackData[c].Address[2], cur_toc.TrackData[c].Address[3]) - 150;
if (address > lb)
lb = address;
}
win_cdrom_ioctl_log("LBCapacity=%d\n", lb);
return lb;
}
int
plat_cdrom_ext_medium_changed(void)
{
long size;
CDROM_TOC toc;
int ret = 0;
plat_cdrom_open();
int temp = DeviceIoControl(handle, IOCTL_CDROM_READ_TOC,
NULL, 0, &toc, sizeof(toc),
(LPDWORD)&size, NULL);
plat_cdrom_close();
if (!temp)
/* There has been some kind of error - not a medium change, but a not ready
condition. */
ret = -1;
else if (!toc_valid || (memcmp(ioctl_path, old_ioctl_path, sizeof(ioctl_path)) != 0)) {
/* Changed to a different host drive - we already detect such medium changes. */
toc_valid = 1;
cur_toc = toc;
if (memcmp(ioctl_path, old_ioctl_path, sizeof(ioctl_path)) != 0)
memcpy(old_ioctl_path, ioctl_path, sizeof(ioctl_path));
} else if ((toc.TrackData[toc.LastTrack].Address[1] !=
cur_toc.TrackData[cur_toc.LastTrack].Address[1]) ||
(toc.TrackData[toc.LastTrack].Address[2] !=
cur_toc.TrackData[cur_toc.LastTrack].Address[2]) ||
(toc.TrackData[toc.LastTrack].Address[3] !=
cur_toc.TrackData[cur_toc.LastTrack].Address[3]))
/* The TOC has changed. */
ret = 1;
win_cdrom_ioctl_log("plat_cdrom_ext_medium_changed(): %i\n", ret);
return ret;
}
void
plat_cdrom_get_audio_tracks(int *st_track, int *end, TMSF *lead_out)
{
plat_cdrom_read_toc();
*st_track = 1;
*end = cur_toc.LastTrack;
lead_out->min = cur_toc.TrackData[cur_toc.LastTrack].Address[1];
lead_out->sec = cur_toc.TrackData[cur_toc.LastTrack].Address[2];
lead_out->fr = cur_toc.TrackData[cur_toc.LastTrack].Address[3];
win_cdrom_ioctl_log("plat_cdrom_get_audio_tracks(): %02i, %02i, %02i:%02i:%02i\n",
*st_track, *end, lead_out->min, lead_out->sec, lead_out->fr);
}
/* This replaces both Info and EndInfo, they are specified by a variable. */
int
plat_cdrom_get_audio_track_info(UNUSED(int end), int track, int *track_num, TMSF *start, uint8_t *attr)
{
plat_cdrom_read_toc();
if ((track < 1) || (track == 0xaa) || (track > (cur_toc.LastTrack + 1))) {
win_cdrom_ioctl_log("plat_cdrom_get_audio_track_info(%02i)\n", track);
return 0;
}
start->min = cur_toc.TrackData[track - 1].Address[1];
start->sec = cur_toc.TrackData[track - 1].Address[2];
start->fr = cur_toc.TrackData[track - 1].Address[3];
*track_num = cur_toc.TrackData[track - 1].TrackNumber;
*attr = cur_toc.TrackData[track - 1].Control;
*attr |= ((cur_toc.TrackData[track - 1].Adr << 4) & 0xf0);
win_cdrom_ioctl_log("plat_cdrom_get_audio_track_info(%02i): %02i:%02i:%02i, %02i, %02X\n",
track, start->min, start->sec, start->fr, *track_num, *attr);
return 1;
}
/* TODO: See if track start is adjusted by 150 or not. */
int
plat_cdrom_get_audio_sub(UNUSED(uint32_t sector), uint8_t *attr, uint8_t *track, uint8_t *index, TMSF *rel_pos, TMSF *abs_pos)
{
CDROM_SUB_Q_DATA_FORMAT insub;
SUB_Q_CHANNEL_DATA sub;
long size = 0;
insub.Format = IOCTL_CDROM_CURRENT_POSITION;
plat_cdrom_open();
DeviceIoControl(handle, IOCTL_CDROM_READ_Q_CHANNEL, &insub, sizeof(insub), &sub, sizeof(sub), (LPDWORD)&size, NULL);
plat_cdrom_close();
if (sub.CurrentPosition.TrackNumber < 1)
return 0;
*track = sub.CurrentPosition.TrackNumber;
*attr = sub.CurrentPosition.Control;
*attr |= ((sub.CurrentPosition.ADR << 4) & 0xf0);
*index = sub.CurrentPosition.IndexNumber;
rel_pos->min = sub.CurrentPosition.TrackRelativeAddress[1];
rel_pos->sec = sub.CurrentPosition.TrackRelativeAddress[2];
rel_pos->fr = sub.CurrentPosition.TrackRelativeAddress[3];
abs_pos->min = sub.CurrentPosition.AbsoluteAddress[1];
abs_pos->sec = sub.CurrentPosition.AbsoluteAddress[2];
abs_pos->fr = sub.CurrentPosition.AbsoluteAddress[3];
win_cdrom_ioctl_log("plat_cdrom_get_audio_sub(): %02i, %02X, %02i, %02i:%02i:%02i, %02i:%02i:%02i\n",
*track, *attr, *index, rel_pos->min, rel_pos->sec, rel_pos->fr, abs_pos->min, abs_pos->sec, abs_pos->fr);
return 1;
}
int
plat_cdrom_get_sector_size(UNUSED(uint32_t sector))
{
long size;
DISK_GEOMETRY dgCDROM;
plat_cdrom_open();
DeviceIoControl(handle, IOCTL_CDROM_GET_DRIVE_GEOMETRY, NULL, 0, &dgCDROM, sizeof(dgCDROM), (LPDWORD)&size, NULL);
plat_cdrom_close();
win_cdrom_ioctl_log("BytesPerSector=%d\n", dgCDROM.BytesPerSector);
return dgCDROM.BytesPerSector;
}
int
plat_cdrom_read_sector(uint8_t *buffer, int raw, uint32_t sector)
{
BOOL status;
long size = 0;
int buflen = raw ? RAW_SECTOR_SIZE : COOKED_SECTOR_SIZE;
plat_cdrom_open();
if (raw) {
win_cdrom_ioctl_log("Raw\n");
/* Raw */
RAW_READ_INFO in;
in.DiskOffset.LowPart = sector * COOKED_SECTOR_SIZE;
in.DiskOffset.HighPart = 0;
in.SectorCount = 1;
in.TrackMode = CDDA;
status = DeviceIoControl(handle, IOCTL_CDROM_RAW_READ, &in, sizeof(in),
buffer, buflen, (LPDWORD)&size, NULL);
} else {
win_cdrom_ioctl_log("Cooked\n");
/* Cooked */
int success = 0;
DWORD newPos = SetFilePointer(handle, sector * COOKED_SECTOR_SIZE, 0, FILE_BEGIN);
if (newPos != 0xFFFFFFFF)
success = ReadFile(handle, buffer, buflen, (LPDWORD)&size, NULL);
status = (success != 0);
}
plat_cdrom_close();
win_cdrom_ioctl_log("ReadSector status=%d, sector=%d, size=%" PRId64 ".\n", status, sector, (long long) size);
return (size == buflen) && (status > 0);
}
void
plat_cdrom_eject(void)
{
long size;
plat_cdrom_open();
DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, (LPDWORD)&size, NULL);
plat_cdrom_close();
}
void
plat_cdrom_close(void)
{
if (handle != NULL) {
CloseHandle(handle);
handle = NULL;
}
}
int
plat_cdrom_set_drive(const char *drv)
{
plat_cdrom_close();
memcpy(old_ioctl_path, ioctl_path, sizeof(ioctl_path));
memset(ioctl_path, 0x00, sizeof(ioctl_path));
wsprintf(ioctl_path, L"%S", drv);
win_cdrom_ioctl_log("Path is %S\n", ioctl_path);
toc_valid = 0;
plat_cdrom_load();
return 1;
}
``` | /content/code_sandbox/src/qt/win_cdrom_ioctl.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 4,014 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Header file for windows raw input native filter for QT
*
*
*
* Authors: Teemu Korhonen
*
*
* This program is free software; you can redistribute it and/or
* as published by the Free Software Foundation; either version 2
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef QT_WINDOWSRAWINPUTFILTER_HPP
#define QT_WINDOWSRAWINPUTFILTER_HPP
#include <QObject>
#include <QMainWindow>
#include <QAbstractNativeEventFilter>
#include <QByteArray>
#include <windows.h>
#include <memory>
#include "qt_mainwindow.hpp"
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
# define result_t qintptr
#else
# define result_t long
#endif
class WindowsRawInputFilter : public QObject, public QAbstractNativeEventFilter {
Q_OBJECT
public:
static std::unique_ptr<WindowsRawInputFilter> Register(MainWindow *window);
bool nativeEventFilter(const QByteArray &eventType, void *message, result_t *result) override;
~WindowsRawInputFilter();
private:
MainWindow *window;
uint16_t scancode_map[768];
int buttons = 0;
int dx = 0;
int dy = 0;
int dwheel = 0;
int menus_open = 0;
WindowsRawInputFilter(MainWindow *window);
void handle_input(HRAWINPUT input);
void keyboard_handle(PRAWINPUT raw);
void mouse_handle(PRAWINPUT raw);
static UINT16 convert_scan_code(UINT16 scan_code);
void keyboard_getkeymap();
};
#endif
``` | /content/code_sandbox/src/qt/qt_winrawinputfilter.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 494 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Hardware renderer module.
*
*
*
* Authors: Joakim L. Gilje <jgilje@jgilje.net>
* Cacodemon345
* Teemu Korhonen
*
*/
#include "qt_hardwarerenderer.hpp"
#include <QApplication>
#include <QVector2D>
#include <QOpenGLPixelTransferOptions>
#include <atomic>
#include <cstdint>
#include <vector>
extern "C" {
#include <86box/86box.h>
#include <86box/plat.h>
#include <86box/video.h>
}
void
HardwareRenderer::resizeGL(int w, int h)
{
m_context->makeCurrent(this);
glViewport(0, 0, qRound(w * devicePixelRatio()), qRound(h * devicePixelRatio()));
}
#define PROGRAM_VERTEX_ATTRIBUTE 0
#define PROGRAM_TEXCOORD_ATTRIBUTE 1
void
HardwareRenderer::initializeGL()
{
m_context->makeCurrent(this);
initializeOpenGLFunctions();
auto image = QImage(2048, 2048, QImage::Format_RGB32);
image.fill(0xff000000);
m_texture = new QOpenGLTexture(image);
m_blt = new QOpenGLTextureBlitter;
m_blt->setRedBlueSwizzle(true);
m_blt->create();
QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this);
const char *vsrc = "attribute highp vec4 VertexCoord;\n"
"attribute mediump vec4 TexCoord;\n"
"varying mediump vec4 texc;\n"
"uniform mediump mat4 MVPMatrix;\n"
"void main(void)\n"
"{\n"
" gl_Position = MVPMatrix * VertexCoord;\n"
" texc = TexCoord;\n"
"}\n";
QString vsrccore = "in highp vec4 VertexCoord;\n"
"in mediump vec4 TexCoord;\n"
"out mediump vec4 texc;\n"
"uniform mediump mat4 MVPMatrix;\n"
"void main(void)\n"
"{\n"
" gl_Position = MVPMatrix * VertexCoord;\n"
" texc = TexCoord;\n"
"}\n";
if (m_context->isOpenGLES() && m_context->format().version() >= qMakePair(3, 0)) {
vsrccore.prepend("#version 300 es\n");
vshader->compileSourceCode(vsrccore);
} else if (m_context->format().version() >= qMakePair(3, 0) && m_context->format().profile() == QSurfaceFormat::CoreProfile) {
vsrccore.prepend("#version 130\n");
vshader->compileSourceCode(vsrccore);
} else
vshader->compileSourceCode(vsrc);
QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this);
const char *fsrc = "uniform sampler2D texture;\n"
"varying mediump vec4 texc;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = texture2D(texture, texc.st).bgra;\n"
"}\n";
QString fsrccore = "uniform sampler2D texture;\n"
"in mediump vec4 texc;\n"
"out highp vec4 FragColor;\n"
"void main(void)\n"
"{\n"
" FragColor = texture2D(texture, texc.st).bgra;\n"
"}\n";
if (m_context->isOpenGLES() && m_context->format().version() >= qMakePair(3, 0)) {
fsrccore.prepend("#version 300 es\n");
fshader->compileSourceCode(fsrccore);
} else if (m_context->format().version() >= qMakePair(3, 0) && m_context->format().profile() == QSurfaceFormat::CoreProfile) {
fsrccore.prepend("#version 130\n");
fshader->compileSourceCode(fsrccore);
} else
fshader->compileSourceCode(fsrc);
m_prog = new QOpenGLShaderProgram;
m_prog->addShader(vshader);
m_prog->addShader(fshader);
m_prog->bindAttributeLocation("VertexCoord", PROGRAM_VERTEX_ATTRIBUTE);
m_prog->bindAttributeLocation("TexCoord", PROGRAM_TEXCOORD_ATTRIBUTE);
m_prog->link();
m_prog->bind();
m_prog->setUniformValue("texture", 0);
if (m_context->format().version() >= qMakePair(3, 0) && m_vao.create()) {
m_vao.bind();
}
m_vbo[PROGRAM_VERTEX_ATTRIBUTE].create();
m_vbo[PROGRAM_VERTEX_ATTRIBUTE].bind();
m_vbo[PROGRAM_VERTEX_ATTRIBUTE].allocate(sizeof(QVector2D) * 4);
m_vbo[PROGRAM_TEXCOORD_ATTRIBUTE].create();
m_vbo[PROGRAM_TEXCOORD_ATTRIBUTE].bind();
m_vbo[PROGRAM_TEXCOORD_ATTRIBUTE].allocate(sizeof(QVector2D) * 4);
pclog("OpenGL vendor: %s\n", glGetString(GL_VENDOR));
pclog("OpenGL renderer: %s\n", glGetString(GL_RENDERER));
pclog("OpenGL version: %s\n", glGetString(GL_VERSION));
pclog("OpenGL shader language version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
glClearColor(0, 0, 0, 1);
m_texture->setWrapMode(QOpenGLTexture::ClampToEdge);
glClear(GL_COLOR_BUFFER_BIT);
m_context->swapBuffers(this);
}
void
HardwareRenderer::paintGL()
{
m_context->makeCurrent(this);
glClear(GL_COLOR_BUFFER_BIT);
QVector<QVector2D> verts;
QVector<QVector2D> texcoords;
QMatrix4x4 mat;
mat.setToIdentity();
mat.ortho(QRectF(0, 0, (qreal) width(), (qreal) height()));
verts.push_back(QVector2D((float) destination.x(), (float) destination.y()));
verts.push_back(QVector2D((float) destination.x(), (float) destination.y() + (float) destination.height()));
verts.push_back(QVector2D((float) destination.x() + (float) destination.width(), (float) destination.y() + (float) destination.height()));
verts.push_back(QVector2D((float) destination.x() + (float) destination.width(), (float) destination.y()));
texcoords.push_back(QVector2D((float) source.x() / 2048.f, (float) (source.y()) / 2048.f));
texcoords.push_back(QVector2D((float) source.x() / 2048.f, (float) (source.y() + source.height()) / 2048.f));
texcoords.push_back(QVector2D((float) (source.x() + source.width()) / 2048.f, (float) (source.y() + source.height()) / 2048.f));
texcoords.push_back(QVector2D((float) (source.x() + source.width()) / 2048.f, (float) (source.y()) / 2048.f));
m_vbo[PROGRAM_VERTEX_ATTRIBUTE].bind();
m_vbo[PROGRAM_VERTEX_ATTRIBUTE].write(0, verts.data(), sizeof(QVector2D) * 4);
m_vbo[PROGRAM_VERTEX_ATTRIBUTE].release();
m_vbo[PROGRAM_TEXCOORD_ATTRIBUTE].bind();
m_vbo[PROGRAM_TEXCOORD_ATTRIBUTE].write(0, texcoords.data(), sizeof(QVector2D) * 4);
m_vbo[PROGRAM_TEXCOORD_ATTRIBUTE].release();
m_prog->setUniformValue("MVPMatrix", mat);
m_prog->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
m_prog->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
m_vbo[PROGRAM_VERTEX_ATTRIBUTE].bind();
m_prog->setAttributeBuffer(PROGRAM_VERTEX_ATTRIBUTE, GL_FLOAT, 0, 2, 0);
m_vbo[PROGRAM_VERTEX_ATTRIBUTE].release();
m_vbo[PROGRAM_TEXCOORD_ATTRIBUTE].bind();
m_prog->setAttributeBuffer(PROGRAM_TEXCOORD_ATTRIBUTE, GL_FLOAT, 0, 2, 0);
m_vbo[PROGRAM_TEXCOORD_ATTRIBUTE].release();
m_texture->bind();
m_texture->setMinMagFilters(video_filter_method ? QOpenGLTexture::Linear : QOpenGLTexture::Nearest, video_filter_method ? QOpenGLTexture::Linear : QOpenGLTexture::Nearest);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
void
HardwareRenderer::setRenderType(RenderType type)
{
QSurfaceFormat format;
switch (type) {
case RenderType::OpenGL3:
format.setVersion(3, 0);
format.setProfile(QSurfaceFormat::CoreProfile);
case RenderType::OpenGL:
format.setRenderableType(QSurfaceFormat::OpenGL);
break;
case RenderType::OpenGLES:
format.setRenderableType(QSurfaceFormat::OpenGLES);
break;
}
format.setSwapInterval(0);
setFormat(format);
}
void
HardwareRenderer::onBlit(int buf_idx, int x, int y, int w, int h)
{
auto tval = this;
void *nuldata = 0;
if (memcmp(&tval, &nuldata, sizeof(void *)) == 0)
return;
auto origSource = source;
if (!m_texture || !m_texture->isCreated()) {
buf_usage[buf_idx].clear();
source.setRect(x, y, w, h);
return;
}
m_context->makeCurrent(this);
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
m_texture->setData(x, y, 0, w, h, 0, QOpenGLTexture::PixelFormat::RGBA, QOpenGLTexture::PixelType::UInt8, (const void *) ((uintptr_t) imagebufs[buf_idx].get() + (uintptr_t) (2048 * 4 * y + x * 4)), &m_transferOptions);
#else
m_texture->bind();
glPixelStorei(GL_UNPACK_ROW_LENGTH, 2048);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, QOpenGLTexture::PixelFormat::RGBA, QOpenGLTexture::PixelType::UInt8, (const void *) ((uintptr_t) imagebufs[buf_idx].get() + (uintptr_t) (2048 * 4 * y + x * 4)));
m_texture->release();
#endif
buf_usage[buf_idx].clear();
source.setRect(x, y, w, h);
if (origSource != source)
onResize(this->width(), this->height());
update();
}
void
HardwareRenderer::resizeEvent(QResizeEvent *event)
{
onResize(width(), height());
QOpenGLWindow::resizeEvent(event);
}
bool
HardwareRenderer::event(QEvent *event)
{
bool res = false;
if (!eventDelegate(event, res))
return QOpenGLWindow::event(event);
return res;
}
std::vector<std::tuple<uint8_t *, std::atomic_flag *>>
HardwareRenderer::getBuffers()
{
std::vector<std::tuple<uint8_t *, std::atomic_flag *>> buffers;
buffers.push_back(std::make_tuple(imagebufs[0].get(), &buf_usage[0]));
buffers.push_back(std::make_tuple(imagebufs[1].get(), &buf_usage[1]));
return buffers;
}
``` | /content/code_sandbox/src/qt/qt_hardwarerenderer.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,605 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Media history management module
*
*
*
* Authors: cold-brewed
*
*/
#include <QApplication>
#include <QFileInfo>
#include <QMetaEnum>
#include <QStringBuilder>
#include <utility>
#include "qt_mediahistorymanager.hpp"
extern "C" {
#include <86box/timer.h>
#include <86box/cdrom.h>
#include <86box/fdd.h>
}
namespace ui {
MediaHistoryManager::MediaHistoryManager()
{
initializeImageHistory();
deserializeAllImageHistory();
initialDeduplication();
}
MediaHistoryManager::~MediaHistoryManager()
= default;
master_list_t &
MediaHistoryManager::blankImageHistory(master_list_t &initialized_master_list) const
{
for (const auto device_type : ui::AllSupportedMediaHistoryTypes) {
device_media_history_t device_media_history;
// Loop for all possible media devices
for (int device_index = 0; device_index < maxDevicesSupported(device_type); device_index++) {
device_index_list_t indexing_list;
device_media_history[device_index] = indexing_list;
// Loop for each history slot
for (int slot_index = 0; slot_index < max_images; slot_index++) {
device_media_history[device_index].append(QString());
}
}
initialized_master_list.insert(device_type, device_media_history);
}
return initialized_master_list;
}
const device_index_list_t &
MediaHistoryManager::getHistoryListForDeviceIndex(int index, ui::MediaType type)
{
if (master_list.contains(type)) {
if ((index >= 0) && (index < master_list[type].size())) {
return master_list[type][index];
} else {
qWarning("Media device index %i for device type %s was requested but index %i is out of range (valid range: >= 0 && < %lli)",
index, mediaTypeToString(type).toUtf8().constData(), index, static_cast<long long>(master_list[type].size()));
}
}
// Failure gets an empty list
return empty_device_index_list;
}
void
MediaHistoryManager::setHistoryListForDeviceIndex(int index, ui::MediaType type, device_index_list_t history_list)
{
master_list[type][index] = std::move(history_list);
}
QString
MediaHistoryManager::getImageForSlot(int index, int slot, ui::MediaType type)
{
QString image_name;
device_index_list_t device_history = getHistoryListForDeviceIndex(index, type);
if ((slot >= 0) && (slot < device_history.size())) {
image_name = device_history[slot];
} else {
qWarning("Media history slot %i, index %i for device type %s was requested but slot %i is out of range (valid range: >= 0 && < %i, device_history.size() is %lli)",
slot, index, mediaTypeToString(type).toUtf8().constData(), slot, maxDevicesSupported(type), static_cast<long long>(device_history.size()));
}
return image_name;
}
// These are hardcoded since we can't include the various
// header files where they are defined (e.g., fdd.h, mo.h).
// However, all in ui::MediaType support 4 except cassette.
int
MediaHistoryManager::maxDevicesSupported(ui::MediaType type)
{
return type == ui::MediaType::Cassette ? 1 : 4;
}
void
MediaHistoryManager::deserializeImageHistoryType(ui::MediaType type)
{
for (int device = 0; device < maxDevicesSupported(type); device++) {
char **device_history_ptr = getEmuHistoryVarForType(type, device);
if (device_history_ptr == nullptr) {
// Device not supported, return and do not deserialize.
// This will leave the image listing at the default initialization state
// from the ui side (this class)
continue;
}
for (int slot = 0; slot < MAX_PREV_IMAGES; slot++) {
master_list[type][device][slot] = device_history_ptr[slot];
}
}
}
void
MediaHistoryManager::deserializeAllImageHistory()
{
for (const auto device_type : ui::AllSupportedMediaHistoryTypes) {
deserializeImageHistoryType(device_type);
}
}
void
MediaHistoryManager::serializeImageHistoryType(ui::MediaType type)
{
for (int device = 0; device < maxDevicesSupported(type); device++) {
char **device_history_ptr = getEmuHistoryVarForType(type, device);
if (device_history_ptr == nullptr) {
// Device not supported, return and do not serialize.
// This will leave the image listing at the current state,
// and it will not be saved on the emu side
continue;
}
for (int slot = 0; slot < MAX_PREV_IMAGES; slot++) {
if (device_history_ptr[slot] != nullptr) {
strncpy(device_history_ptr[slot], master_list[type][device][slot].toUtf8().constData(), MAX_IMAGE_PATH_LEN);
}
}
}
}
void
MediaHistoryManager::serializeAllImageHistory()
{
for (const auto device_type : ui::AllSupportedMediaHistoryTypes) {
serializeImageHistoryType(device_type);
}
}
void
MediaHistoryManager::initialDeduplication()
{
QString current_image;
// Perform initial dedup if an image is loaded
for (const auto device_type : ui::AllSupportedMediaHistoryTypes) {
for (int device_index = 0; device_index < maxDevicesSupported(device_type); device_index++) {
device_index_list_t device_history = getHistoryListForDeviceIndex(device_index, device_type);
switch (device_type) {
case ui::MediaType::Optical:
current_image = cdrom[device_index].image_path;
break;
case ui::MediaType::Floppy:
current_image = floppyfns[device_index];
break;
default:
continue;
break;
}
deduplicateList(device_history, QVector<QString>(1, current_image));
// Fill in missing, if any
int missing = MAX_PREV_IMAGES - device_history.size();
if (missing) {
for (int i = 0; i < missing; i++) {
device_history.push_back(QString());
}
}
setHistoryListForDeviceIndex(device_index, device_type, device_history);
}
}
}
char **
MediaHistoryManager::getEmuHistoryVarForType(ui::MediaType type, int index)
{
switch (type) {
case ui::MediaType::Optical:
return &cdrom[index].image_history[0];
case ui::MediaType::Floppy:
return &fdd_image_history[index][0];
default:
return nullptr;
}
}
device_index_list_t &
MediaHistoryManager::deduplicateList(device_index_list_t &device_history, const QVector<QString> &filenames)
{
QVector<QString> items_to_delete;
for (auto &list_item_path : device_history) {
if (list_item_path.isEmpty()) {
continue;
}
for (const auto &path_to_check : filenames) {
if (path_to_check.isEmpty()) {
continue;
}
QString adjusted_path = pathAdjustSingle(path_to_check);
int match = QString::localeAwareCompare(list_item_path, adjusted_path);
if (match == 0) {
items_to_delete.append(list_item_path);
}
}
}
// Remove by name rather than index because the index would change
// after each removal
for (const auto &path : items_to_delete) {
device_history.removeAll(path);
}
return device_history;
}
void
MediaHistoryManager::addImageToHistory(int index, ui::MediaType type, const QString &image_name, const QString &new_image_name)
{
device_index_list_t device_history = getHistoryListForDeviceIndex(index, type);
QVector<QString> files_to_check;
files_to_check.append(image_name);
files_to_check.append(new_image_name);
device_history = deduplicateList(device_history, files_to_check);
if (!image_name.isEmpty()) {
device_history.push_front(image_name);
}
// Pop any extras
if (device_history.size() > MAX_PREV_IMAGES) {
device_history.pop_back();
}
// Fill in missing, if any
int missing = MAX_PREV_IMAGES - device_history.size();
if (missing) {
for (int i = 0; i < missing; i++) {
device_history.push_back(QString());
}
}
device_history = removeMissingImages(device_history);
device_history = pathAdjustFull(device_history);
setHistoryListForDeviceIndex(index, type, device_history);
serializeImageHistoryType(type);
}
QString
MediaHistoryManager::mediaTypeToString(ui::MediaType type)
{
QMetaEnum qme = QMetaEnum::fromType<ui::MediaType>();
return qme.valueToKey(static_cast<int>(type));
}
QString
MediaHistoryManager::pathAdjustSingle(QString checked_path)
{
QString current_usr_path = getUsrPath();
QFileInfo file_info(checked_path);
if (file_info.filePath().isEmpty() || current_usr_path.isEmpty() || file_info.isRelative()) {
return checked_path;
}
if (file_info.filePath().startsWith(current_usr_path)) {
checked_path = file_info.filePath().remove(current_usr_path);
}
return checked_path;
}
device_index_list_t &
MediaHistoryManager::pathAdjustFull(device_index_list_t &device_history)
{
for (auto &checked_path : device_history) {
checked_path = pathAdjustSingle(checked_path);
}
return device_history;
}
QString
MediaHistoryManager::getUsrPath()
{
QString current_usr_path(usr_path);
// Ensure `usr_path` has a trailing slash
return current_usr_path.endsWith("/") ? current_usr_path : current_usr_path.append("/");
}
device_index_list_t &
MediaHistoryManager::removeMissingImages(device_index_list_t &device_history)
{
for (auto &checked_path : device_history) {
QFileInfo file_info(checked_path);
if (file_info.filePath().isEmpty()) {
continue;
}
// For this check, explicitly prepend `usr_path` to relative paths to account for $CWD platform variances
QFileInfo absolute_path = file_info.isRelative() ? QFileInfo(getUsrPath().append(file_info.filePath())) : file_info;
if ((file_info.filePath().left(8) != "ioctl://") && !absolute_path.exists()) {
qWarning("Image file %s does not exist - removing from history", qPrintable(file_info.filePath()));
checked_path = "";
}
}
return device_history;
}
void
MediaHistoryManager::initializeImageHistory()
{
auto initial_master_list = getMasterList();
setMasterList(blankImageHistory(initial_master_list));
}
const master_list_t &
MediaHistoryManager::getMasterList() const
{
return master_list;
}
void
MediaHistoryManager::setMasterList(const master_list_t &masterList)
{
master_list = masterList;
}
void
MediaHistoryManager::clearImageHistory()
{
initializeImageHistory();
serializeAllImageHistory();
}
} // ui
``` | /content/code_sandbox/src/qt/qt_mediahistorymanager.cpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 2,467 |
```c++
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Header for OpenGL renderer options dialog
*
* Authors: Teemu Korhonen
*
*/
#ifndef QT_OPENGLOPTIONSDIALOG_H
#define QT_OPENGLOPTIONSDIALOG_H
#include <QDialog>
#include <functional>
#include "qt_opengloptions.hpp"
namespace Ui {
class OpenGLOptionsDialog;
}
class OpenGLOptionsDialog : public QDialog {
Q_OBJECT
public:
explicit OpenGLOptionsDialog(QWidget *parent, const OpenGLOptions &options, std::function<OpenGLOptions *()> optionsFactory);
~OpenGLOptionsDialog();
signals:
void optionsChanged(OpenGLOptions *options);
public slots:
void accept() override;
private:
Ui::OpenGLOptionsDialog *ui;
std::function<OpenGLOptions *()> createOptions;
private slots:
void on_addShader_clicked();
};
#endif // QT_OPENGLOPTIONSDIALOG_H
``` | /content/code_sandbox/src/qt/qt_opengloptionsdialog.hpp | c++ | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 269 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* Implementation of the Intel 1 Mbit and 2 Mbit, 8-bit and
* 16-bit flash devices.
*
*
*
* Authors: Sarah Walker, <path_to_url
* Miran Grca, <mgrca8@gmail.com>
*
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <86box/86box.h>
#include <86box/device.h>
#include <86box/mem.h>
#include <86box/machine.h>
#include <86box/timer.h>
#include <86box/nvr.h>
#include <86box/plat.h>
#define FLAG_WORD 4
#define FLAG_BXB 2
#define FLAG_INV_A16 1
enum {
BLOCK_MAIN1,
BLOCK_MAIN2,
BLOCK_DATA1,
BLOCK_DATA2,
BLOCK_BOOT,
BLOCKS_NUM
};
enum {
CMD_SET_READ = 0x00,
CMD_READ_SIGNATURE = 0x90,
CMD_ERASE = 0x20,
CMD_ERASE_CONFIRM = 0x20,
CMD_ERASE_VERIFY = 0xA0,
CMD_PROGRAM = 0x40,
CMD_PROGRAM_VERIFY = 0xC0,
CMD_RESET = 0xFF
};
typedef struct flash_t {
uint8_t command;
uint8_t pad;
uint8_t pad0;
uint8_t pad1;
uint8_t *array;
mem_mapping_t mapping;
mem_mapping_t mapping_h[2];
} flash_t;
static char flash_path[1024];
static uint8_t
flash_read(uint32_t addr, void *priv)
{
const flash_t *dev = (flash_t *) priv;
uint8_t ret = 0xff;
addr &= biosmask;
switch (dev->command) {
case CMD_ERASE_VERIFY:
case CMD_PROGRAM_VERIFY:
case CMD_RESET:
case CMD_SET_READ:
ret = dev->array[addr];
break;
case CMD_READ_SIGNATURE:
if (addr == 0x00000)
ret = 0x31; /* CATALYST */
else if (addr == 0x00001)
ret = 0xB4; /* 28F010 */
break;
default:
break;
}
return ret;
}
static uint16_t
flash_readw(uint32_t addr, void *priv)
{
flash_t *dev = (flash_t *) priv;
const uint16_t *q;
addr &= biosmask;
q = (uint16_t *) &(dev->array[addr]);
return *q;
}
static uint32_t
flash_readl(uint32_t addr, void *priv)
{
flash_t *dev = (flash_t *) priv;
const uint32_t *q;
addr &= biosmask;
q = (uint32_t *) &(dev->array[addr]);
return *q;
}
static void
flash_write(uint32_t addr, uint8_t val, void *priv)
{
flash_t *dev = (flash_t *) priv;
addr &= biosmask;
switch (dev->command) {
case CMD_ERASE:
if (val == CMD_ERASE_CONFIRM)
memset(dev->array, 0xff, biosmask + 1);
break;
case CMD_PROGRAM:
dev->array[addr] = val;
break;
default:
dev->command = val;
break;
}
}
static void
flash_writew(UNUSED(uint32_t addr), UNUSED(uint16_t val), UNUSED(void *priv))
{
//
}
static void
flash_writel(UNUSED(uint32_t addr), UNUSED(uint32_t val), UNUSED(void *priv))
{
//
}
static void
catalyst_flash_add_mappings(flash_t *dev)
{
memcpy(dev->array, rom, biosmask + 1);
mem_mapping_add(&dev->mapping, 0xe0000, 0x20000,
flash_read, flash_readw, flash_readl,
flash_write, flash_writew, flash_writel,
dev->array, MEM_MAPPING_EXTERNAL | MEM_MAPPING_ROM | MEM_MAPPING_ROMCS, (void *) dev);
mem_mapping_add(&(dev->mapping_h[0]), 0xfffc0000, 0x20000,
flash_read, flash_readw, flash_readl,
flash_write, flash_writew, flash_writel,
dev->array, MEM_MAPPING_EXTERNAL | MEM_MAPPING_ROM | MEM_MAPPING_ROMCS, (void *) dev);
mem_mapping_add(&(dev->mapping_h[1]), 0xfffe0000, 0x20000,
flash_read, flash_readw, flash_readl,
flash_write, flash_writew, flash_writel,
dev->array, MEM_MAPPING_EXTERNAL | MEM_MAPPING_ROM | MEM_MAPPING_ROMCS, (void *) dev);
}
static void
catalyst_flash_reset(void *priv)
{
flash_t *dev = (flash_t *) priv;
dev->command = CMD_RESET;
}
static void *
catalyst_flash_init(UNUSED(const device_t *info))
{
FILE *fp;
flash_t *dev;
dev = malloc(sizeof(flash_t));
memset(dev, 0, sizeof(flash_t));
sprintf(flash_path, "%s.bin", machine_get_internal_name_ex(machine));
mem_mapping_disable(&bios_mapping);
mem_mapping_disable(&bios_high_mapping);
dev->array = (uint8_t *) malloc(0x20000);
memset(dev->array, 0xff, 0x20000);
catalyst_flash_add_mappings(dev);
dev->command = CMD_RESET;
fp = nvr_fopen(flash_path, "rb");
if (fp) {
(void) !fread(dev->array, 0x20000, 1, fp);
fclose(fp);
}
return dev;
}
static void
catalyst_flash_close(void *priv)
{
FILE *fp;
flash_t *dev = (flash_t *) priv;
fp = nvr_fopen(flash_path, "wb");
fwrite(dev->array, 0x20000, 1, fp);
fclose(fp);
free(dev->array);
dev->array = NULL;
free(dev);
}
const device_t catalyst_flash_device = {
.name = "Catalyst 28F010-D Flash BIOS",
.internal_name = "catalyst_flash",
.flags = DEVICE_PCI,
.local = 0,
.init = catalyst_flash_init,
.close = catalyst_flash_close,
.reset = catalyst_flash_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/mem/catalyst_flash.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 1,545 |
```c
/*
* 86Box A hypervisor and IBM PC system emulator that specializes in
* running old operating systems and software designed for IBM
* PC systems and compatibles from 1981 through fairly recent
* system designs based on the PCI bus.
*
* This file is part of the 86Box distribution.
*
* DRAM row handling.
*
* Authors: Miran Grca, <mgrca8@gmail.com>
*
*/
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#define HAVE_STDARG_H
#include <86box/86box.h>
#include "cpu.h"
#include "x86_ops.h"
#include "x86.h"
#include <86box/config.h>
#include <86box/device.h>
#include <86box/io.h>
#include <86box/mem.h>
#include <86box/spd.h>
#include <86box/row.h>
#include <86box/plat_unused.h>
/* 0 1 2 3 4 5 6 7 */
static uint8_t rows_num;
static uint8_t rows_default;
static uint8_t rows_bits;
static uint32_t row_unit;
static uint8_t drb_defaults[16];
static row_t *rows;
static uint8_t
row_read(uint32_t addr, void *priv)
{
const row_t *dev = (row_t *) priv;
uint32_t new_addr = ((addr - dev->host_base) & dev->ram_mask) + dev->ram_base;
addreadlookup(mem_logical_addr, new_addr);
return dev->buf[new_addr];
}
static uint16_t
row_readw(uint32_t addr, void *priv)
{
row_t *dev = (row_t *) priv;
uint32_t new_addr = ((addr - dev->host_base) & dev->ram_mask) + dev->ram_base;
addreadlookup(mem_logical_addr, new_addr);
return *(uint16_t *) &(dev->buf[new_addr]);
}
static uint32_t
row_readl(uint32_t addr, void *priv)
{
row_t *dev = (row_t *) priv;
uint32_t new_addr = ((addr - dev->host_base) & dev->ram_mask) + dev->ram_base;
addreadlookup(mem_logical_addr, new_addr);
return *(uint32_t *) &(dev->buf[new_addr]);
}
static void
row_write(uint32_t addr, uint8_t val, void *priv)
{
const row_t *dev = (row_t *) priv;
uint32_t new_addr = ((addr - dev->host_base) & dev->ram_mask) + dev->ram_base;
addwritelookup(mem_logical_addr, new_addr);
mem_write_ramb_page(new_addr, val, &pages[addr >> 12]);
}
static void
row_writew(uint32_t addr, uint16_t val, void *priv)
{
const row_t *dev = (row_t *) priv;
uint32_t new_addr = ((addr - dev->host_base) & dev->ram_mask) + dev->ram_base;
addwritelookup(mem_logical_addr, new_addr);
mem_write_ramw_page(new_addr, val, &pages[addr >> 12]);
}
static void
row_writel(uint32_t addr, uint32_t val, void *priv)
{
const row_t *dev = (row_t *) priv;
uint32_t new_addr = ((addr - dev->host_base) & dev->ram_mask) + dev->ram_base;
addwritelookup(mem_logical_addr, new_addr);
mem_write_raml_page(new_addr, val, &pages[addr >> 12]);
}
void
row_allocate(uint8_t row_id, uint8_t set)
{
uint32_t offset;
/* Do nothing if size is either zero or invalid. */
if ((rows[row_id].host_size == 0x00000000) || (rows[row_id].host_size == 0xffffffff))
return;
if (rows[row_id].ram_size == 0x00000000)
return;
for (uint32_t c = (rows[row_id].host_base >> 12); c < ((rows[row_id].host_base + rows[row_id].host_size) >> 12); c++) {
offset = c - (rows[row_id].host_base >> 12);
pages[c].mem = set ? (rows[row_id].buf + rows[row_id].ram_base + ((offset << 12) & rows[row_id].ram_mask)) : page_ff;
pages[c].write_b = set ? mem_write_ramb_page : NULL;
pages[c].write_w = set ? mem_write_ramw_page : NULL;
pages[c].write_l = set ? mem_write_raml_page : NULL;
#ifdef USE_NEW_DYNAREC
pages[c].evict_prev = EVICT_NOT_IN_LIST;
pages[c].byte_dirty_mask = &byte_dirty_mask[offset * 64];
pages[c].byte_code_present_mask = &byte_code_present_mask[offset * 64];
#endif
}
if (rows[row_id].host_base >= 0x00100000) {
mem_set_mem_state_both(rows[row_id].host_base, rows[row_id].host_base + rows[row_id].host_size,
set ? (MEM_READ_INTERNAL | MEM_WRITE_INTERNAL) : (MEM_READ_EXTERNAL | MEM_WRITE_EXTERNAL));
} else {
if (0x000a0000 > rows[row_id].host_base) {
mem_set_mem_state_both(rows[row_id].host_base, 0x000a0000 - rows[row_id].host_base,
set ? (MEM_READ_INTERNAL | MEM_WRITE_INTERNAL) : (MEM_READ_EXTERNAL | MEM_WRITE_EXTERNAL));
}
if ((rows[row_id].host_base + rows[row_id].host_size) > 0x00100000) {
mem_set_mem_state_both(0x00100000, (rows[row_id].host_base + rows[row_id].host_size) - 0x00100000,
set ? (MEM_READ_INTERNAL | MEM_WRITE_INTERNAL) : (MEM_READ_EXTERNAL | MEM_WRITE_EXTERNAL));
}
}
if (set) {
mem_mapping_set_addr(&rows[row_id].mapping, rows[row_id].host_base, rows[row_id].host_size);
mem_mapping_set_exec(&rows[row_id].mapping, rows[row_id].buf + rows[row_id].ram_base);
mem_mapping_set_mask(&rows[row_id].mapping, rows[row_id].ram_mask);
if ((rows[row_id].host_base == rows[row_id].ram_base) && (rows[row_id].host_size == rows[row_id].ram_size)) {
#if (defined __amd64__ || defined _M_X64 || defined __aarch64__ || defined _M_ARM64)
mem_mapping_set_handler(&rows[row_id].mapping, mem_read_ram,mem_read_ramw,mem_read_raml,
mem_write_ram,mem_write_ramw,mem_write_raml);
#else
if (rows[row_id].buf == ram2) {
mem_mapping_set_handler(&rows[row_id].mapping, mem_read_ram_2gb,mem_read_ram_2gbw,mem_read_ram_2gbl,
mem_write_ram,mem_write_ramw,mem_write_raml);
} else {
mem_mapping_set_handler(&rows[row_id].mapping, mem_read_ram,mem_read_ramw,mem_read_raml,
mem_write_ram,mem_write_ramw,mem_write_raml);
}
#endif
} else {
mem_mapping_set_handler(&rows[row_id].mapping, row_read, row_readw, row_readl,
row_write, row_writew, row_writel);
}
} else
mem_mapping_disable(&rows[row_id].mapping);
}
void
row_disable(uint8_t row_id)
{
row_allocate(row_id, 0);
}
void
row_set_boundary(uint8_t row_id, uint32_t boundary)
{
if (row_id >= rows_num)
return;
boundary &= ((1 << rows_bits) - 1);
rows[row_id].host_size = boundary * row_unit;
if (row_id == 0)
rows[row_id].host_base = 0x00000000;
else {
rows[row_id].host_base = rows[row_id - 1].boundary * row_unit;
if (rows[row_id - 1].boundary > boundary)
rows[row_id].host_size = 0x00000000;
else
rows[row_id].host_size -= rows[row_id].host_base;
}
rows[row_id].boundary = boundary;
row_allocate(row_id, 1);
}
void
row_reset(UNUSED(void *priv))
{
uint32_t boundary;
uint32_t shift;
for (int8_t i = (rows_num - 1); i >= 0; i--)
row_disable(i);
for (uint8_t i = 0; i < rows_num; i++) {
shift = (i & 1) << 2;
boundary = ((uint32_t) drb_defaults[i]) + (((((uint32_t) drb_defaults[(i >> 1) + 8]) >> shift) & 0xf) << 8);
row_set_boundary(i, boundary);
}
}
void
row_close(UNUSED(void *priv))
{
free(rows);
rows = NULL;
}
void *
row_init(const device_t *info)
{
uint32_t cur_drb = 0;
uint32_t cur_drbe = 0;
uint32_t last_drb = 0;
uint32_t last_drbe = 0;
uint8_t phys_drbs[16];
int i;
int max = info->local & 0xff;
uint32_t shift;
uint32_t drb;
uint32_t boundary;
uint32_t mask;
row_t *new_rows = NULL;
rows_bits = ((info->local >> 24) & 0xff);
mask = (1 << rows_bits) - 1;
row_unit = ((info->local >> 8) & 0xff);
memset(phys_drbs, 0x00, 16);
spd_write_drbs(phys_drbs, 0x00, max, row_unit);
row_unit <<= 20;
rows_default = (info->local >> 16) & 0xff;
memset(drb_defaults, 0x00, 16);
for (i = 0; i < 8; i++)
drb_defaults[i] = rows_default;
new_rows = calloc(max + 1, sizeof(row_t));
rows_num = max + 1;
rows = new_rows;
mem_mapping_disable(&ram_low_mapping);
mem_mapping_disable(&ram_mid_mapping);
mem_mapping_disable(&ram_high_mapping);
#if (!(defined __amd64__ || defined _M_X64 || defined __aarch64__ || defined _M_ARM64))
if (mem_size > 1048576)
mem_mapping_disable(&ram_2gb_mapping);
#endif
for (uint32_t c = 0; c < pages_sz; c++) {
pages[c].mem = page_ff;
pages[c].write_b = NULL;
pages[c].write_w = NULL;
pages[c].write_l = NULL;
#ifdef USE_NEW_DYNAREC
pages[c].evict_prev = EVICT_NOT_IN_LIST;
pages[c].byte_dirty_mask = &byte_dirty_mask[c * 64];
pages[c].byte_code_present_mask = &byte_code_present_mask[c * 64];
#endif
}
/* Set all memory space above the default allocated area to external. */
boundary = ((uint32_t) rows_default) * row_unit;
mem_set_mem_state_both(boundary, (mem_size << 10) - boundary, MEM_READ_EXTERNAL | MEM_WRITE_EXTERNAL);
for (i = 0; i <= max; i++) {
cur_drb = phys_drbs[i];
cur_drbe = phys_drbs[(i >> 1) + 8];
shift = (i & 1) << 2;
drb = (cur_drb & mask) + (((cur_drbe >> shift) & 0x03) << 8);
rows[i].ram_size = drb * row_unit;
shift = ((i - 1) & 1) << 2;
drb = (last_drb & mask) + (((last_drbe >> shift) & 0x03) << 8);
rows[i].ram_base = drb * row_unit;
rows[i].ram_size -= rows[i].ram_base;
rows[i].buf = ram;
#if (!(defined __amd64__ || defined _M_X64 || defined __aarch64__ || defined _M_ARM64))
if (rows[i].ram_base >= (1 << 30)) {
rows[i].ram_base -= (1 << 30);
rows[i].buf = ram2;
}
#endif
rows[i].ram_mask = rows[i].ram_size - 1;
mem_mapping_add(&rows[i].mapping, rows[i].ram_base, rows[i].ram_size,
row_read, row_readw, row_readl,
row_write, row_writew, row_writel,
rows[i].buf + rows[i].ram_base, MEM_MAPPING_INTERNAL, &(rows[i]));
mem_mapping_disable(&rows[i].mapping);
shift = (i & 1) << 2;
boundary = ((uint32_t) drb_defaults[i]) + ((((uint32_t) drb_defaults[(i >> 1) + 8]) >> shift) << 8);
row_set_boundary(i, boundary);
last_drb = cur_drb;
last_drbe = cur_drbe;
}
flushmmucache();
return new_rows;
}
/* NOTE: NOT const, so that we can patch it at init. */
device_t row_device = {
.name = "DRAM Rows",
.internal_name = "dram_rows",
.flags = DEVICE_AT,
.local = 0x0000,
.init = row_init,
.close = row_close,
.reset = row_reset,
{ .available = NULL },
.speed_changed = NULL,
.force_redraw = NULL,
.config = NULL
};
``` | /content/code_sandbox/src/mem/row.c | c | 2016-06-25T22:29:10 | 2024-08-16T19:09:21 | 86Box | 86Box/86Box | 2,616 | 3,138 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.