Textractor_test/GUI/mainwindow.cpp

351 lines
14 KiB
C++
Raw Normal View History

2018-07-21 15:40:16 -07:00
#include "mainwindow.h"
#include "ui_mainwindow.h"
2018-12-18 12:14:54 -05:00
#include "defs.h"
2018-11-04 02:13:51 -05:00
#include "text.h"
#include "extenwindow.h"
2018-07-25 21:48:18 -07:00
#include "misc.h"
#include "host/util.h"
2019-02-18 22:39:04 -05:00
#include <shellapi.h>
#include <winhttp.h>
#include <QFormLayout>
2018-12-14 22:26:49 -05:00
#include <QPushButton>
2019-02-04 15:53:13 -05:00
#include <QCheckBox>
#include <QSpinBox>
#include <QMessageBox>
2018-08-22 15:11:40 -04:00
#include <QInputDialog>
#include <QFileDialog>
2018-07-23 12:25:02 -07:00
2018-07-21 15:40:16 -07:00
MainWindow::MainWindow(QWidget *parent) :
2018-07-25 10:46:59 -07:00
QMainWindow(parent),
2018-11-01 10:38:14 -04:00
ui(new Ui::MainWindow),
2018-11-10 01:17:02 -05:00
extenWindow(new ExtenWindow(this))
2018-07-21 15:40:16 -07:00
{
2018-07-25 10:46:59 -07:00
ui->setupUi(this);
for (auto[text, slot] : Array<std::tuple<QString, void(MainWindow::*)()>>{
2018-12-18 12:14:54 -05:00
{ ATTACH, &MainWindow::AttachProcess },
{ LAUNCH, &MainWindow::LaunchProcess },
2018-12-18 12:14:54 -05:00
{ DETACH, &MainWindow::DetachProcess },
{ ADD_HOOK, &MainWindow::AddHook },
{ SAVE_HOOKS, &MainWindow::SaveHooks },
{ SETTINGS, &MainWindow::Settings },
{ EXTENSIONS, &MainWindow::Extensions }
2018-12-14 22:26:49 -05:00
})
{
QPushButton* button = new QPushButton(ui->processFrame);
2018-12-14 22:26:49 -05:00
connect(button, &QPushButton::clicked, this, slot);
button->setText(text);
ui->processLayout->addWidget(button);
2018-12-14 22:26:49 -05:00
}
ui->processLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
2018-08-21 22:43:30 -04:00
connect(ui->ttCombo, qOverload<int>(&QComboBox::activated), this, &MainWindow::ViewThread);
2019-01-22 14:57:13 -05:00
connect(ui->textOutput, &QPlainTextEdit::selectionChanged, [this] { if (!(QApplication::mouseButtons() & Qt::LeftButton)) ui->textOutput->copy(); });
2018-12-18 12:14:54 -05:00
QSettings settings(CONFIG_FILE, QSettings::IniFormat);
2019-01-06 00:07:20 -05:00
if (settings.contains(WINDOW)) setGeometry(settings.value(WINDOW).toRect());
2019-02-04 15:53:13 -05:00
TextThread::filterRepetition = settings.value(FILTER_REPETITION, TextThread::filterRepetition).toBool();
2018-12-31 15:06:47 -05:00
TextThread::flushDelay = settings.value(FLUSH_DELAY, TextThread::flushDelay).toInt();
TextThread::maxBufferSize = settings.value(MAX_BUFFER_SIZE, TextThread::maxBufferSize).toInt();
2019-01-05 03:47:32 -05:00
Host::defaultCodepage = settings.value(DEFAULT_CODEPAGE, Host::defaultCodepage).toInt();
2018-08-21 22:43:30 -04:00
Host::Start(
2018-12-18 12:55:11 -05:00
[this](DWORD processId) { ProcessConnected(processId); },
[this](DWORD processId) { ProcessDisconnected(processId); },
2019-02-04 15:18:47 -05:00
[this](TextThread& thread) { ThreadAdded(thread); },
[this](TextThread& thread) { ThreadRemoved(thread); },
[this](TextThread& thread, std::wstring& output) { return SentenceReceived(thread, output); }
2018-08-21 22:43:30 -04:00
);
2019-02-09 00:30:38 -05:00
current = &Host::GetThread(Host::console);
2018-11-04 02:13:51 -05:00
Host::AddConsoleOutput(ABOUT);
2019-02-21 13:18:37 -05:00
DWORD DUMMY;
AttachConsole(ATTACH_PARENT_PROCESS);
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), CL_OPTIONS, wcslen(CL_OPTIONS), &DUMMY, NULL);
2019-02-18 22:39:04 -05:00
std::vector<DWORD> processIds = Util::GetAllProcessIds();
std::vector<std::wstring> processNames;
for (auto processId : processIds) processNames.emplace_back(Util::GetModuleFilename(processId).value_or(L""));
int argc;
std::unique_ptr<LPWSTR[], Functor<LocalFree>> argv(CommandLineToArgvW(GetCommandLineW(), &argc));
for (int i = 0; i < argc; ++i)
if (std::wstring arg = argv[i]; arg[0] == L'/' || arg[0] == L'-')
2019-02-21 13:18:37 -05:00
if (arg[1] == L'p')
2019-02-18 22:39:04 -05:00
if (DWORD processId = _wtoi(arg.substr(2).c_str())) Host::InjectProcess(processId);
else for (int i = 0; i < processIds.size(); ++i)
if (processNames[i].find(L"\\" + arg.substr(2)) != std::wstring::npos) Host::InjectProcess(processIds[i]);
std::thread([]
{
2019-01-09 22:35:01 -05:00
using InternetHandle = AutoHandle<Functor<WinHttpCloseHandle>>;
// Queries GitHub releases API https://developer.github.com/v3/repos/releases/ and checks the last release tag to check if it's the same
2019-01-09 22:35:01 -05:00
if (InternetHandle internet = WinHttpOpen(L"Mozilla/5.0 Textractor", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, 0))
if (InternetHandle connection = WinHttpConnect(internet, L"api.github.com", INTERNET_DEFAULT_HTTPS_PORT, 0))
if (InternetHandle request = WinHttpOpenRequest(connection, L"GET", L"/repos/Artikash/Textractor/releases", NULL, NULL, NULL, WINHTTP_FLAG_SECURE))
if (WinHttpSendRequest(request, NULL, 0, NULL, 0, 0, NULL))
{
DWORD bytesRead;
char buffer[1000] = {};
WinHttpReceiveResponse(request, NULL);
WinHttpReadData(request, buffer, 1000, &bytesRead);
if (abs(strstr(buffer, "/tag/") - strstr(buffer, CURRENT_VERSION)) > 10) Host::AddConsoleOutput(UPDATE_AVAILABLE);
}
}).detach();
2018-07-21 15:40:16 -07:00
}
MainWindow::~MainWindow()
{
QSettings(CONFIG_FILE, QSettings::IniFormat).setValue(WINDOW, geometry());
2018-12-27 18:52:59 -05:00
SetErrorMode(SEM_NOGPFAULTERRORBOX);
2018-12-03 18:31:00 -05:00
ExitProcess(0);
2018-07-21 15:40:16 -07:00
}
2018-07-22 16:53:51 -07:00
void MainWindow::closeEvent(QCloseEvent*)
{
QCoreApplication::quit(); // Need to do this to kill any windows that might've been made by extensions
}
void MainWindow::ProcessConnected(DWORD processId)
2018-07-23 22:57:54 -07:00
{
if (processId == 0) return;
2019-02-03 08:49:58 -05:00
QString process = S(Util::GetModuleFilename(processId).value_or(L"???"));
QMetaObject::invokeMethod(this, [this, process, processId]
{
ui->processCombo->addItem(QString::number(processId, 16).toUpper() + ": " + QFileInfo(process).fileName());
2019-02-03 08:49:58 -05:00
});
if (process == "???") return;
2019-02-03 08:49:58 -05:00
QTextFile(GAME_SAVE_FILE, QIODevice::WriteOnly | QIODevice::Append).write((process + "\n").toUtf8());
2019-02-03 08:49:58 -05:00
QStringList allProcesses = QString(QTextFile(HOOK_SAVE_FILE, QIODevice::ReadOnly).readAll()).split("\n", QString::SkipEmptyParts);
// Can't use QFileInfo::absoluteFilePath since hook save file has '\\' as path separator
auto hookList = std::find_if(allProcesses.rbegin(), allProcesses.rend(), [&](QString hookList) { return hookList.contains(process); });
if (hookList != allProcesses.rend())
for (auto hookInfo : hookList->split(" , "))
2019-02-04 15:18:47 -05:00
if (auto hp = Util::ParseCode(S(hookInfo))) Host::InsertHook(processId, hp.value());
2019-02-12 04:14:08 -05:00
else swscanf_s(S(hookInfo).c_str(), L"|%I64d:%I64d:%[^\n]", &savedThreadCtx.first, &savedThreadCtx.second, savedThreadCode, (unsigned)ARRAYSIZE(savedThreadCode));
2018-07-23 22:57:54 -07:00
}
void MainWindow::ProcessDisconnected(DWORD processId)
2018-07-23 22:57:54 -07:00
{
2019-01-06 02:57:52 -05:00
QMetaObject::invokeMethod(this, [this, processId]
{
ui->processCombo->removeItem(ui->processCombo->findText(QString::number(processId, 16).toUpper() + ":", Qt::MatchStartsWith));
}, Qt::BlockingQueuedConnection);
2018-07-23 22:57:54 -07:00
}
2019-02-04 15:18:47 -05:00
void MainWindow::ThreadAdded(TextThread& thread)
2018-07-23 22:57:54 -07:00
{
2019-02-04 15:18:47 -05:00
std::wstring threadCode = Util::GenerateCode(thread.hp, thread.tp.processId);
QString ttString = TextThreadString(thread) + S(thread.name) + " (" + S(threadCode) + ")";
bool savedMatch = savedThreadCtx.first == thread.tp.ctx && savedThreadCtx.second == thread.tp.ctx2 && savedThreadCode == threadCode;
2019-02-03 08:49:58 -05:00
if (savedMatch) savedThreadCtx.first = savedThreadCtx.second = savedThreadCode[0] = 0;
QMetaObject::invokeMethod(this, [this, ttString, savedMatch]
2019-01-06 02:57:52 -05:00
{
ui->ttCombo->addItem(ttString);
2019-02-03 08:49:58 -05:00
if (savedMatch) ViewThread(ui->ttCombo->count() - 1);
2019-01-06 02:57:52 -05:00
});
}
2019-02-04 15:18:47 -05:00
void MainWindow::ThreadRemoved(TextThread& thread)
{
QString ttString = TextThreadString(thread);
2018-12-18 12:55:11 -05:00
QMetaObject::invokeMethod(this, [this, ttString]
2018-07-25 10:46:59 -07:00
{
int threadIndex = ui->ttCombo->findText(ttString, Qt::MatchStartsWith);
2019-02-03 08:49:58 -05:00
if (threadIndex == ui->ttCombo->currentIndex()) ViewThread(0);
ui->ttCombo->removeItem(threadIndex);
2019-01-06 02:57:52 -05:00
}, Qt::BlockingQueuedConnection);
2018-07-23 22:57:54 -07:00
}
2019-02-04 15:18:47 -05:00
bool MainWindow::SentenceReceived(TextThread& thread, std::wstring& sentence)
2018-10-08 00:26:43 -04:00
{
2019-02-09 00:30:38 -05:00
if (!DispatchSentenceToExtensions(sentence, GetMiscInfo(thread).data())) return false;
sentence += L'\n';
if (current == &thread) QMetaObject::invokeMethod(this, [this, sentence]
2018-10-08 00:26:43 -04:00
{
2019-02-09 00:30:38 -05:00
ui->textOutput->moveCursor(QTextCursor::End);
ui->textOutput->insertPlainText(S(sentence));
ui->textOutput->moveCursor(QTextCursor::End);
});
return true;
2018-10-08 00:26:43 -04:00
}
2019-02-04 15:18:47 -05:00
QString MainWindow::TextThreadString(TextThread& thread)
2018-08-22 15:11:40 -04:00
{
2018-09-21 22:25:37 -04:00
return QString("%1:%2:%3:%4:%5: ").arg(
2019-02-04 15:18:47 -05:00
QString::number(thread.handle, 16),
QString::number(thread.tp.processId, 16),
QString::number(thread.tp.addr, 16),
QString::number(thread.tp.ctx, 16),
QString::number(thread.tp.ctx2, 16)
2018-08-22 15:11:40 -04:00
).toUpper();
}
ThreadParam MainWindow::ParseTextThreadString(QString ttString)
2018-08-22 15:11:40 -04:00
{
QStringList threadParam = ttString.split(":");
return { threadParam[1].toUInt(nullptr, 16), threadParam[2].toULongLong(nullptr, 16), threadParam[3].toULongLong(nullptr, 16), threadParam[4].toULongLong(nullptr, 16) };
2018-08-22 15:11:40 -04:00
}
DWORD MainWindow::GetSelectedProcessId()
{
return ui->processCombo->currentText().split(":")[0].toULong(nullptr, 16);
2018-08-22 15:11:40 -04:00
}
2019-02-09 00:30:38 -05:00
std::array<InfoForExtension, 10> MainWindow::GetMiscInfo(TextThread& thread)
{
2018-12-28 12:14:56 -05:00
return
2019-02-09 00:30:38 -05:00
{ {
{ "current select", &thread == current },
2019-02-04 15:18:47 -05:00
{ "text number", thread.handle },
{ "process id", thread.tp.processId },
2019-02-09 00:30:38 -05:00
{ "hook address", (int64_t)thread.tp.addr },
2019-02-04 15:18:47 -05:00
{ "text handle", thread.handle },
2019-02-09 00:30:38 -05:00
{ "text name", (int64_t)thread.name.c_str() },
{ nullptr, 0 } // nullptr marks end of info array
} };
}
2018-12-18 12:14:54 -05:00
void MainWindow::AttachProcess()
2018-07-22 16:53:51 -07:00
{
QMultiHash<QString, DWORD> allProcesses;
2019-02-18 22:39:04 -05:00
for (auto processId : Util::GetAllProcessIds())
if (auto processName = Util::GetModuleFilename(processId)) allProcesses.insert(QFileInfo(S(processName.value())).fileName(), processId);
2018-09-09 22:37:48 -04:00
QStringList processList(allProcesses.uniqueKeys());
2018-08-20 14:30:50 -04:00
processList.sort(Qt::CaseInsensitive);
if (QString process = QInputDialog::getItem(this, SELECT_PROCESS, ATTACH_INFO, processList, 0, true, &ok, Qt::WindowCloseButtonHint); ok)
if (process.toInt(nullptr, 0)) Host::InjectProcess(process.toInt(nullptr, 0));
else for (auto processId : allProcesses.values(process)) Host::InjectProcess(processId);
2018-07-23 22:57:54 -07:00
}
void MainWindow::LaunchProcess()
{
QStringList savedProcesses = QString::fromUtf8(QTextFile(GAME_SAVE_FILE, QIODevice::ReadOnly).readAll()).split("\n", QString::SkipEmptyParts);
2019-02-02 16:50:28 -05:00
std::reverse(savedProcesses.begin(), savedProcesses.end());
2019-02-13 16:22:49 -05:00
savedProcesses.removeDuplicates();
savedProcesses.push_back(SEARCH_GAME);
std::wstring process = S(QInputDialog::getItem(this, SELECT_PROCESS, "", savedProcesses, 0, true, &ok, Qt::WindowCloseButtonHint));
if (!ok) return;
if (S(process) == SEARCH_GAME) process = S(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, SELECT_PROCESS, "C:\\", PROCESSES)));
2019-01-22 11:23:35 -05:00
if (process.find(L'\\') == std::wstring::npos) return;
std::wstring path = std::wstring(process).erase(process.rfind(L'\\'));
PROCESS_INFORMATION info = {};
if (QMessageBox::question(this, SELECT_PROCESS, USE_JP_LOCALE) == QMessageBox::Yes)
if (HMODULE localeEmulator = LoadLibraryOnce(L"LoaderDll"))
{
// see https://github.com/xupefei/Locale-Emulator/blob/aa99dec3b25708e676c90acf5fed9beaac319160/LEProc/LoaderWrapper.cs#L252
struct
{
ULONG AnsiCodePage = SHIFT_JIS;
ULONG OemCodePage = SHIFT_JIS;
ULONG LocaleID = LANG_JAPANESE;
ULONG DefaultCharset = SHIFTJIS_CHARSET;
ULONG HookUiLanguageApi = FALSE;
WCHAR DefaultFaceName[LF_FACESIZE] = {};
TIME_ZONE_INFORMATION Timezone;
ULONG64 Unused = 0;
} LEB;
GetTimeZoneInformation(&LEB.Timezone);
((LONG(__stdcall*)(decltype(&LEB), LPCWSTR appName, LPWSTR commandLine, LPCWSTR currentDir, void*, void*, PROCESS_INFORMATION*, void*, void*, void*, void*))
2019-01-22 11:23:35 -05:00
GetProcAddress(localeEmulator, "LeCreateProcess"))(&LEB, process.c_str(), NULL, path.c_str(), NULL, NULL, &info, NULL, NULL, NULL, NULL);
}
if (info.hProcess == NULL)
{
STARTUPINFOW DUMMY = { sizeof(DUMMY) };
2019-01-22 11:23:35 -05:00
CreateProcessW(process.c_str(), NULL, nullptr, nullptr, FALSE, 0, nullptr, path.c_str(), &DUMMY, &info);
}
if (info.hProcess == NULL) return Host::AddConsoleOutput(LAUNCH_FAILED);
Host::InjectProcess(info.dwProcessId);
CloseHandle(info.hProcess);
CloseHandle(info.hThread);
}
2018-12-18 12:14:54 -05:00
void MainWindow::DetachProcess()
2018-07-23 22:57:54 -07:00
{
2018-08-21 22:43:30 -04:00
Host::DetachProcess(GetSelectedProcessId());
2018-07-23 22:57:54 -07:00
}
2018-12-18 12:14:54 -05:00
void MainWindow::AddHook()
2018-07-25 21:48:18 -07:00
{
if (QString hookCode = QInputDialog::getText(this, ADD_HOOK, CODE_INFODUMP, QLineEdit::Normal, "", &ok, Qt::WindowCloseButtonHint); ok)
if (auto hp = Util::ParseCode(S(hookCode))) Host::InsertHook(GetSelectedProcessId(), hp.value());
else Host::AddConsoleOutput(INVALID_CODE);
2018-07-25 21:48:18 -07:00
}
2018-12-18 12:14:54 -05:00
void MainWindow::SaveHooks()
2018-07-26 22:42:21 -07:00
{
if (auto processName = Util::GetModuleFilename(GetSelectedProcessId()))
2018-11-27 16:57:47 -05:00
{
QHash<uint64_t, QString> hookCodes;
for (int i = 0; i < ui->ttCombo->count(); ++i)
{
ThreadParam tp = ParseTextThreadString(ui->ttCombo->itemText(i));
if (tp.processId == GetSelectedProcessId())
{
HookParam hp = Host::GetHookParam(tp);
if (!(hp.type & HOOK_ENGINE)) hookCodes[tp.addr] = S(Util::GenerateCode(hp, tp.processId));
}
}
2019-02-03 08:49:58 -05:00
auto hookInfo = QStringList() << S(processName.value()) << hookCodes.values();
2019-02-04 15:18:47 -05:00
TextThread& current = Host::GetThread(ParseTextThreadString(ui->ttCombo->currentText()));
if (current.tp.processId == GetSelectedProcessId())
hookInfo << QString("|%1:%2:%3").arg(current.tp.ctx).arg(current.tp.ctx2).arg(S(Util::GenerateCode(Host::GetHookParam(current.tp), current.tp.processId)));
2019-02-03 08:49:58 -05:00
QTextFile(HOOK_SAVE_FILE, QIODevice::WriteOnly | QIODevice::Append).write((hookInfo.join(" , ") + "\n").toUtf8());
2018-11-27 16:57:47 -05:00
}
2018-07-26 22:42:21 -07:00
}
2018-12-18 12:14:54 -05:00
void MainWindow::Settings()
2018-11-10 05:13:59 -05:00
{
struct : QDialog
{
using QDialog::QDialog;
void launch()
{
auto settings = new QSettings(CONFIG_FILE, QSettings::IniFormat, this);
auto layout = new QFormLayout(this);
auto save = new QPushButton(this);
save->setText(SAVE_SETTINGS);
layout->addWidget(save);
for (auto[value, label] : Array<std::tuple<int&, const char*>>{
2019-01-05 03:47:32 -05:00
{ Host::defaultCodepage, DEFAULT_CODEPAGE },
{ TextThread::maxBufferSize, MAX_BUFFER_SIZE },
{ TextThread::flushDelay, FLUSH_DELAY },
})
{
auto spinBox = new QSpinBox(this);
spinBox->setMaximum(INT_MAX);
spinBox->setValue(value);
layout->insertRow(0, label, spinBox);
2018-12-31 15:06:47 -05:00
connect(save, &QPushButton::clicked, [=, &value] { settings->setValue(label, value = spinBox->value()); });
}
2019-02-04 15:53:13 -05:00
for (auto[value, label] : Array<std::tuple<bool&, const char*>>{
{ TextThread::filterRepetition, FILTER_REPETITION },
})
{
auto checkBox = new QCheckBox(this);
checkBox->setChecked(value);
layout->insertRow(0, label, checkBox);
connect(save, &QPushButton::clicked, [=, &value] { settings->setValue(label, value = checkBox->isChecked()); });
}
connect(save, &QPushButton::clicked, this, &QDialog::accept);
setWindowTitle(SETTINGS);
exec();
}
} settingsDialog(this, Qt::WindowCloseButtonHint);
settingsDialog.launch();
2018-11-10 05:13:59 -05:00
}
2018-12-18 12:14:54 -05:00
void MainWindow::Extensions()
2018-07-23 22:57:54 -07:00
{
extenWindow->activateWindow();
extenWindow->showNormal();
2018-07-22 16:53:51 -07:00
}
2018-07-26 22:42:21 -07:00
2018-12-18 12:14:54 -05:00
void MainWindow::ViewThread(int index)
2018-07-26 22:42:21 -07:00
{
2019-02-03 08:49:58 -05:00
ui->ttCombo->setCurrentIndex(index);
2019-02-09 00:30:38 -05:00
ui->textOutput->setPlainText(S((current = &Host::GetThread(ParseTextThreadString(ui->ttCombo->itemText(index))))->storage->c_str()));
ui->textOutput->moveCursor(QTextCursor::End);
2018-07-26 22:42:21 -07:00
}