From a4022d0cf47208be75651473ed3b3f0789ec47f3 Mon Sep 17 00:00:00 2001 From: Mykola Dimura Date: Fri, 19 Feb 2021 11:27:26 +0100 Subject: [PATCH] Add UTF-16 support --- .gitlab-ci.yml | 20 +- Galaxy.cpp | 20 +- MainWindow.cpp | 1204 +++++++++++++++++++++++--------------------- MainWindow.ui | 57 +-- SRHDDumpReader.pro | 2 +- 5 files changed, 696 insertions(+), 607 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c466efb..d9e379d 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -32,6 +32,20 @@ build-win32: paths: - build-win32/release/SRHDDumpReader.exe +pack-ubuntu: + stage: package + image: burningdaylight/ubuntu-latest-devel + script: + - mkdir -p ./SRHDDumpReader + - cp build-ubuntu/SRHDDumpReader ./SRHDDumpReader/ + - cp -r presets ./SRHDDumpReader/ + - cp ./*.json ./SRHDDumpReader/ + - cp ./Click1.wav ./SRHDDumpReader/ + artifacts: + name: "SRHDDumpReader_linux_${CI_BUILD_REF_NAME}-${CI_BUILD_REF:0:8}" + paths: + - SRHDDumpReader + pack-win64: stage: package image: burningdaylight/mingw-arch:qt @@ -39,7 +53,8 @@ pack-win64: - mkdir -p ./SRHDDumpReader/platforms/ - mkdir -p ./SRHDDumpReader/imageformats/ - cp build-win64/release/SRHDDumpReader.exe ./SRHDDumpReader/ - - cp /usr/x86_64-w64-mingw32/bin/{libssp-0,libbz2-1,libiconv-2,libpcre-1,libwinpthread-1,Qt5Multimedia,zlib1,libfreetype-6,libglib-2.0-0,libintl-8,libpng16-16,Qt5Core,Qt5Network,libgcc_s_seh-1,libharfbuzz-0,libpcre16-0,libpcre2-16-0,libgraphite2,libstdc++-6,Qt5Gui,Qt5Widgets,Qt5Svg}.dll ./SRHDDumpReader/ + - cp /usr/x86_64-w64-mingw32/bin/lib{gcc_s_seh-1,ssp-0,bz2-1,iconv-2,pcre-1,pcre2-16-0,winpthread-1,freetype-6,glib-2.0-0,intl-8,png16-16,harfbuzz-0,graphite2,stdc++-6}.dll ./SRHDDumpReader/ + - cp /usr/x86_64-w64-mingw32/bin/{zlib1,Qt5Core,Qt5Network,Qt5Multimedia,Qt5Gui,Qt5Widgets,Qt5Svg}.dll ./SRHDDumpReader/ - cp /usr/x86_64-w64-mingw32/lib/qt/plugins/platforms/qwindows.dll ./SRHDDumpReader/platforms/ - cp /usr/x86_64-w64-mingw32/lib/qt/plugins/imageformats/{qsvg,qico,qtiff,qjpeg}.dll ./SRHDDumpReader/imageformats/ - cp -r presets ./SRHDDumpReader/ @@ -57,7 +72,8 @@ pack-win32: - mkdir -p ./SRHDDumpReader/platforms/ - mkdir -p ./SRHDDumpReader/imageformats/ - cp build-win32/release/SRHDDumpReader.exe ./SRHDDumpReader/ - - cp /usr/i686-w64-mingw32/bin/{libssp-0,libbz2-1,libiconv-2,libpcre-1,libwinpthread-1,Qt5Multimedia,zlib1,libfreetype-6,libglib-2.0-0,libintl-8,libpng16-16,Qt5Core,Qt5Network,libgcc_s_sjlj-1,libharfbuzz-0,libpcre16-0,libpcre2-16-0,libgraphite2,libstdc++-6,Qt5Gui,Qt5Widgets,Qt5Svg}.dll ./SRHDDumpReader/ + - cp /usr/i686-w64-mingw32/bin/lib{gcc_s_dw2-1,ssp-0,bz2-1,iconv-2,pcre-1,pcre2-16-0,winpthread-1,freetype-6,glib-2.0-0,intl-8,png16-16,harfbuzz-0,graphite2,stdc++-6}.dll ./SRHDDumpReader/ || true + - cp /usr/i686-w64-mingw32/bin/{zlib1,Qt5Core,Qt5Network,Qt5Multimedia,Qt5Gui,Qt5Widgets,Qt5Svg}.dll ./SRHDDumpReader/ - cp /usr/i686-w64-mingw32/lib/qt/plugins/platforms/qwindows.dll ./SRHDDumpReader/platforms/ - cp /usr/i686-w64-mingw32/lib/qt/plugins/imageformats/{qsvg,qico,qtiff,qjpeg}.dll ./SRHDDumpReader/imageformats/ - cp -r presets ./SRHDDumpReader/ diff --git a/Galaxy.cpp b/Galaxy.cpp index 1e55e33..29cb915 100644 --- a/Galaxy.cpp +++ b/Galaxy.cpp @@ -59,8 +59,9 @@ void Galaxy::parseDump(QTextStream &stream) const static QMap globalOptions = { {"Player ^{", 0}, {"StarList ^{", 1}, {"HoleList ^{", 2}}; - QString line = stream.readLine(); - while (!line.isNull()) { + QString line; + do { + line = stream.readLine(); switch (globalOptions.value(line, -1)) { case 0: // Player { @@ -86,9 +87,7 @@ void Galaxy::parseDump(QTextStream &stream) // skip record break; } - - line = stream.readLine(); - } + } while (!line.isNull()); } void Galaxy::clear() @@ -149,6 +148,9 @@ unsigned Galaxy::galaxyTechLevel() const auto maxPtlIt = std::find_if(ptlCount.rbegin(), ptlCount.rend(), [](const int &c) { return c > 0; }); unsigned maxPtl = std::distance(maxPtlIt, ptlCount.rend()); + if (maxPtl < 1) { + return 0; + } if (ptlCount[maxPtl] >= 5) { return maxPtl; } else if (ptlCount[maxPtl] >= 2 || ptlCount[maxPtl - 1] >= 4) { @@ -533,15 +535,15 @@ QString Galaxy::blackHoleNextLootChange(unsigned row) const QDate today = QDate(3300, 1, 1).addDays(currentDay - 301); QString changes; int ttclose = blackHoleTurnsToClose(row); - int lastChange = std::min(ttclose,77*5); - lastChange = ttclose<1?77*5:lastChange; + int lastChange = std::min(ttclose, 77 * 5); + lastChange = ttclose < 1 ? 77 * 5 : lastChange; for (unsigned daysToChange = 77 - (currentDay % 77); daysToChange < lastChange; daysToChange += 77) { changes += today.addDays(daysToChange).toString("dd MMMM yyyy") + "; "; } - if (lastChangemodel(); + const QAbstractItemModel *model = selectionModel->model(); QModelIndexList indexes = selectionModel->selectedIndexes(); - if(indexes.size() < 1){ + if (indexes.size() < 1) { return ""; } std::sort(indexes.begin(), indexes.end()); - QString selectedText="[table][tr]"; - QModelIndex previous=indexes.takeFirst(); - for(const QModelIndex& index:indexes) - { - QString text = "[td]" + model->data(previous).toString() + "[/td]"; + QString selectedText = "[table][tr]"; + QModelIndex previous = indexes.takeFirst(); + for (const QModelIndex &index : indexes) { + QString text = + "[td]" + model->data(previous).toString() + "[/td]"; // At this point `text` contains the text in one cell selectedText.append(text); - // If you are at the start of the row the row number of the previous index - // isn't the same. Text is followed by a row separator, which is a newline. - if (index.row() != previous.row()) - { + // If you are at the start of the row the row number of the + // previous index isn't the same. Text is followed by a row + // separator, which is a newline. + if (index.row() != previous.row()) { selectedText.append("[/tr]\n[tr]"); } previous = index; } - selectedText.append("[td]"+model->data(previous).toString()+"[/td]"); - selectedText+="[/tr][/table]"; + selectedText.append("[td]" + model->data(previous).toString() + + "[/td]"); + selectedText += "[/tr][/table]"; return selectedText; } QString tabSeparatedValues(const QItemSelectionModel *selectionModel) { - const QAbstractItemModel* model=selectionModel->model(); + const QAbstractItemModel *model = selectionModel->model(); QModelIndexList indexes = selectionModel->selectedIndexes(); - if(indexes.size() < 1) { + if (indexes.size() < 1) { return ""; } std::sort(indexes.begin(), indexes.end()); QString selectedText; - QModelIndex previous=indexes.takeFirst(); - for(const QModelIndex& index:indexes) - { + QModelIndex previous = indexes.takeFirst(); + for (const QModelIndex &index : indexes) { QString text = model->data(previous).toString(); // At this point `text` contains the text in one cell selectedText.append(text); - // If you are at the start of the row the row number of the previous index - // isn't the same. Text is followed by a row separator, which is a newline. - if (index.row() != previous.row()) - { + // If you are at the start of the row the row number of the + // previous index isn't the same. Text is followed by a row + // separator, which is a newline. + if (index.row() != previous.row()) { selectedText.append(QLatin1Char('\n')); } - // Otherwise it's the same row, so append a column separator, which is a tab. - else - { + // Otherwise it's the same row, so append a column separator, + // which is a tab. + else { selectedText.append(QLatin1Char('\t')); } previous = index; @@ -108,14 +105,14 @@ QString tabSeparatedValues(const QItemSelectionModel *selectionModel) return selectedText; } -MainWindow::MainWindow(QWidget *parent) : - QMainWindow(parent), - ui(new Ui::MainWindow),tradeModel(&galaxy,this),tradeProxyModel(this), - eqModel(&galaxy,this),bhModel(&galaxy,this),planetsModel(&galaxy,this) +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), ui(new Ui::MainWindow), tradeModel(&galaxy, this), + tradeProxyModel(this), eqModel(&galaxy, this), bhModel(&galaxy, this), + planetsModel(&galaxy, this) { QItemEditorFactory *factory = new QItemEditorFactory; QItemEditorCreatorBase *colorListCreator = - new QStandardItemEditorCreator(); + new QStandardItemEditorCreator(); factory->registerEditor(QVariant::Color, colorListCreator); QItemEditorFactory::setDefaultFactory(factory); @@ -129,25 +126,26 @@ MainWindow::MainWindow(QWidget *parent) : connect(&reloadTimer, SIGNAL(timeout()), this, SLOT(parseDump())); reloadTimer.setInterval(2000); connect(ui->actionAutoReload, &QAction::toggled, [=](bool on) { - if(on) { + if (on) { this->reloadTimer.start(); - } - else { + } else { this->reloadTimer.stop(); } - } ); + }); ui->mapImageLabel->setBackgroundRole(QPalette::Base); ui->scrollArea->setBackgroundRole(QPalette::Dark); reloadMenu.addAction(ui->actionAutoReload); - QToolButton *reloadButton=static_cast(ui->mainToolBar->widgetForAction(ui->actionReload)); + QToolButton *reloadButton = static_cast( + ui->mainToolBar->widgetForAction(ui->actionReload)); reloadButton->setMenu(&reloadMenu); reloadButton->setPopupMode(QToolButton::MenuButtonPopup); addAction(ui->actionSaveReport); saveReportMenu.addAction(ui->actionAutoSaveReport); - QToolButton *reportButton=static_cast(ui->mainToolBar->widgetForAction(ui->actionSaveReport)); + QToolButton *reportButton = static_cast( + ui->mainToolBar->widgetForAction(ui->actionSaveReport)); reportButton->setMenu(&saveReportMenu); reportButton->setPopupMode(QToolButton::MenuButtonPopup); @@ -156,25 +154,29 @@ MainWindow::MainWindow(QWidget *parent) : _mapScaleSpinBox.setSingleStep(50); _mapScaleSpinBox.setToolTip(tr("Map width")); _mapScaleSpinBox.setWhatsThis(tr("Map width")); - ui->mainToolBar->insertWidget(ui->mainToolBar->actions()[3],&_mapScaleSpinBox); - connect(&_mapScaleSpinBox,SIGNAL(valueChanged(int)),this,SLOT(setMapScale(int))); + ui->mainToolBar->insertWidget(ui->mainToolBar->actions()[3], + &_mapScaleSpinBox); + connect(&_mapScaleSpinBox, SIGNAL(valueChanged(int)), this, + SLOT(setMapScale(int))); _mapFontSpinBox.setMaximum(99); _mapFontSpinBox.setSingleStep(1); _mapFontSpinBox.setToolTip(tr("Map font size")); - ui->mainToolBar->insertWidget(ui->mainToolBar->actions()[4],&_mapFontSpinBox); - connect(&_mapFontSpinBox,SIGNAL(valueChanged(int)),this,SLOT(setMapFontSize(int))); -// _mapFontSpinBox.setFixedWidth(40); + ui->mainToolBar->insertWidget(ui->mainToolBar->actions()[4], + &_mapFontSpinBox); + connect(&_mapFontSpinBox, SIGNAL(valueChanged(int)), this, + SLOT(setMapFontSize(int))); + // _mapFontSpinBox.setFixedWidth(40); sound.setSource(QUrl::fromLocalFile("Click1.wav")); sound.setVolume(1.0); setDockNestingEnabled(true); setCentralWidget(0); - tabifyDockWidget(ui->tradeDockWidget,ui->eqDockWidget); - tabifyDockWidget(ui->eqDockWidget,ui->bhDockWidget); - tabifyDockWidget(ui->bhDockWidget,ui->tradeDockWidget); - tabifyDockWidget(ui->tradeDockWidget,ui->imageDockWidget); + tabifyDockWidget(ui->tradeDockWidget, ui->eqDockWidget); + tabifyDockWidget(ui->eqDockWidget, ui->bhDockWidget); + tabifyDockWidget(ui->bhDockWidget, ui->tradeDockWidget); + tabifyDockWidget(ui->tradeDockWidget, ui->imageDockWidget); ui->tradeDockWidget->raise(); readSettings(); @@ -182,97 +184,107 @@ MainWindow::MainWindow(QWidget *parent) : eqProxyModel.setSourceModel(&eqModel); planetsProxyModel.setSourceModel(&planetsModel); - HierarchicalHeaderView* hv=new HierarchicalHeaderView(Qt::Horizontal, ui->tradeTableView); + HierarchicalHeaderView *hv = + new HierarchicalHeaderView(Qt::Horizontal, ui->tradeTableView); hv->setHighlightSections(true); hv->setSectionsClickable(true); ui->tradeTableView->setHorizontalHeader(hv); - int tableFontHeight=QFontMetrics(QFont("sans",9)).height(); - int tableFontWidth=QFontMetrics(QFont("sans",9)).charWidth("o",0); + int tableFontHeight = QFontMetrics(QFont("sans", 9)).height(); + int tableFontWidth = QFontMetrics(QFont("sans", 9)).charWidth("o", 0); ui->tradeTableView->setModel(&tradeProxyModel); ui->tradeTableView->resizeColumnsToContents(); - //ui->tradeTableView->resizeRowsToContents(); - ui->tradeTableView->setColumnWidth(0,tableFontWidth*14); - ui->tradeTableView->setColumnWidth(1,tableFontWidth*10); + // ui->tradeTableView->resizeRowsToContents(); + ui->tradeTableView->setColumnWidth(0, tableFontWidth * 14); + ui->tradeTableView->setColumnWidth(1, tableFontWidth * 10); ui->planetsTableView->setModel(&planetsProxyModel); - planetsHeaderView= - new FilterHorizontalHeaderView(&planetsProxyModel,ui->planetsTableView); + planetsHeaderView = new FilterHorizontalHeaderView( + &planetsProxyModel, ui->planetsTableView); ui->planetsTableView->setHorizontalHeader(planetsHeaderView); ui->planetsTableView->resizeColumnsToContents(); ui->equipmentTableView->setModel(&eqProxyModel); - eqHeaderView=new FilterHorizontalHeaderView(&eqProxyModel,ui->equipmentTableView); + eqHeaderView = new FilterHorizontalHeaderView(&eqProxyModel, + ui->equipmentTableView); ui->equipmentTableView->setHorizontalHeader(eqHeaderView); ui->equipmentTableView->resizeColumnsToContents(); - ui->equipmentTableView->setColumnWidth(0,tableFontWidth*2); - ui->equipmentTableView->setColumnWidth(1,tableFontWidth*24); - ui->equipmentTableView->setColumnWidth(2,tableFontWidth*12); - ui->equipmentTableView->setColumnWidth(3,tableFontWidth*6);//Size - ui->equipmentTableView->setColumnWidth(4,tableFontWidth*7);//Made - ui->equipmentTableView->setColumnWidth(5,tableFontWidth*7);//Cost - ui->equipmentTableView->setColumnWidth(6,tableFontWidth*5);//TL - ui->equipmentTableView->setColumnWidth(7,tableFontWidth*16);//L T - ui->equipmentTableView->setColumnWidth(8,tableFontWidth*20);//Loc - ui->equipmentTableView->setColumnWidth(9,tableFontWidth*10);//Star - ui->equipmentTableView->setColumnWidth(10,tableFontWidth*8);//Dist - ui->equipmentTableView->setColumnWidth(11,tableFontWidth*8);//Owner - ui->equipmentTableView->setColumnWidth(12,tableFontWidth*8);//Durab - ui->equipmentTableView->setColumnWidth(13,tableFontWidth*48);//Bonus - //ui->equipmentTableView->resizeRowsToContents(); - ui->equipmentTableView->verticalHeader()->setContextMenuPolicy(Qt::CustomContextMenu); + ui->equipmentTableView->setColumnWidth(0, tableFontWidth * 2); + ui->equipmentTableView->setColumnWidth(1, tableFontWidth * 24); + ui->equipmentTableView->setColumnWidth(2, tableFontWidth * 12); + ui->equipmentTableView->setColumnWidth(3, tableFontWidth * 6); // Size + ui->equipmentTableView->setColumnWidth(4, tableFontWidth * 7); // Made + ui->equipmentTableView->setColumnWidth(5, tableFontWidth * 7); // Cost + ui->equipmentTableView->setColumnWidth(6, tableFontWidth * 5); // TL + ui->equipmentTableView->setColumnWidth(7, tableFontWidth * 16); // L T + ui->equipmentTableView->setColumnWidth(8, tableFontWidth * 20); // Loc + ui->equipmentTableView->setColumnWidth(9, tableFontWidth * 10); // Star + ui->equipmentTableView->setColumnWidth(10, tableFontWidth * 8); // Dist + ui->equipmentTableView->setColumnWidth(11, tableFontWidth * 8); // Owner + ui->equipmentTableView->setColumnWidth(12, tableFontWidth * 8); // Durab + ui->equipmentTableView->setColumnWidth(13, + tableFontWidth * 48); // Bonus + // ui->equipmentTableView->resizeRowsToContents(); + ui->equipmentTableView->verticalHeader()->setContextMenuPolicy( + Qt::CustomContextMenu); connect(ui->equipmentTableView->verticalHeader(), SIGNAL(customContextMenuRequested(QPoint)), SLOT(customHeaderMenuRequested(QPoint))); - QStringList colorNames=supportedColors(); - for (const QString& name:colorNames) { - QPixmap pix(100,100); + QStringList colorNames = supportedColors(); + for (const QString &name : colorNames) { + QPixmap pix(100, 100); QColor color(name); pix.fill(color); - QAction* act=new QAction(QIcon(pix),name, this); - connect(act,&QAction::triggered,[this,color](){ - eqProxyModel.setData(eqProxyModel.index(eqMenuRow,0),color); + QAction *act = new QAction(QIcon(pix), name, this); + connect(act, &QAction::triggered, [this, color]() { + eqProxyModel.setData(eqProxyModel.index(eqMenuRow, 0), + color); }); eqMenu.addAction(act); } - ui->equipmentTableView->verticalHeader()->setDefaultSectionSize(tableFontHeight); - ui->tradeTableView->verticalHeader()->setDefaultSectionSize(tableFontHeight); - ui->planetsTableView->verticalHeader()->setDefaultSectionSize(tableFontHeight); - ui->bhTableView->verticalHeader()->setDefaultSectionSize(tableFontHeight); + ui->equipmentTableView->verticalHeader()->setDefaultSectionSize( + tableFontHeight); + ui->tradeTableView->verticalHeader()->setDefaultSectionSize( + tableFontHeight); + ui->planetsTableView->verticalHeader()->setDefaultSectionSize( + tableFontHeight); + ui->bhTableView->verticalHeader()->setDefaultSectionSize( + tableFontHeight); - ui->equipmentTableView->verticalHeader()->setFixedWidth(tableFontWidth*8); - ui->planetsTableView->verticalHeader()->setFixedWidth(tableFontWidth*5); + ui->equipmentTableView->verticalHeader()->setFixedWidth(tableFontWidth + * 8); + ui->planetsTableView->verticalHeader()->setFixedWidth(tableFontWidth + * 5); ui->bhTableView->setModel(&bhModel); ui->bhTableView->resizeColumnsToContents(); - connect(planetsHeaderView,&FilterHorizontalHeaderView::presetSaved, - [&](const QVariantMap& preset, const QString& name) { - QString fileName=presetDirPlanets+name+".dr.json"; - savePreset(preset,fileName); - }); + connect(planetsHeaderView, &FilterHorizontalHeaderView::presetSaved, + [&](const QVariantMap &preset, const QString &name) { + QString fileName = presetDirPlanets + name + ".dr.json"; + savePreset(preset, fileName); + }); - connect(eqHeaderView,&FilterHorizontalHeaderView::presetSaved, - [&](const QVariantMap& preset, const QString& name) { - QString fileName=presetDirEq+name+".dr.json"; - savePreset(preset,fileName); - }); + connect(eqHeaderView, &FilterHorizontalHeaderView::presetSaved, + [&](const QVariantMap &preset, const QString &name) { + QString fileName = presetDirEq + name + ".dr.json"; + savePreset(preset, fileName); + }); - _filename=rangersDir+"/save/autodump.txt"; + _filename = rangersDir + "/save/autodump.txt"; loadPresets(); openDump(QCoreApplication::arguments().value(1)); } -void copySelectedText(const QItemSelectionModel* selModel, bool bbcode=false) +void copySelectedText(const QItemSelectionModel *selModel, bool bbcode = false) { QString selected_text; - if(bbcode) { - selected_text=bbSeparatedValues(selModel); - } - else{ - selected_text=tabSeparatedValues(selModel); + if (bbcode) { + selected_text = bbSeparatedValues(selModel); + } else { + selected_text = tabSeparatedValues(selModel); } @@ -280,19 +292,21 @@ void copySelectedText(const QItemSelectionModel* selModel, bool bbcode=false) } bool MainWindow::eventFilter(QObject *object, QEvent *event) { - if( (object == ui->planetsTableView || object==ui->equipmentTableView || - object==ui->tradeTableView || object==ui->bhTableView) && - event->type() == QEvent::KeyPress) { + if ((object == ui->planetsTableView || object == ui->equipmentTableView + || object == ui->tradeTableView || object == ui->bhTableView) + && event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast(event); if (keyEvent->matches(QKeySequence::Copy)) { - QAbstractItemView* viewObject=static_cast(object); + QAbstractItemView *viewObject = + static_cast(object); copySelectedText(viewObject->selectionModel()); return true; - } - else if(keyEvent->modifiers().testFlag(Qt::ShiftModifier) && - keyEvent->modifiers().testFlag(Qt::ControlModifier)) { - QAbstractItemView* viewObject=static_cast(object); - copySelectedText(viewObject->selectionModel(),true); + } else if (keyEvent->modifiers().testFlag(Qt::ShiftModifier) + && keyEvent->modifiers().testFlag( + Qt::ControlModifier)) { + QAbstractItemView *viewObject = + static_cast(object); + copySelectedText(viewObject->selectionModel(), true); return true; } } @@ -307,41 +321,42 @@ void MainWindow::readSettings() { QSettings settings("p-s team", "SRHDDumpReader"); - shortSleep=settings.value("shortSleep",25).toInt(); - maxGenerationTime=settings.value("maxGenerationTime",120000).toInt(); - mapWidth=std::max(10,settings.value("mapWidth",800).toInt()); + shortSleep = settings.value("shortSleep", 25).toInt(); + maxGenerationTime = settings.value("maxGenerationTime", 120000).toInt(); + mapWidth = std::max(10, settings.value("mapWidth", 800).toInt()); _mapScaleSpinBox.setValue(mapWidth); - mapFontSize=std::max(0,settings.value("mapFontSize",8).toInt()); + mapFontSize = std::max(0, settings.value("mapFontSize", 8).toInt()); _mapFontSpinBox.setValue(mapFontSize); - bool autoSaveReport=settings.value("autoSaveReport",false).toBool(); + bool autoSaveReport = settings.value("autoSaveReport", false).toBool(); ui->actionAutoSaveReport->setChecked(autoSaveReport); - bool autoReload=settings.value("autoReload",false).toBool(); + bool autoReload = settings.value("autoReload", false).toBool(); ui->actionAutoReload->setChecked(autoReload); - //ui->actionAutoReload->toggle(); + // ui->actionAutoReload->toggle(); QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("size", QSize(400, 400)).toSize(); resize(size); move(pos); restoreState(settings.value("windowState").toByteArray()); - std::cout<<"rangersDir:"<actionAutoReload->isChecked()); - settings.setValue("autoSaveReport",ui->actionAutoSaveReport->isChecked()); + settings.setValue("autoReload", ui->actionAutoReload->isChecked()); + settings.setValue("autoSaveReport", + ui->actionAutoSaveReport->isChecked()); settings.setValue("pos", pos()); settings.setValue("size", size()); @@ -373,54 +389,59 @@ void MainWindow::closeEvent(QCloseEvent *event) event->accept(); } -bool MainWindow::parseDump(const QString& filename) +bool MainWindow::parseDump(const QString &filename) { using namespace std; using namespace std::chrono; high_resolution_clock::time_point tStart = high_resolution_clock::now(); - if(!filename.isEmpty()) { - _filename=filename; + if (!filename.isEmpty()) { + _filename = filename; } QFile file(_filename); - if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) - { - showMessage(tr("File could not be open: ")+_filename); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + showMessage(tr("File could not be open: ") + _filename); return false; } - if(filename.isEmpty() && QFileInfo(_filename).lastModified()==_fileModified) - { - //dump was parsed earlier - showMessage(tr("dump was parsed earlier, skipping")+_filename); + if (filename.isEmpty() + && QFileInfo(_filename).lastModified() == _fileModified) { + // dump was parsed earlier + showMessage(tr("dump was parsed earlier, skipping") + + _filename); return false; } - _fileModified=QFileInfo(_filename).lastModified(); - setWindowTitle(QStringLiteral("SRHDDumpReader - ")+QFileInfo(_filename).baseName()); + _fileModified = QFileInfo(_filename).lastModified(); + setWindowTitle(QStringLiteral("SRHDDumpReader - ") + + QFileInfo(_filename).baseName()); galaxy.clear(); - const QByteArray& allArr=(file.readAll()); - QTextStream stream(allArr); - QTextCodec::ConverterState state; - QTextCodec *codec = QTextCodec::codecForName("UTF-8"); - const QString text = codec->toUnicode(allArr.left(500).constData(), 500, &state); - if (state.invalidChars > 0) { + QTextStream stream(&file); + QString buf = stream.read(500); + stream.seek(0); + if (buf.contains(QChar(65533))) { stream.setCodec("Windows-1251"); - std::cout<<"Using Windows-1251 encoding"<( tReadEnd - tStart ).count(); - string timeTaken="Reading the file took "+to_string(duration/1000.0)+" s. "; + std::cout << "File encoding: " << stream.codec()->name().toStdString() + << ", " << filename.toStdString() << std::endl; + buf = stream.readAll(); + high_resolution_clock::time_point tReadEnd = + high_resolution_clock::now(); + auto duration = duration_cast(tReadEnd - tStart).count(); + string timeTaken = "Reading the file took " + + to_string(duration / 1000.0) + " s. "; + stream.setString(&buf); galaxy.parseDump(stream); - showMessage(tr("Parsed %1 stars, %2 planets, %3 black holes, %4 ships and %5 items"). - arg(galaxy.starCount()).arg(galaxy.planetCount()). - arg(galaxy.blackHoleCount()). - arg(galaxy.shipCount()).arg(galaxy.equipmentCount()), - 5000); - high_resolution_clock::time_point tParseEnd = high_resolution_clock::now(); - duration = duration_cast( tParseEnd - tReadEnd ).count(); - timeTaken+="Parsing - "+to_string(duration/1000.0)+" s. "; + showMessage( + tr("Parsed %1 stars, %2 planets, %3 black holes, %4 ships and %5 items") + .arg(galaxy.starCount()) + .arg(galaxy.planetCount()) + .arg(galaxy.blackHoleCount()) + .arg(galaxy.shipCount()) + .arg(galaxy.equipmentCount()), + 5000); + high_resolution_clock::time_point tParseEnd = + high_resolution_clock::now(); + duration = duration_cast(tParseEnd - tReadEnd).count(); + timeTaken += "Parsing - " + to_string(duration / 1000.0) + " s. "; tradeModel.reload(); eqModel.reload(); @@ -428,30 +449,38 @@ bool MainWindow::parseDump(const QString& filename) planetsModel.reload(); ui->tradeTableView->resizeColumnsToContents(); ui->planetsTableView->resizeColumnsToContents(); - //ui->tradeTableView->resizeRowsToContents(); - //ui->equipmentTableView->resizeColumnsToContents(); + // ui->tradeTableView->resizeRowsToContents(); + // ui->equipmentTableView->resizeColumnsToContents(); // //ui->equipmentTableView->resizeRowsToContents(); - //ui->equipmentTableView->resizeRowToContents(0); - //int sectionSize=ui->equipmentTableView->verticalHeader()->sectionSize(0); - //ui->equipmentTableView->verticalHeader()->setDefaultSectionSize(sectionSize); + // ui->equipmentTableView->resizeRowToContents(0); + // int + // sectionSize=ui->equipmentTableView->verticalHeader()->sectionSize(0); + // ui->equipmentTableView->verticalHeader()->setDefaultSectionSize(sectionSize); setWindowTitle(QStringLiteral("SRHDDumpReader - ") - +QFileInfo(_filename).baseName()+". Galaxy's tech level: " - +QString::number(galaxy.galaxyTechLevel())); + + QFileInfo(_filename).baseName() + + ". Galaxy's tech level: " + + QString::number(galaxy.galaxyTechLevel())); - high_resolution_clock::time_point tModelUpdateEnd = high_resolution_clock::now(); - duration = duration_cast( tModelUpdateEnd - tParseEnd ).count(); - timeTaken+="Model update - "+to_string(duration/1000.0)+" s. "; + high_resolution_clock::time_point tModelUpdateEnd = + high_resolution_clock::now(); + duration = duration_cast(tModelUpdateEnd - tParseEnd) + .count(); + timeTaken += "Model update - " + to_string(duration / 1000.0) + " s. "; updateMap(); - high_resolution_clock::time_point tMapEnd = high_resolution_clock::now(); - duration = duration_cast( tMapEnd - tModelUpdateEnd ).count(); - timeTaken+="map update - "+to_string(duration/1000.0)+" s. "; - - duration = duration_cast( high_resolution_clock::now() - tStart ).count(); - timeTaken+="Total: "+to_string(duration/1000.0)+" s."; - cout<actionAutoSaveReport->isChecked()) { + high_resolution_clock::time_point tMapEnd = + high_resolution_clock::now(); + duration = + duration_cast(tMapEnd - tModelUpdateEnd).count(); + timeTaken += "map update - " + to_string(duration / 1000.0) + " s. "; + + duration = duration_cast(high_resolution_clock::now() + - tStart) + .count(); + timeTaken += "Total: " + to_string(duration / 1000.0) + " s."; + cout << timeTaken << endl; + + if (ui->actionAutoSaveReport->isChecked()) { saveReport(); } return true; @@ -459,21 +488,24 @@ bool MainWindow::parseDump(const QString& filename) bool MainWindow::openDump() { - QString fileName = QFileDialog::getOpenFileName(this, - tr("Open Dump File"), rangersDir+"/save/", - tr("SRHD Dump (*.txt);;All Files (*)")); + QString fileName = QFileDialog::getOpenFileName( + this, tr("Open Dump File"), rangersDir + "/save/", + tr("SRHD Dump (*.txt);;All Files (*)")); return openDump(fileName); } void MainWindow::showAbout() { - QMessageBox::about(this,"SRHDDumpReader",QString("SRHDDumpReader v. %1\nAuthor: Mykola Dimura\n" - "Description: small program to parse and analyse" - " the galaxy dumps from \"Space Rangers HD: A War" - " Apart\" video game\n" - "Tip: press F7 in-game for QuickDump.") - .arg(QApplication::applicationVersion())); + QMessageBox::about( + this, "SRHDDumpReader", + QString("SRHDDumpReader v. %1\nAuthor: Mykola Dimura\n" + "Parse and analyse the galaxy dumps from " + "\"Space Rangers HD: A War Apart\" video game\n" + "Tip: press F7 in-game for QuickDump.\n" + "Qt Version: %2") + .arg(QApplication::applicationVersion()) + .arg(qVersion())); } @@ -486,124 +518,140 @@ void MainWindow::saveReport() using namespace std::chrono; high_resolution_clock::time_point tStart = high_resolution_clock::now(); - QVariantMap oldEqPreset=eqHeaderView->preset(); - QVariantMap oldPlPreset=planetsHeaderView->preset(); + QVariantMap oldEqPreset = eqHeaderView->preset(); + QVariantMap oldPlPreset = planetsHeaderView->preset(); _reportSummary.clear(); _reportDepthList.clear(); QFileInfo fileInfo(_filename); - QString filename=fileInfo.path()+'/'+fileInfo.completeBaseName()+".report"; + QString filename = + fileInfo.path() + '/' + fileInfo.completeBaseName() + ".report"; QFile ofile(filename); - if(ofile.exists()) { - //QString timestamp=QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss"); - //QFile::rename(filename,_filename+timestamp+".report"); + if (ofile.exists()) { + // QString + // timestamp=QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss"); + // QFile::rename(filename,_filename+timestamp+".report"); QFile::remove(filename); } - if(!ofile.open(QIODevice::WriteOnly | QIODevice::Text)) { - showMessage(tr("Could not create the report file ")+filename); + if (!ofile.open(QIODevice::WriteOnly | QIODevice::Text)) { + showMessage(tr("Could not create the report file ") + filename); return; } - QString bhBuf=tr("Black holes: %1\n").arg(galaxy.blackHoleCount()); - - //Bases - ui->tradeTableView->sortByColumn(2,Qt::AscendingOrder); - QString basesBuf="Bases:\nname\tstar\tdistance\n"; - for(int row=0; rowtradeTableView->sortByColumn(2, Qt::AscendingOrder); + QString basesBuf = "Bases:\nname\tstar\tdistance\n"; + for (int row = 0; row < tradeProxyModel.rowCount(); row++) { + double dist = + tradeProxyModel.data(tradeProxyModel.index(row, 2)) + .toInt(); + int size = tradeProxyModel.data(tradeProxyModel.index(row, 27)) + .toInt(); + QString name = + tradeProxyModel.data(tradeProxyModel.index(row, 0)) + .toString(); + QString star = + tradeProxyModel.data(tradeProxyModel.index(row, 1)) + .toString(); + if (size == 0) { // Base, not planet + basesBuf += name + '\t' + star + '\t' + + QString::number(dist); + basesBuf += '\n'; continue; } } QString lastSummaryEntry; - //planets Presets + // planets Presets QString planetsBuf; - for(const QString& fileName: planetsReportPresets) - { + for (const QString &fileName : planetsReportPresets) { planetsHeaderView->setPreset(loadPreset(fileName)); - lastSummaryEntry=QFileInfo(fileName).baseName(); - _reportSummary[lastSummaryEntry]=planetsProxyModel.rowCount(); - lastSummaryEntry+=": "+QString::number(planetsProxyModel.rowCount()); - planetsBuf+=lastSummaryEntry+'\n'; - planetsBuf+=tabSeparatedValues(planetsProxyModel); - planetsBuf+='\n'; + lastSummaryEntry = QFileInfo(fileName).baseName(); + _reportSummary[lastSummaryEntry] = planetsProxyModel.rowCount(); + lastSummaryEntry += + ": " + QString::number(planetsProxyModel.rowCount()); + planetsBuf += lastSummaryEntry + '\n'; + planetsBuf += tabSeparatedValues(planetsProxyModel); + planetsBuf += '\n'; } - //eq Presets + // eq Presets QString eqBuf; - for(const QString& fileName: eqReportPresets) - { + for (const QString &fileName : eqReportPresets) { eqHeaderView->setPreset(loadPreset(fileName)); - lastSummaryEntry=QFileInfo(fileName).baseName(); - _reportSummary[lastSummaryEntry]=eqProxyModel.rowCount(); + lastSummaryEntry = QFileInfo(fileName).baseName(); + _reportSummary[lastSummaryEntry] = eqProxyModel.rowCount(); QVector depthList; - for(int proxyRow=0; proxyRowsetPreset(oldEqPreset); planetsHeaderView->setPreset(oldPlPreset); QTextStream out(&ofile); // we will serialize the data into the file out.setCodec("UTF-8"); - out << scoresSummary()+'\n'+planetsBuf+eqBuf+basesBuf+'\n'+bhBuf+'\n'; // serialize a string - - statusBar()->showMessage(tr("Report saved: ")+filename); - auto duration = duration_cast( high_resolution_clock::now() - tStart ).count(); - std::cout<<"Report saved: "+filename.toStdString()+" in "+ - to_string(duration/1000.0)+" s.\n"+ - reportSummary().toStdString()<showMessage(tr("Report saved: ") + filename); + auto duration = duration_cast(high_resolution_clock::now() + - tStart) + .count(); + std::cout << "Report saved: " + filename.toStdString() + " in " + + to_string(duration / 1000.0) + " s.\n" + + reportSummary().toStdString() + << std::endl; } void MainWindow::saveAllReports() { QFileInfo fileInfo(_filename); - QString filename=fileInfo.path()+"/summary.report"; + QString filename = fileInfo.path() + "/summary.report"; QFile ofile(filename); - if(ofile.exists()) { - //QString timestamp=QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss"); - //QFile::rename(filename,_filename+timestamp+".report"); + if (ofile.exists()) { + // QString + // timestamp=QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss"); + // QFile::rename(filename,_filename+timestamp+".report"); QFile::remove(filename); } - if(!ofile.open(QIODevice::WriteOnly | QIODevice::Text)) { - showMessage(tr("Could not create the summary report file ")+filename); + if (!ofile.open(QIODevice::WriteOnly | QIODevice::Text)) { + showMessage(tr("Could not create the summary report file ") + + filename); return; } QTextStream out(&ofile); out.setCodec("UTF-8"); - out << reportSummaryHeader()+'\n'; - for(const QString& dumpFileName: dumpFileList) - { + out << reportSummaryHeader() + '\n'; + for (const QString &dumpFileName : dumpFileList) { parseDump(dumpFileName); - if(!ui->actionAutoSaveReport->isChecked()) - { + if (!ui->actionAutoSaveReport->isChecked()) { saveReport(); } - out << QFileInfo(dumpFileName).baseName()+"\t"+reportSummary(false)+'\n'; + out << QFileInfo(dumpFileName).baseName() + "\t" + + reportSummary(false) + '\n'; } parseDump(dumpFileList[currentDumpIndex]); } void MainWindow::loadNextDump() { - if(currentDumpIndex<0 || currentDumpIndex>=dumpFileList.size()-1) { + if (currentDumpIndex < 0 + || currentDumpIndex >= dumpFileList.size() - 1) { return; } parseDump(dumpFileList[++currentDumpIndex]); @@ -612,16 +660,20 @@ void MainWindow::loadNextDump() void MainWindow::loadPreviousDump() { - if(currentDumpIndex<=0) { + if (currentDumpIndex <= 0) { return; } parseDump(dumpFileList[--currentDumpIndex]); updateDumpArrows(); } -void MainWindow::customHeaderMenuRequested(QPoint pos){ - eqMenuRow=ui->equipmentTableView->verticalHeader()->logicalIndexAt(pos); - eqMenu.popup(ui->equipmentTableView->verticalHeader()->viewport()->mapToGlobal(pos)); +void MainWindow::customHeaderMenuRequested(QPoint pos) +{ + eqMenuRow = + ui->equipmentTableView->verticalHeader()->logicalIndexAt(pos); + eqMenu.popup(ui->equipmentTableView->verticalHeader() + ->viewport() + ->mapToGlobal(pos)); } bool MainWindow::openDump(const QString &fileName) @@ -629,30 +681,31 @@ bool MainWindow::openDump(const QString &fileName) if (fileName.isEmpty()) return false; //_filename=fileName; - QDir currentDir=QFileInfo(fileName).dir(); + QDir currentDir = QFileInfo(fileName).dir(); currentDir.setNameFilters(QStringList("*.txt")); currentDir.setFilter(QDir::Files); - const QFileInfoList& infoList=currentDir.entryInfoList(); + const QFileInfoList &infoList = currentDir.entryInfoList(); dumpFileList.clear(); - for(const auto& info:infoList) - { - dumpFileList<addPreset(preset,QFileInfo(fileName).baseName()); - std::cout<addPreset(preset, + QFileInfo(fileName).baseName()); + std::cout << fileName.toLocal8Bit().toStdString() << std::endl; } - for(const QString& fileName:eqDir.entryList(QDir::Files)) - { - auto preset=loadPreset(eqDir.path()+'/'+fileName); - eqHeaderView->addPreset(preset,QFileInfo(fileName).baseName()); - std::cout<addPreset(preset, QFileInfo(fileName).baseName()); + std::cout << fileName.toLocal8Bit().toStdString() << std::endl; } - //Presets to include in reports: - std::cout<<"loading presets for reports:"<mapImageLabel->setPixmap(QPixmap::fromImage(galaxyMap)); ui->mapImageLabel->resize(galaxyMap.size()); } void MainWindow::updateDumpArrows() { - if(currentDumpIndex<0 || currentDumpIndex>=dumpFileList.size()-1) - { + if (currentDumpIndex < 0 + || currentDumpIndex >= dumpFileList.size() - 1) { ui->actionNextDump->setDisabled(true); - } - else - { + } else { ui->actionNextDump->setEnabled(true); } - if(currentDumpIndex<=0) - { + if (currentDumpIndex <= 0) { ui->actionPreviousDump->setDisabled(true); - } - else - { + } else { ui->actionPreviousDump->setEnabled(true); } } void MainWindow::saveMap() { - if(mapWidth>10) { + if (mapWidth > 10) { QFileInfo fileInfo(_filename); - QString filename=fileInfo.path()+'/'+fileInfo.completeBaseName()+"_map.png"; - if(QFileInfo(filename).exists()) { + QString filename = fileInfo.path() + '/' + + fileInfo.completeBaseName() + "_map.png"; + if (QFileInfo(filename).exists()) { QFile::remove(filename); } galaxyMap.save(filename); @@ -753,45 +798,45 @@ void MainWindow::saveMap() QVariantMap MainWindow::loadPreset(const QString &fileName) const { QFile file(fileName); - if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) { - showMessage(tr("Unable to open file ")+ - file.errorString()+" "+file.fileName()); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + showMessage(tr("Unable to open file ") + file.errorString() + + " " + file.fileName()); return QVariantMap(); } - QJsonDocument doc=QJsonDocument::fromJson(file.readAll()); - if(doc.isNull()) { + QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); + if (doc.isNull()) { showMessage(tr("Unable to parse JSON file")); return QVariantMap(); } return doc.toVariant().toMap(); } -QMap MainWindow::readScorers(const QString &filename) +QMap +MainWindow::readScorers(const QString &filename) { QMap scorers; QFile scorersFile(filename); - if (!scorersFile.open(QIODevice::ReadOnly|QIODevice::Text)) { + if (!scorersFile.open(QIODevice::ReadOnly | QIODevice::Text)) { return scorers; } - QJsonDocument doc=QJsonDocument::fromJson(scorersFile.readAll()); - if(doc.isNull()) { + QJsonDocument doc = QJsonDocument::fromJson(scorersFile.readAll()); + if (doc.isNull()) { return scorers; } - QVariantMap scorersJson=doc.toVariant().toMap(); - using VarMapCI=QVariantMap::const_iterator; - for (VarMapCI i = scorersJson.begin(); i != scorersJson.end(); ++i) - { + QVariantMap scorersJson = doc.toVariant().toMap(); + using VarMapCI = QVariantMap::const_iterator; + for (VarMapCI i = scorersJson.begin(); i != scorersJson.end(); ++i) { scorers[i.key()].read(i.value().toMap()); } return scorers; } -bool isUseless(const QMap& val, const QMap& min) +bool isUseless(const QMap &val, const QMap &min) { - using MapStrIntCI=QMap::const_iterator; - for (MapStrIntCI i = min.begin(); i != min.end(); ++i) - { - if(val.value(i.key(),0)::const_iterator; + for (MapStrIntCI i = min.begin(); i != min.end(); ++i) { + if (val.value(i.key(), 0) < i.value()) { + std::cout << i.key().toStdString() << " < " << i.value() + << std::endl; return true; } } @@ -801,48 +846,44 @@ bool isUseless(const QMap& val, const QMap& min) #ifdef _WIN32 bool rangersWindowActive() { - HWND wnd=GetForegroundWindow(); + HWND wnd = GetForegroundWindow(); DWORD windowProcessId = 0; - GetWindowThreadProcessId(wnd,&windowProcessId); - //std::cout<<"active window process: "<(message); - if (msg->message == WM_HOTKEY) - { - switch(msg->wParam) - { + if (msg->message == WM_HOTKEY) { + switch (msg->wParam) { case 100: saveDumpWin(); break; case 101: - //TODO: debug + // TODO: debug generateGalaxies(); sound.play(); break; @@ -853,51 +894,51 @@ bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long * return false; } -bool MainWindow::simulateInput(const std::string& str) const +bool MainWindow::simulateInput(const std::string &str) const { INPUT inp; inp.type = INPUT_KEYBOARD; inp.ki.wScan = 0; inp.ki.time = 0; - //inp.ki.dwFlags = 0; + // inp.ki.dwFlags = 0; inp.ki.dwExtraInfo = 0; std::vector ip; - for(char c:str) - { - if(std::islower(c)) - { - if(c=='e'){ - inp.ki.wScan = 0x1C;//Enter + for (char c : str) { + if (std::islower(c)) { + if (c == 'e') { + inp.ki.wScan = 0x1C; // Enter inp.ki.wVk = 0; - inp.ki.dwFlags = 0 | KEYEVENTF_SCANCODE; // 0 for key press + inp.ki.dwFlags = + 0 + | KEYEVENTF_SCANCODE; // 0 for key press ip.push_back(inp); - inp.ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; + inp.ki.dwFlags = + KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; ip.push_back(inp); - } - else if (c=='s'){ - inp.ki.wVk = 0x1B;//Esc; + } else if (c == 's') { + inp.ki.wVk = 0x1B; // Esc; inp.ki.dwFlags = 0; // 0 for key press ip.push_back(inp); inp.ki.dwFlags = KEYEVENTF_KEYUP; ip.push_back(inp); - } - else if (c=='f'){ - inp.ki.wVk = 0x78;//F9 + } else if (c == 'f') { + inp.ki.wVk = 0x78; // F9 inp.ki.dwFlags = 0; // 0 for key press ip.push_back(inp); inp.ki.dwFlags = KEYEVENTF_KEYUP; ip.push_back(inp); - } - else if (c=='b'){ + } else if (c == 'b') { inp.ki.wVk = 0; - inp.ki.wScan = 0x0E;//backspace - inp.ki.dwFlags = 0 | KEYEVENTF_SCANCODE; // 0 for key press + inp.ki.wScan = 0x0E; // backspace + inp.ki.dwFlags = + 0 + | KEYEVENTF_SCANCODE; // 0 for key press ip.push_back(inp); - inp.ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; + inp.ki.dwFlags = + KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; ip.push_back(inp); } - } - else { + } else { // Press normal key inp.ki.wVk = c; inp.ki.dwFlags = 0; // 0 for key press @@ -906,8 +947,9 @@ bool MainWindow::simulateInput(const std::string& str) const ip.push_back(inp); } } - if(!rangersWindowActive()) { - showMessage(tr("Rangers are not in focus, aborting input simulation.")); + if (!rangersWindowActive()) { + showMessage(tr( + "Rangers are not in focus, aborting input simulation.")); return false; } SendInput(ip.size(), ip.data(), sizeof(INPUT)); @@ -918,20 +960,21 @@ bool MainWindow::simulateInput(const std::string& str) const void MainWindow::saveDumpWin() { - //TODO: make function bool, return status - if(!rangersWindowActive()) { - showMessage(tr("Rangers are not in focus, aborting QuickDump.")); + // TODO: make function bool, return status + if (!rangersWindowActive()) { + showMessage( + tr("Rangers are not in focus, aborting QuickDump.")); return; } - _filename=rangersDir+"/save/autodump"; + _filename = rangersDir + "/save/autodump"; - if(QFileInfo(_filename+".txt").exists()) { - QFile::remove(_filename+".txt"); + if (QFileInfo(_filename + ".txt").exists()) { + QFile::remove(_filename + ".txt"); } - if(QFileInfo(_filename+".sav").exists()) { - QFile::remove(_filename+".sav"); + if (QFileInfo(_filename + ".sav").exists()) { + QFile::remove(_filename + ".sav"); } - _filename+=".txt"; + _filename += ".txt"; INPUT inp; inp.type = INPUT_KEYBOARD; @@ -940,120 +983,126 @@ void MainWindow::saveDumpWin() inp.ki.dwFlags = 0; inp.ki.dwExtraInfo = 0; - std::vector ip(2,inp); + std::vector ip(2, inp); - //First imitate Ctrl+Shift+MAKEDUMP + // First imitate Ctrl+Shift+MAKEDUMP ip[0].ki.wVk = VK_CONTROL; ip[1].ki.wVk = VK_SHIFT; SendInput(ip.size(), ip.data(), sizeof(INPUT)); responsiveSleep(shortSleep); - if(!simulateInput("MAKEDUMP")) { + if (!simulateInput("MAKEDUMP")) { return; } ip.clear(); inp.ki.wVk = VK_SHIFT; - inp.ki.dwFlags = KEYEVENTF_KEYUP ; + inp.ki.dwFlags = KEYEVENTF_KEYUP; ip.push_back(inp); inp.ki.wVk = VK_CONTROL; inp.ki.dwFlags = KEYEVENTF_KEYUP; ip.push_back(inp); SendInput(ip.size(), ip.data(), sizeof(INPUT)); - responsiveSleep(shortSleep*75);//Wait for save window to showup + responsiveSleep(shortSleep * 75); // Wait for save window to showup - //Remove proposed save name - if(!simulateInput("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) { + // Remove proposed save name + if (!simulateInput( + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) { return; } - //Enter new save name ("autodump") - if(!simulateInput("AUTODUMP")) { + // Enter new save name ("autodump") + if (!simulateInput("AUTODUMP")) { return; } - //Press Enter to save - if(!simulateInput("e")) { + // Press Enter to save + if (!simulateInput("e")) { return; } - //wait till the saving has finished - const int dt=300; - int oldSize=0; + // wait till the saving has finished + const int dt = 300; + int oldSize = 0; QFileInfo fileInfo(_filename); - QString cyrFilename=_filename; - cyrFilename.replace("autodump.txt","фгещвгьз.txt"); - auto cyrFileInfo=QFileInfo(cyrFilename); - for(int t=0; t<30000; t+=dt) - { + QString cyrFilename = _filename; + cyrFilename.replace("autodump.txt", "фгещвгьз.txt"); + auto cyrFileInfo = QFileInfo(cyrFilename); + for (int t = 0; t < 30000; t += dt) { responsiveSleep(dt); fileInfo.refresh(); - if(fileInfo.size()==0) { + if (fileInfo.size() == 0) { cyrFileInfo.refresh(); - if(cyrFileInfo.size()>0) { - fileInfo=cyrFileInfo; + if (cyrFileInfo.size() > 0) { + fileInfo = cyrFileInfo; } } - int size=fileInfo.size(); - if(size && size==oldSize) { + int size = fileInfo.size(); + if (size && size == oldSize) { QFile::rename(cyrFilename, _filename); - QFile::rename(cyrFilename.left(cyrFilename.length() - 4)+".sav", _filename.left(_filename.length() - 4)+".sav"); + QFile::rename(cyrFilename.left(cyrFilename.length() - 4) + + ".sav", + _filename.left(_filename.length() - 4) + + ".sav"); parseDump(); return; } - oldSize=size; + oldSize = size; } - showMessage(tr("Could not save the dump, timeot reached. Not parsing.")); + showMessage( + tr("Could not save the dump, timeot reached. Not parsing.")); } QImage MainWindow::currentScreen(float kx, float ky, float kw, float kh) { using namespace std; - auto screenTaken=QDateTime::currentDateTime(); - if(!simulateInput("f")) {//make new screenshot + auto screenTaken = QDateTime::currentDateTime(); + if (!simulateInput("f")) { // make new screenshot return QImage(); } - const QString rangersDir=QStandardPaths::locate(QStandardPaths::DocumentsLocation,"SpaceRangersHD",QStandardPaths::LocateDirectory); - QDir dir(rangersDir+"/Screenshots"); + const QString rangersDir = QStandardPaths::locate( + QStandardPaths::DocumentsLocation, "SpaceRangersHD", + QStandardPaths::LocateDirectory); + QDir dir(rangersDir + "/Screenshots"); QStringList fileList; QString screenFilename; QDateTime fileModified; responsiveSleep(screenSaveLag); int t; - for(t=screenSaveLag; t<8000; t+=screenSaveLag*0.1) - { - responsiveSleep(screenSaveLag*0.1); + for (t = screenSaveLag; t < 8000; t += screenSaveLag * 0.1) { + responsiveSleep(screenSaveLag * 0.1); dir.refresh(); - fileList=dir.entryList(QDir::Files,QDir::Time); - if(fileList.isEmpty()){ + fileList = dir.entryList(QDir::Files, QDir::Time); + if (fileList.isEmpty()) { continue; } - screenFilename=dir.absolutePath()+"/"+fileList.first(); - fileModified=QFileInfo(screenFilename).lastModified(); - if(screenTaken.msecsTo(fileModified)<0) {//old screenshot + screenFilename = dir.absolutePath() + "/" + fileList.first(); + fileModified = QFileInfo(screenFilename).lastModified(); + if (screenTaken.msecsTo(fileModified) < 0) { // old screenshot continue; - } - else { + } else { break; } } - if(screenFilename.isEmpty()) { - cerr< realGenTimes(10,maxGenerationTime); - const unsigned historyLength=10; - std::vector numGenChecks(historyLength,10); + int generationTime = 20000; + // std::vector realGenTimes(10,maxGenerationTime); + const unsigned historyLength = 10; + std::vector numGenChecks(historyLength, 10); QImage originalGenerationFinished; - for(int i=0; ;i++) - { - high_resolution_clock::time_point iterationStart = high_resolution_clock::now(); + for (int i = 0;; i++) { + high_resolution_clock::time_point iterationStart = + high_resolution_clock::now(); - //check, if the state is right - auto currentMainMenu=currentScreen(0,0.9,0.05,0.1); - if(currentMainMenu!=originalMainMenu) { + // check, if the state is right + auto currentMainMenu = currentScreen(0, 0.9, 0.05, 0.1); + if (currentMainMenu != originalMainMenu) { currentMainMenu.save("failedMainMenu.png"); - showMessage(tr("Main menu is expected, but does not match. Generation stopped. ")); + showMessage(tr( + "Main menu is expected, but does not match. Generation stopped. ")); return; } - //New Game - if(!simulateInput("N")) { + // New Game + if (!simulateInput("N")) { return; } - responsiveSleep(shortSleep*8); - //Enter (start generation) - if(!simulateInput("e")) { + responsiveSleep(shortSleep * 8); + // Enter (start generation) + if (!simulateInput("e")) { return; } - responsiveSleep(shortSleep*8); - //Enter (continue to generation if extra settings opened, ignored if it is already generating) - if(!simulateInput("e")) { + responsiveSleep(shortSleep * 8); + // Enter (continue to generation if extra settings opened, + // ignored if it is already generating) + if (!simulateInput("e")) { return; } - //Wait until the galaxy is ready - high_resolution_clock::time_point tGenerationStarted = high_resolution_clock::now(); + // Wait until the galaxy is ready + high_resolution_clock::time_point tGenerationStarted = + high_resolution_clock::now(); QImage currentGenerationFinished; - if(i==0) {//first run + if (i == 0) { // first run responsiveSleep(maxGenerationTime); - originalGenerationFinished=currentScreen(0.45,0.925,0.1,0.05); - originalGenerationFinished.save("originalGenerationFinished.png"); - } - else { + originalGenerationFinished = + currentScreen(0.45, 0.925, 0.1, 0.05); + originalGenerationFinished.save( + "originalGenerationFinished.png"); + } else { responsiveSleep(generationTime); - const int dt=3000; + const int dt = 3000; int t; - numGenChecks[i%historyLength]=0; - for(t=generationTime; t=maxGenerationTime) { - currentGenerationFinished.save("failedGenerationFinished.png"); - showMessage(tr("Galaxy_generation_finished is expected, but does not match. Generation stopped")); + if (t >= maxGenerationTime) { + currentGenerationFinished.save( + "failedGenerationFinished.png"); + showMessage(tr( + "Galaxy_generation_finished is expected, but does not match. Generation stopped")); return; } - high_resolution_clock::time_point tGenerationFinished = high_resolution_clock::now(); - auto curGenerationTime=duration_cast( tGenerationFinished - tGenerationStarted ).count(); - //realGenTimes[i%10]=generationTime; - std::cout<<"Last galaxy generation took: "<( + tGenerationFinished + - tGenerationStarted) + .count(); + // realGenTimes[i%10]=generationTime; + std::cout << "Last galaxy generation took: " + << curGenerationTime / 1000.0 << "s. "; + int minChecks = *std::min_element(numGenChecks.begin(), + numGenChecks.end()); + std::cout << "Succeeded after " + << numGenChecks[i % historyLength] + << " checks. "; + std::cout << "Minimum number of checks: " << minChecks + << ". "; + if (numGenChecks[i % historyLength] < 2) { + generationTime -= 1000; } else { - minChecks=std::max(2,minChecks); - generationTime+=1000*(minChecks-2); + minChecks = std::max(2, minChecks); + generationTime += 1000 * (minChecks - 2); } - std::cout<<"Trying next: "<actionAutoSaveReport->isChecked()) { + if (!ui->actionAutoSaveReport->isChecked()) { saveReport(); } - QString timestamp=QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss"); - - QString prefix=rangersDir+"/save/autodump"; - if(isUseless(_reportSummary,minRowsPreset)) {//useless save - QFile::remove(prefix+".txt"); - QFile::remove(prefix+".sav"); - QFile::remove(prefix+".report"); - QFile::remove(prefix+"_map.png"); - } - else { - QFile::rename(prefix+".txt",prefix+timestamp+".txt"); - QFile::rename(prefix+".sav",prefix+timestamp+".sav_"); - QFile::rename(prefix+".report",prefix+timestamp+".report"); - QFile::rename(prefix+"_map.png",prefix+timestamp+"_map.png"); + QString timestamp = QDateTime::currentDateTime().toString( + "yyyyMMdd-hhmmss"); + + QString prefix = rangersDir + "/save/autodump"; + if (isUseless(_reportSummary, minRowsPreset)) { // useless save + QFile::remove(prefix + ".txt"); + QFile::remove(prefix + ".sav"); + QFile::remove(prefix + ".report"); + QFile::remove(prefix + "_map.png"); + } else { + QFile::rename(prefix + ".txt", + prefix + timestamp + ".txt"); + QFile::rename(prefix + ".sav", + prefix + timestamp + ".sav_"); + QFile::rename(prefix + ".report", + prefix + timestamp + ".report"); + QFile::rename(prefix + "_map.png", + prefix + timestamp + "_map.png"); } - responsiveSleep(shortSleep*20); - if(!simulateInput("s")) {//Esc + responsiveSleep(shortSleep * 20); + if (!simulateInput("s")) { // Esc return; } - responsiveSleep(shortSleep*40); - if(!simulateInput("E")) {//E==exit + responsiveSleep(shortSleep * 40); + if (!simulateInput("E")) { // E==exit return; } - if(!simulateInput("e")) {//Enter (confirm) + if (!simulateInput("e")) { // Enter (confirm) return; } - responsiveSleep(shortSleep*40); - int iterationTime=duration_cast( high_resolution_clock::now() - iterationStart ).count(); - std::string logoutstr=timestamp.toStdString()+ - ": Iteration "+std::to_string(i)+ - " finished in "+to_string(iterationTime)+ - " s. "; - logfile<(high_resolution_clock::now() + - iterationStart) + .count(); + std::string logoutstr = timestamp.toStdString() + ": Iteration " + + std::to_string(i) + " finished in " + + to_string(iterationTime) + " s. "; + logfile << logoutstr + reportSummary().toStdString() << endl; + std::cout << logoutstr << endl; } } #endif @@ -1208,19 +1283,19 @@ void MainWindow::Scorer::read(const QVariantMap &map) presetNames.clear(); weights.clear(); areBoolean.clear(); - using VarMapCI=QVariantMap::const_iterator; - for (VarMapCI i = map.begin(); i != map.end(); ++i) - { - QVariantMap score=i.value().toMap(); - const QString& presetName=i.key(); - double weight=score.value("weight").toDouble(); - bool isBool=score.value("isBool").toBool(); - bool penalize=score.value("depthPenalize").toBool(); - addPreset(presetName,weight,isBool,penalize); + using VarMapCI = QVariantMap::const_iterator; + for (VarMapCI i = map.begin(); i != map.end(); ++i) { + QVariantMap score = i.value().toMap(); + const QString &presetName = i.key(); + double weight = score.value("weight").toDouble(); + bool isBool = score.value("isBool").toBool(); + bool penalize = score.value("depthPenalize").toBool(); + addPreset(presetName, weight, isBool, penalize); } } -void MainWindow::Scorer::addPreset(const QString presetName, double weight, bool isBool, bool depthPenalize) +void MainWindow::Scorer::addPreset(const QString presetName, double weight, + bool isBool, bool depthPenalize) { presetNames.push_back(presetName); weights.push_back(weight); @@ -1232,15 +1307,16 @@ QStringList supportedColors() { QVariantList colorNames; QFile file("selection_colors.json"); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){ - std::cerr<<"could not open selection_colors.json"<0 0 685 - 22 + 30 @@ -91,21 +91,21 @@ false - - 18 - 10 + + 18 + true - - 18 - 10 + + 18 + false @@ -163,21 +163,21 @@ QTableView::item false - - 18 - 10 + + 18 + true - - 18 - 10 + + 18 + @@ -223,18 +223,18 @@ QTableView::item false - - 18 - 10 - + 18 10 + + 18 + @@ -256,12 +256,7 @@ QTableView::item { font: 9pt "Sans Serif"; } -QTableView::item -{ - border: 0px; - padding: 0px; - margin: 0px; -} + QAbstractItemView::NoEditTriggers @@ -284,21 +279,21 @@ QTableView::item false - - 18 - 10 + + 18 + true - - 18 - 10 + + 18 + @@ -338,8 +333,8 @@ QTableView::item 0 0 - 270 - 73 + 264 + 85 diff --git a/SRHDDumpReader.pro b/SRHDDumpReader.pro index 47df9fe..beee54f 100644 --- a/SRHDDumpReader.pro +++ b/SRHDDumpReader.pro @@ -4,10 +4,10 @@ # #------------------------------------------------- -COMMIT_BRANCH = $$system(git rev-parse --abbrev-ref HEAD) COMMIT_DATE = $$system(git show -s --pretty='%ci') COMMIT_DATE = $$first(COMMIT_DATE) COMMIT_HASH = $$system(git log --pretty=format:'%h' -n 1) +COMMIT_BRANCH =$$system(git branch -a --contains $$COMMIT_HASH | grep -v HEAD | head -n1 | tr / \' \' | awk \'{print $NF}\') DEFINES += APP_VERSION=\\\"$$COMMIT_DATE-$$COMMIT_BRANCH-$$COMMIT_HASH\\\" CONFIG(release, debug|release): DEFINES+=NDEBUG