initial port for Cevo game in C++ (libs)

This commit is contained in:
Geoffray Levasseur committed 2026-10-22 17:20:45 +02:00
commit 8436242032
375 files changed
+46282

No files matched your search

+95
View File
@@ -0,0 +1,95 @@
# CevoCommon: Qt port of perso/cevo/Packages/Common (the game-agnostic
# utility package every other Lazarus package/form depends on) - one shared
# library, `cevocommon`, mirroring the original's single Common.lpk package.
# Forms/ mirrors Packages/Common/Forms (dialogs built on the rest of this
# library); the game-specific forms (perso/cevo/Forms/) are a separate,
# later task.
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets Xml)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets Xml)
set(CEVO_COMMON_HEADERS
include/Cevo/ApplicationInfo.h
include/Cevo/ColorButton.h
include/Cevo/DataFile.h
include/Cevo/DebugLog.h
include/Cevo/Delay.h
include/Cevo/FormBase.h
include/Cevo/Geometric.h
include/Cevo/Item.h
include/Cevo/MetaCanvas.h
include/Cevo/PersistentForm.h
include/Cevo/Pool.h
include/Cevo/PrefixMultiplier.h
include/Cevo/StringTable.h
include/Cevo/SyncCounter.h
include/Cevo/Table.h
include/Cevo/TestCase.h
include/Cevo/Threading.h
include/Cevo/XML.h
Forms/include/Cevo/FormAbout.h
Forms/include/Cevo/FormItem.h
Forms/include/Cevo/FormJobProgress.h
Forms/include/Cevo/FormKeyShortcuts.h
Forms/include/Cevo/FormList.h
Forms/include/Cevo/FormTest.h
Forms/include/Cevo/FormTests.h
)
set(CEVO_COMMON_SOURCES
src/ColorButton.cpp
src/DataFile.cpp
src/DebugLog.cpp
src/Delay.cpp
src/FormBase.cpp
src/Geometric.cpp
src/Item.cpp
src/MetaCanvas.cpp
src/PersistentForm.cpp
src/PrefixMultiplier.cpp
src/StringTable.cpp
src/SyncCounter.cpp
src/Table.cpp
src/TestCase.cpp
src/Threading.cpp
src/XML.cpp
Forms/src/FormAbout.cpp
Forms/src/FormItem.cpp
Forms/src/FormJobProgress.cpp
Forms/src/FormKeyShortcuts.cpp
Forms/src/FormList.cpp
Forms/src/FormTest.cpp
Forms/src/FormTests.cpp
)
set(CEVO_COMMON_UI
Forms/src/FormAbout.ui
Forms/src/FormItem.ui
Forms/src/FormJobProgress.ui
Forms/src/FormKeyShortcuts.ui
Forms/src/FormList.ui
Forms/src/FormTest.ui
Forms/src/FormTests.ui
)
add_library(cevocommon SHARED ${CEVO_COMMON_SOURCES} ${CEVO_COMMON_HEADERS} ${CEVO_COMMON_UI})
target_include_directories(cevocommon PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include
${CMAKE_CURRENT_SOURCE_DIR}/Forms/include
)
target_link_libraries(cevocommon PUBLIC Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Xml)
set_target_properties(cevocommon PROPERTIES
AUTOMOC ON
AUTOUIC ON
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
)
include(GNUInstallDirs)
install(TARGETS cevocommon
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/cevo-evo
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}/cevo-evo
)
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include "Cevo/ApplicationInfo.h"
#include "Cevo/FormBase.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class FormAbout;
}
QT_END_NAMESPACE
namespace Cevo {
// Equivalent of FormAbout.pas's TFormAbout.
class FormAbout : public FormBase {
Q_OBJECT
public:
explicit FormAbout(QWidget *parent = nullptr);
~FormAbout() override;
const ApplicationInfo *applicationInfo() const { return m_applicationInfo; }
void setApplicationInfo(const ApplicationInfo *value) { m_applicationInfo = value; }
void updateInterface();
protected:
void showEvent(QShowEvent *event) override;
private slots:
void onHomePageClicked();
private:
Ui::FormAbout *ui;
const ApplicationInfo *m_applicationInfo = nullptr;
};
} // namespace Cevo
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#include "Cevo/FormBase.h"
#include "Cevo/Item.h"
#include <QVector>
class QLabel;
class QWidget;
QT_BEGIN_NAMESPACE
namespace Ui {
class FormItem;
}
QT_END_NAMESPACE
namespace Cevo {
// Equivalent of FormItem.pas's TFormItem: builds one label+control pair per
// ItemField on the fly, based on each field's DataType.
class FormItem : public FormBase {
Q_OBJECT
public:
explicit FormItem(QWidget *parent = nullptr);
~FormItem() override;
Item *item() const { return m_item; }
void setItem(Item *value);
void updateInterface();
private slots:
void onOkClicked();
void onControlChanged();
private:
void initControls();
void loadData(Item *item);
void saveData(Item *item);
Ui::FormItem *ui;
Item *m_item = nullptr;
QVector<QWidget *> m_dataControls;
QVector<QLabel *> m_dataLabels;
};
} // namespace Cevo
+163
View File
@@ -0,0 +1,163 @@
#pragma once
#include "Cevo/FormBase.h"
#include <QDateTime>
#include <QElapsedTimer>
#include <QObject>
#include <QString>
#include <QStringList>
#include <functional>
#include <memory>
#include <vector>
class QCloseEvent;
class QTimer;
QT_BEGIN_NAMESPACE
namespace Ui {
class FormJobProgress;
}
QT_END_NAMESPACE
namespace Cevo {
class Job;
class FormJobProgress;
// Equivalent of JobProgressView.pas's TProgress. Safe to update from the
// job's worker thread: setters only touch this object's own data (never
// read back from another thread) and emit `changed()`, which Qt delivers
// as a queued call to FormJobProgress's slot since that object lives on
// the main thread - no mutex needed, unlike the original's TCriticalSection.
// Push-based: unlike the original (where only SetValue invoked OnChange,
// and SetMax/SetText only ever reached the UI via the 100ms poll timer),
// all three setters emit `changed()` here for immediate, lag-free updates.
class JobProgress : public QObject {
Q_OBJECT
public:
using QObject::QObject;
int value() const { return m_value; }
int max() const { return m_max; }
QString text() const { return m_text; }
void setMax(int value);
void setText(const QString &text);
void setValue(int value);
void increment();
void reset();
signals:
void changed();
private:
int m_value = 0;
int m_max = 100;
QString m_text;
};
// Equivalent of JobProgressView.pas's TJob.
class Job {
public:
explicit Job(FormJobProgress *owner);
QString title;
std::function<void(Job &)> method;
bool noThreaded = false;
// Kept for interface fidelity with TJob.WaitFor, which the original
// itself never reads anywhere either (write-only field upstream too).
bool waitFor = false;
bool finished = false;
QString resultString;
QDateTime startTime;
QDateTime endTime;
JobProgress progress;
// Appends to the owning dialog's log, marshalling to the main thread
// if called from the job's worker thread (equivalent of TJob.AddLogItem).
void addLogItem(const QString &text);
bool isTerminateRequested() const { return m_terminateRequested; }
void requestTerminate() { m_terminateRequested = true; }
private:
FormJobProgress *m_owner;
bool m_terminateRequested = false;
};
// Equivalent of JobProgressView.pas's TFormJobProgressView + TJobProgressView
// merged into one dialog (Qt's QDialog already is the "component that owns
// the form" the original split across two classes for Lazarus-IDE-palette
// reasons - RegisterComponents('Common', [TJobProgressView]) has no Qt
// equivalent). NOT ported: the OwnerDraw/OnOwnerDraw hook (lets a caller
// suppress the dialog and draw its own progress UI instead) - grepping the
// whole perso/cevo tree found no actual consumer of TJobProgressView at
// all, so this is dead infrastructure; drop it and simply don't call
// start() if you want fully custom progress UI.
class FormJobProgress : public FormBase {
Q_OBJECT
public:
explicit FormJobProgress(QWidget *parent = nullptr);
~FormJobProgress() override;
bool autoClose() const { return m_autoClose; }
void setAutoClose(bool value) { m_autoClose = value; }
// Delay, in ms, before the dialog actually shows itself once start() is
// running (0 shows immediately). Equivalent of TJobProgressView.ShowDelay.
int showDelay() const { return m_showDelay; }
void setShowDelay(int value) { m_showDelay = value; }
// Equivalent of TJobProgressView.AddJob. Ownership stays with this
// dialog; the returned pointer stays valid until clear() or destruction.
Job *addJob(const QString &title, std::function<void(Job &)> method, bool noThreaded = false,
bool waitFor = false);
void clear();
// Equivalent of TJobProgressView.Start: runs every added job in order,
// blocking the caller until all jobs finish or stop() is called, while
// pumping the Qt event loop (via Threading.h's runInThread()) so the
// dialog stays responsive - matches the original's
// Application.ProcessMessages-pumping wait loop.
void start();
// Equivalent of TJobProgressView.Stop / the Terminate property setter:
// cooperatively asks the current (and all pending) jobs to stop.
void stop();
bool isTerminateRequested() const { return m_terminateRequested; }
signals:
void jobFinished(Job *job);
protected:
void closeEvent(QCloseEvent *event) override;
private slots:
void onTimerUpdate();
private:
void reloadJobList();
void updateProgress();
void updateHeight();
void appendLog(const QString &text);
friend class Job;
Ui::FormJobProgress *ui;
QTimer *m_updateTimer;
std::vector<std::unique_ptr<Job>> m_jobs;
int m_currentJobIndex = -1;
Job *m_currentJob = nullptr;
bool m_finished = false;
bool m_autoClose = true;
int m_showDelay = 0;
bool m_terminateRequested = false;
QDateTime m_totalStartTime;
QElapsedTimer m_partElapsed;
QStringList m_log;
};
} // namespace Cevo
@@ -0,0 +1,47 @@
#pragma once
#include "Cevo/FormBase.h"
#include <QList>
#include <QPointer>
class QObject;
QT_BEGIN_NAMESPACE
namespace Ui {
class FormKeyShortcuts;
}
QT_END_NAMESPACE
namespace Cevo {
// Equivalent of FormKeyShortcuts.pas's TFormKeyShortcuts: lists every
// QAction found (recursively) under a set of source objects, with its
// shortcut, double-click/Enter to trigger it. Column sorting uses
// QTreeWidget's native header-click sorting - no ListViewSort port needed.
class FormKeyShortcuts : public FormBase {
Q_OBJECT
public:
explicit FormKeyShortcuts(QWidget *parent = nullptr);
~FormKeyShortcuts() override;
// Equivalent of LoadFromComponent: objects whose QAction children (found
// recursively) should be listed.
void setSourceObjects(const QList<QObject *> &objects) { m_sourceObjects = objects; }
void setMainWindow(QWidget *window) { m_mainWindow = window; }
protected:
void showEvent(QShowEvent *event) override;
private slots:
void onExecuteSelected();
private:
void reload();
Ui::FormKeyShortcuts *ui;
QList<QObject *> m_sourceObjects;
QPointer<QWidget> m_mainWindow;
};
} // namespace Cevo
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include "Cevo/FormBase.h"
#include "Cevo/Item.h"
class QAction;
QT_BEGIN_NAMESPACE
namespace Ui {
class FormList;
}
QT_END_NAMESPACE
namespace Cevo {
// Equivalent of FormList.pas's TFormList: add/modify/remove/clone items of
// a BaseItemList, with columns derived from the list's ItemFields.
class FormList : public FormBase {
Q_OBJECT
public:
explicit FormList(QWidget *parent = nullptr);
~FormList() override;
BaseItemList *list() const { return m_list; }
void setList(BaseItemList *value);
int minItemCount = 0;
int maxItemCount = -1; // -1: unlimited
protected:
void showEvent(QShowEvent *event) override;
private slots:
void onAdd();
void onModify();
void onRemove();
void onClone();
void onSelectAll();
void onSelectionChanged();
private:
void updateColumns();
void updateList();
void updateInterface();
Ui::FormList *ui;
BaseItemList *m_list = nullptr;
QAction *m_actionAdd = nullptr;
QAction *m_actionModify = nullptr;
QAction *m_actionRemove = nullptr;
QAction *m_actionClone = nullptr;
};
} // namespace Cevo
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include "Cevo/FormBase.h"
#include "Cevo/TestCase.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class FormTest;
}
QT_END_NAMESPACE
namespace Cevo {
// Equivalent of FormTest.pas's TFormTest.
class FormTest : public FormBase {
Q_OBJECT
public:
explicit FormTest(QWidget *parent = nullptr);
~FormTest() override;
TestCase *testCase() const { return m_testCase; }
void setTestCase(TestCase *value) { m_testCase = value; }
protected:
void showEvent(QShowEvent *event) override;
private slots:
void onRunClicked();
private:
Ui::FormTest *ui;
TestCase *m_testCase = nullptr;
};
} // namespace Cevo
+41
View File
@@ -0,0 +1,41 @@
#pragma once
#include "Cevo/FormBase.h"
#include "Cevo/TestCase.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class FormTests;
}
QT_END_NAMESPACE
namespace Cevo {
// Equivalent of FormTests.pas's TFormTests.
class FormTests : public FormBase {
Q_OBJECT
public:
explicit FormTests(QWidget *parent = nullptr);
~FormTests() override;
TestCases *testCases() const { return m_testCases; }
void setTestCases(TestCases *value);
protected:
void showEvent(QShowEvent *event) override;
private slots:
void onRunClicked();
void onRunSelected();
void onShowSelected();
void onSelectionChanged();
private:
void reloadList();
void updateInterface();
Ui::FormTests *ui;
TestCases *m_testCases = nullptr;
};
} // namespace Cevo
+44
View File
@@ -0,0 +1,44 @@
#include "Cevo/FormAbout.h"
#include "ui_FormAbout.h"
#include <QDesktopServices>
#include <QUrl>
namespace Cevo {
FormAbout::FormAbout(QWidget *parent) : FormBase(parent), ui(new Ui::FormAbout)
{
ui->setupUi(this);
connect(ui->buttonHomePage, &QPushButton::clicked, this, &FormAbout::onHomePageClicked);
}
FormAbout::~FormAbout()
{
delete ui;
}
void FormAbout::showEvent(QShowEvent *event)
{
FormBase::showEvent(event);
if (m_applicationInfo) {
ui->labelAppName->setText(m_applicationInfo->appName);
ui->labelContent->setText(tr("Version") + ": " + m_applicationInfo->version() + '\n' + tr("Release date") +
": " + m_applicationInfo->releaseDate.toString() + '\n' + tr("License") + ": " +
m_applicationInfo->license);
ui->labelDescription->setText(m_applicationInfo->description);
ui->imageLogo->setPixmap(m_applicationInfo->icon);
}
updateInterface();
}
void FormAbout::updateInterface()
{
ui->buttonHomePage->setEnabled(m_applicationInfo != nullptr);
}
void FormAbout::onHomePageClicked()
{
QDesktopServices::openUrl(QUrl(m_applicationInfo->homePage));
}
} // namespace Cevo
+109
View File
@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FormAbout</class>
<widget class="QDialog" name="FormAbout">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>480</width>
<height>280</height>
</rect>
</property>
<property name="windowTitle">
<string>About</string>
</property>
<layout class="QVBoxLayout" name="mainLayout">
<item>
<layout class="QHBoxLayout" name="topLayout">
<item>
<widget class="QLabel" name="imageLogo">
<property name="minimumSize">
<size>
<width>48</width>
<height>48</height>
</size>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelAppName">
<property name="font">
<font>
<pointsize>20</pointsize>
</font>
</property>
<property name="text">
<string>Title</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="labelDescription">
<property name="text">
<string>Description</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelContent">
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
</spacer>
</item>
<item>
<layout class="QHBoxLayout" name="buttonLayout">
<item>
<widget class="QPushButton" name="buttonHomePage">
<property name="text">
<string>Home page</string>
</property>
</widget>
</item>
<item>
<spacer name="buttonSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="buttonClose">
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonClose</sender>
<signal>clicked()</signal>
<receiver>FormAbout</receiver>
<slot>accept()</slot>
</connection>
</connections>
</ui>
+203
View File
@@ -0,0 +1,203 @@
#include "Cevo/FormItem.h"
#include "Cevo/ColorButton.h"
#include "ui_FormItem.h"
#include <QCheckBox>
#include <QComboBox>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QSpinBox>
#include <limits>
#include <stdexcept>
namespace Cevo {
FormItem::FormItem(QWidget *parent) : FormBase(parent), ui(new Ui::FormItem)
{
ui->setupUi(this);
connect(ui->buttonOk, &QPushButton::clicked, this, &FormItem::onOkClicked);
}
FormItem::~FormItem()
{
delete ui;
}
void FormItem::setItem(Item *value)
{
if (m_item == value)
return;
m_item = value;
if (m_item) {
initControls();
loadData(m_item);
setWindowTitle(m_item->className());
} else {
qDeleteAll(m_dataControls);
qDeleteAll(m_dataLabels);
m_dataControls.clear();
m_dataLabels.clear();
}
}
void FormItem::initControls()
{
auto *layout = qobject_cast<QFormLayout *>(ui->scrollBoxContents->layout());
qDeleteAll(m_dataControls);
qDeleteAll(m_dataLabels);
m_dataControls.clear();
m_dataLabels.clear();
const ItemFields fields = m_item->getFields();
for (const ItemField &field : fields) {
auto *label = new QLabel(field.name + ':', ui->scrollBoxContents);
QWidget *control = nullptr;
switch (field.dataType) {
case DataType::Integer: {
auto *spin = new QSpinBox(ui->scrollBoxContents);
spin->setMaximum(std::numeric_limits<int>::max());
control = spin;
break;
}
case DataType::String:
control = new QLineEdit(ui->scrollBoxContents);
break;
case DataType::Color:
control = new ColorButton(ui->scrollBoxContents);
break;
case DataType::Enumeration: {
auto *combo = new QComboBox(ui->scrollBoxContents);
connect(combo, &QComboBox::currentIndexChanged, this, &FormItem::onControlChanged);
control = combo;
break;
}
case DataType::Reference:
control = new QComboBox(ui->scrollBoxContents);
break;
case DataType::Boolean:
control = new QCheckBox(ui->scrollBoxContents);
break;
default:
throw std::invalid_argument(("Unsupported field value data type " + dataTypeStr(field.dataType)).toStdString());
}
layout->addRow(label, control);
m_dataLabels.append(label);
m_dataControls.append(control);
}
}
void FormItem::loadData(Item *item)
{
const ItemFields fields = item->getFields();
for (int i = 0; i < fields.count(); ++i) {
const ItemField &field = fields.at(i);
QWidget *control = m_dataControls.at(i);
switch (field.dataType) {
case DataType::Integer:
qobject_cast<QSpinBox *>(control)->setValue(item->getValueInt(field.index));
break;
case DataType::String:
qobject_cast<QLineEdit *>(control)->setText(item->getValueString(field.index));
break;
case DataType::Color:
qobject_cast<ColorButton *>(control)->setColor(item->getValueColor(field.index));
break;
case DataType::Boolean:
qobject_cast<QCheckBox *>(control)->setChecked(item->getValueBool(field.index));
break;
case DataType::Enumeration: {
auto *combo = qobject_cast<QComboBox *>(control);
const QSignalBlocker blocker(combo);
combo->clear();
combo->addItems(field.enumStates);
combo->setCurrentIndex(item->getValueEnum(field.index));
break;
}
case DataType::Reference: {
auto *combo = qobject_cast<QComboBox *>(control);
const QSignalBlocker blocker(combo);
combo->clear();
BaseItemList *referenceList = item->getReferenceList(field.index);
if (referenceList) {
for (int j = 0; j < referenceList->count(); ++j) {
Item *refItem = referenceList->at(j);
combo->addItem(refItem->name, QVariant::fromValue(static_cast<Item *>(refItem)));
}
}
Item *referenceItem = item->getValueReference(field.index);
combo->setCurrentIndex(combo->findData(QVariant::fromValue(referenceItem)));
break;
}
default:
throw std::invalid_argument(("Unsupported field value data type " + dataTypeStr(field.dataType)).toStdString());
}
}
updateInterface();
}
void FormItem::saveData(Item *item)
{
const ItemFields fields = item->getFields();
for (int i = 0; i < fields.count(); ++i) {
const ItemField &field = fields.at(i);
QWidget *control = m_dataControls.at(i);
switch (field.dataType) {
case DataType::Integer:
item->setValueInt(field.index, qobject_cast<QSpinBox *>(control)->value());
break;
case DataType::String:
item->setValueString(field.index, qobject_cast<QLineEdit *>(control)->text());
break;
case DataType::Color:
item->setValueColor(field.index, qobject_cast<ColorButton *>(control)->color());
break;
case DataType::Boolean:
item->setValueBool(field.index, qobject_cast<QCheckBox *>(control)->isChecked());
break;
case DataType::Enumeration:
item->setValueEnum(field.index, qobject_cast<QComboBox *>(control)->currentIndex());
break;
case DataType::Reference: {
auto *combo = qobject_cast<QComboBox *>(control);
const int index = combo->currentIndex();
item->setValueReference(field.index, index >= 0 ? combo->currentData().value<Item *>() : nullptr);
break;
}
default:
throw std::invalid_argument(("Unsupported field value data type " + dataTypeStr(field.dataType)).toStdString());
}
}
}
void FormItem::updateInterface()
{
const ItemFields fields = m_item->getFields();
for (int i = 0; i < fields.count(); ++i) {
const ItemField &field = fields.at(i);
bool visible = field.visibleIfIndex <= 0;
if (field.visibleIfIndex > 0) {
const ItemField &controlField = fields.at(field.visibleIfIndex);
if (controlField.dataType == DataType::Enumeration)
visible = qobject_cast<QComboBox *>(m_dataControls.at(field.visibleIfIndex))->currentIndex() > 0;
}
m_dataControls.at(i)->setVisible(visible);
m_dataLabels.at(i)->setVisible(visible);
}
}
void FormItem::onControlChanged()
{
updateInterface();
}
void FormItem::onOkClicked()
{
saveData(m_item);
accept();
}
} // namespace Cevo
+63
View File
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FormItem</class>
<widget class="QDialog" name="FormItem">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>480</width>
<height>380</height>
</rect>
</property>
<property name="windowTitle">
<string>Item</string>
</property>
<layout class="QVBoxLayout" name="mainLayout">
<item>
<widget class="QScrollArea" name="scrollBox1">
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollBoxContents">
<layout class="QFormLayout" name="fieldsLayout"/>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="buttonLayout">
<item>
<spacer name="buttonSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="buttonOk">
<property name="text">
<string>OK</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonCancel">
<property name="text">
<string>Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonCancel</sender>
<signal>clicked()</signal>
<receiver>FormItem</receiver>
<slot>reject()</slot>
</connection>
</connections>
</ui>
+306
View File
@@ -0,0 +1,306 @@
#include "Cevo/FormJobProgress.h"
#include "Cevo/Threading.h"
#include "ui_FormJobProgress.h"
#include <QCloseEvent>
#include <QCoreApplication>
#include <QListWidgetItem>
#include <QStyle>
#include <QTimer>
#include <algorithm>
namespace Cevo {
namespace {
constexpr int UpdateIntervalMs = 100;
constexpr int EstimatedTimeShowThreshold = 4;
constexpr int EstimatedTimeShowThresholdTotal = 1;
QString formatDuration(qint64 milliseconds)
{
if (milliseconds < 0)
milliseconds = 0;
const qint64 totalSeconds = milliseconds / 1000;
return QStringLiteral("%1:%2:%3")
.arg(totalSeconds / 3600, 2, 10, QLatin1Char('0'))
.arg((totalSeconds % 3600) / 60, 2, 10, QLatin1Char('0'))
.arg(totalSeconds % 60, 2, 10, QLatin1Char('0'));
}
} // namespace
void JobProgress::setMax(int value)
{
m_max = std::max(value, 1);
if (m_value >= m_max)
m_value = m_max;
emit changed();
}
void JobProgress::setText(const QString &text)
{
if (m_text == text)
return;
m_text = text;
emit changed();
}
void JobProgress::setValue(int value)
{
if (value < m_max && value != m_value) {
m_value = value;
emit changed();
}
}
void JobProgress::increment()
{
setValue(m_value + 1);
}
void JobProgress::reset()
{
// Matches the original: silent, does not emit changed().
m_value = 0;
}
Job::Job(FormJobProgress *owner) : m_owner(owner)
{
}
void Job::addLogItem(const QString &text)
{
synchronizeToMainThread([this, text] { m_owner->appendLog(text); });
}
FormJobProgress::FormJobProgress(QWidget *parent) : FormBase(parent), ui(new Ui::FormJobProgress)
{
ui->setupUi(this);
m_updateTimer = new QTimer(this);
connect(m_updateTimer, &QTimer::timeout, this, &FormJobProgress::onTimerUpdate);
reloadJobList();
}
FormJobProgress::~FormJobProgress()
{
delete ui;
}
Job *FormJobProgress::addJob(const QString &title, std::function<void(Job &)> method, bool noThreaded,
bool waitFor)
{
auto job = std::make_unique<Job>(this);
job->title = title;
job->method = std::move(method);
job->noThreaded = noThreaded;
job->waitFor = waitFor;
job->progress.setMax(100);
job->progress.reset();
Job *raw = job.get();
connect(&raw->progress, &JobProgress::changed, this, [this, raw] {
if (raw == m_currentJob)
updateProgress();
});
m_jobs.push_back(std::move(job));
reloadJobList();
return raw;
}
void FormJobProgress::clear()
{
m_jobs.clear();
m_log.clear();
m_currentJob = nullptr;
m_currentJobIndex = -1;
reloadJobList();
}
void FormJobProgress::start()
{
m_terminateRequested = false;
m_finished = false;
setWindowTitle(tr("Please wait..."));
m_log.clear();
ui->memoLog->clear();
ui->labelText->clear();
ui->labelEstimatedTimePart->setVisible(false);
ui->labelEstimatedTimeTotal->setVisible(false);
m_currentJob = nullptr;
m_currentJobIndex = -1;
if (m_showDelay == 0) {
m_updateTimer->start(UpdateIntervalMs);
onTimerUpdate();
} else {
m_updateTimer->start(m_showDelay);
}
m_totalStartTime = QDateTime::currentDateTime();
ui->progressBarTotal->setValue(0);
ui->progressBarTotal->setVisible(false);
std::size_t i = 0;
while (i < m_jobs.size()) {
Job *job = m_jobs[i].get();
m_currentJobIndex = static_cast<int>(i);
m_currentJob = job;
job->startTime = QDateTime::currentDateTime();
m_partElapsed.start();
ui->labelEstimatedTimePart->setText(tr("Estimated time:"));
ui->progressBarPart->setValue(0);
ui->progressBarPart->setVisible(false);
reloadJobList();
QCoreApplication::processEvents();
try {
if (job->noThreaded)
job->method(*job);
else
runInThread([job] { job->method(*job); });
} catch (const std::exception &e) {
// An uncaught exception on a worker QThread would otherwise
// terminate the whole process - caught here and treated like
// the original's Terminate-and-stop-iterating path (disclosed
// safety fix, not just a literal port of the Pascal try/except).
job->resultString = QString::fromUtf8(e.what());
job->addLogItem(job->resultString);
m_terminateRequested = true;
}
ui->progressBarPart->hide();
emit jobFinished(job);
if (m_terminateRequested)
break;
job->endTime = QDateTime::currentDateTime();
job->finished = true;
++i;
}
m_currentJob = nullptr;
m_updateTimer->stop();
ui->memoLog->setPlainText(m_log.join(QLatin1Char('\n')));
if (m_log.isEmpty() && m_autoClose)
hide();
if (!isVisible())
clear();
setWindowTitle(tr("Finished"));
m_finished = true;
m_currentJobIndex = -1;
reloadJobList();
}
void FormJobProgress::stop()
{
m_terminateRequested = true;
for (const auto &job : m_jobs)
job->requestTerminate();
}
void FormJobProgress::closeEvent(QCloseEvent *event)
{
if (m_finished) {
event->accept();
} else {
event->ignore();
stop();
setWindowTitle(tr("Please wait...") + tr("Termination"));
}
}
void FormJobProgress::onTimerUpdate()
{
updateProgress();
if (!isVisible()) {
m_updateTimer->setInterval(UpdateIntervalMs);
show();
}
}
void FormJobProgress::reloadJobList()
{
ui->listViewJobs->clear();
for (int i = 0; i < static_cast<int>(m_jobs.size()); ++i) {
Job *job = m_jobs[static_cast<std::size_t>(i)].get();
auto *item = new QListWidgetItem(job->title, ui->listViewJobs);
if (i == m_currentJobIndex)
item->setIcon(style()->standardIcon(QStyle::SP_ArrowRight));
else if (job->finished)
item->setIcon(style()->standardIcon(QStyle::SP_DialogApplyButton));
}
updateHeight();
}
void FormJobProgress::updateProgress()
{
if (!m_currentJob)
return;
Job &job = *m_currentJob;
ui->progressBarPart->setMaximum(job.progress.max());
ui->progressBarPart->setValue(job.progress.value());
ui->labelText->setText(job.progress.text());
if (job.progress.value() > 0)
ui->progressBarPart->setVisible(true);
qint64 estimatedPartMs = 0;
if (job.progress.value() >= EstimatedTimeShowThreshold) {
estimatedPartMs = m_partElapsed.elapsed() * (job.progress.max() - job.progress.value()) / job.progress.value();
ui->labelEstimatedTimePart->setText(tr("Estimated time: %1").arg(formatDuration(estimatedPartMs)));
ui->labelEstimatedTimePart->setVisible(true);
}
const int totalMax = static_cast<int>(m_jobs.size()) * 100;
const int totalValue = m_currentJobIndex * 100 +
(job.progress.max() > 0 ? (job.progress.value() * 100 / job.progress.max()) : 0);
ui->progressBarTotal->setMaximum(totalMax);
ui->progressBarTotal->setValue(totalValue);
if (totalValue >= EstimatedTimeShowThresholdTotal) {
const qint64 elapsedTotalMs = m_totalStartTime.msecsTo(QDateTime::currentDateTime());
const qint64 remainingMs = estimatedPartMs +
(elapsedTotalMs + estimatedPartMs) * ((static_cast<int>(m_jobs.size()) - 1 - m_currentJobIndex) * 100) /
std::max(1, (m_currentJobIndex + 1) * 100);
if (remainingMs > 0) {
ui->labelEstimatedTimeTotal->setText(tr("Total estimated time: %1").arg(formatDuration(remainingMs)));
ui->labelEstimatedTimeTotal->setVisible(true);
} else {
ui->labelEstimatedTimeTotal->setVisible(false);
}
}
updateHeight();
}
void FormJobProgress::updateHeight()
{
// Unlike the original's manual pixel-math UpdateHeight(), this just
// toggles widget visibility and lets Qt's own layout system (QVBoxLayout
// skips hidden widgets automatically) + adjustSize() compute the actual
// dialog size - a disclosed simplification, not a literal port.
const bool hasJobs = !m_jobs.empty();
ui->labelOperation->setVisible(hasJobs);
ui->listViewJobs->setVisible(hasJobs);
const bool running = hasJobs && !m_finished;
ui->labelEstimatedTimePart->setVisible(running && ui->labelEstimatedTimePart->isVisible());
ui->progressBarPart->setVisible(running && ui->progressBarPart->isVisible());
const bool runningMultiple = running && m_jobs.size() > 1;
ui->labelEstimatedTimeTotal->setVisible(runningMultiple && ui->labelEstimatedTimeTotal->isVisible());
ui->progressBarTotal->setVisible(runningMultiple);
ui->labelText->setVisible(!ui->labelText->text().isEmpty());
ui->memoLog->setVisible(!m_log.isEmpty());
adjustSize();
}
void FormJobProgress::appendLog(const QString &text)
{
m_log.append(text);
ui->memoLog->appendPlainText(text);
updateHeight();
}
} // namespace Cevo
+73
View File
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FormJobProgress</class>
<widget class="QDialog" name="FormJobProgress">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>540</width>
<height>345</height>
</rect>
</property>
<property name="windowTitle">
<string>Please wait...</string>
</property>
<layout class="QVBoxLayout" name="mainLayout">
<item>
<widget class="QLabel" name="labelOperation">
<property name="text">
<string>Operations:</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelText">
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="QListWidget" name="listViewJobs"/>
</item>
<item>
<widget class="QLabel" name="labelEstimatedTimePart">
<property name="text">
<string>Estimated time:</string>
</property>
</widget>
</item>
<item>
<widget class="QProgressBar" name="progressBarPart">
<property name="value">
<number>0</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelEstimatedTimeTotal">
<property name="text">
<string>Total estimated time:</string>
</property>
</widget>
</item>
<item>
<widget class="QProgressBar" name="progressBarTotal">
<property name="value">
<number>0</number>
</property>
</widget>
</item>
<item>
<widget class="QPlainTextEdit" name="memoLog">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
+65
View File
@@ -0,0 +1,65 @@
#include "Cevo/FormKeyShortcuts.h"
#include "ui_FormKeyShortcuts.h"
#include <QAction>
#include <QMenu>
#include <QWidget>
namespace Cevo {
FormKeyShortcuts::FormKeyShortcuts(QWidget *parent) : FormBase(parent), ui(new Ui::FormKeyShortcuts)
{
ui->setupUi(this);
connect(ui->listView1, &QTreeWidget::itemDoubleClicked, this, &FormKeyShortcuts::onExecuteSelected);
connect(ui->listView1, &QTreeWidget::customContextMenuRequested, this, [this](const QPoint &pos) {
QMenu menu(this);
menu.addAction(tr("Execute"), this, &FormKeyShortcuts::onExecuteSelected)
->setEnabled(ui->listView1->currentItem() != nullptr);
menu.exec(ui->listView1->viewport()->mapToGlobal(pos));
});
}
FormKeyShortcuts::~FormKeyShortcuts()
{
delete ui;
}
void FormKeyShortcuts::showEvent(QShowEvent *event)
{
FormBase::showEvent(event);
reload();
}
void FormKeyShortcuts::reload()
{
ui->listView1->clear();
for (QObject *source : std::as_const(m_sourceObjects)) {
const QList<QAction *> actions = source->findChildren<QAction *>(QString(), Qt::FindChildrenRecursively);
for (QAction *action : actions) {
auto *row = new QTreeWidgetItem(ui->listView1);
row->setText(0, action->text().remove('&'));
QWidget *owner = qobject_cast<QWidget *>(action->parent());
while (owner && owner->objectName().isEmpty() && owner->parentWidget())
owner = owner->parentWidget();
if (owner == m_mainWindow)
row->setText(1, tr("Main window"));
else if (owner)
row->setText(1, !owner->windowTitle().isEmpty() ? owner->windowTitle() : owner->objectName());
else
row->setText(1, tr("Global"));
row->setText(2, action->shortcut().toString(QKeySequence::NativeText));
row->setData(0, Qt::UserRole, QVariant::fromValue(static_cast<void *>(action)));
}
}
}
void FormKeyShortcuts::onExecuteSelected()
{
QTreeWidgetItem *selected = ui->listView1->currentItem();
if (!selected)
return;
auto *action = static_cast<QAction *>(selected->data(0, Qt::UserRole).value<void *>());
action->trigger();
}
} // namespace Cevo
+74
View File
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FormKeyShortcuts</class>
<widget class="QDialog" name="FormKeyShortcuts">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>640</width>
<height>360</height>
</rect>
</property>
<property name="windowTitle">
<string>Key shortcuts</string>
</property>
<layout class="QVBoxLayout" name="mainLayout">
<item>
<widget class="QTreeWidget" name="listView1">
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<column>
<property name="text">
<string>Action</string>
</property>
</column>
<column>
<property name="text">
<string>Window</string>
</property>
</column>
<column>
<property name="text">
<string>Shortcut</string>
</property>
</column>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="buttonLayout">
<item>
<spacer name="buttonSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="buttonClose">
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonClose</sender>
<signal>clicked()</signal>
<receiver>FormKeyShortcuts</receiver>
<slot>accept()</slot>
</connection>
</connections>
</ui>
+188
View File
@@ -0,0 +1,188 @@
#include "Cevo/FormList.h"
#include "Cevo/FormItem.h"
#include "ui_FormList.h"
#include <QAction>
#include <QMenu>
#include <QMessageBox>
#include <QShortcut>
namespace Cevo {
FormList::FormList(QWidget *parent) : FormBase(parent), ui(new Ui::FormList)
{
ui->setupUi(this);
m_actionAdd = ui->toolBar1->addAction(tr("Add"), this, &FormList::onAdd);
m_actionAdd->setShortcut(QKeySequence::New);
m_actionModify = ui->toolBar1->addAction(tr("Modify"), this, &FormList::onModify);
m_actionModify->setShortcut(Qt::Key_Return);
m_actionRemove = ui->toolBar1->addAction(tr("Remove"), this, &FormList::onRemove);
m_actionRemove->setShortcut(QKeySequence::Delete);
m_actionClone = ui->toolBar1->addAction(tr("Clone"), this, &FormList::onClone);
auto *selectAll = new QAction(tr("Select all"), this);
selectAll->setShortcut(QKeySequence::SelectAll);
connect(selectAll, &QAction::triggered, this, &FormList::onSelectAll);
addAction(selectAll);
for (QAction *action : { m_actionAdd, m_actionModify, m_actionRemove, m_actionClone })
addAction(action); // also reachable via shortcut when the toolbar isn't focused
connect(ui->listView1, &QTreeWidget::itemDoubleClicked, this, &FormList::onModify);
connect(ui->listView1, &QTreeWidget::itemSelectionChanged, this, &FormList::onSelectionChanged);
connect(ui->listView1, &QTreeWidget::customContextMenuRequested, this, [this](const QPoint &pos) {
QMenu menu(this);
menu.addActions(ui->toolBar1->actions());
menu.exec(ui->listView1->viewport()->mapToGlobal(pos));
});
updateInterface();
}
FormList::~FormList()
{
delete ui;
}
void FormList::setList(BaseItemList *value)
{
if (m_list == value)
return;
m_list = value;
updateInterface();
updateList();
}
void FormList::showEvent(QShowEvent *event)
{
FormBase::showEvent(event);
updateColumns();
updateList();
updateInterface();
}
void FormList::updateColumns()
{
if (!m_list) {
ui->listView1->setColumnCount(0);
return;
}
const ItemFields fields = m_list->getItemFields();
ui->listView1->setColumnCount(fields.count());
for (int i = 0; i < fields.count(); ++i)
ui->listView1->headerItem()->setText(i, fields.at(i).name);
}
void FormList::updateList()
{
ui->listView1->clear();
if (!m_list)
return;
const ItemFields fields = m_list->getItemFields();
for (int i = 0; i < m_list->count(); ++i) {
Item *item = m_list->at(i);
auto *row = new QTreeWidgetItem(ui->listView1);
for (int j = 0; j < fields.count(); ++j) {
const ItemField &field = fields.at(j);
if (field.dataType == DataType::Color)
row->setBackground(j, item->getValueColor(field.index));
else
row->setText(j, item->getValueAsText(field.index));
}
row->setData(0, Qt::UserRole, QVariant::fromValue(item));
}
}
void FormList::updateInterface()
{
const QList<QTreeWidgetItem *> selected = ui->listView1->selectedItems();
const int selCount = selected.count();
const bool atCapacity = maxItemCount != -1 && m_list && m_list->count() >= maxItemCount;
m_actionRemove->setEnabled(m_list && !selected.isEmpty() && m_list->count() - selCount >= minItemCount);
m_actionModify->setEnabled(m_list && !selected.isEmpty());
m_actionAdd->setEnabled(m_list && !atCapacity);
m_actionClone->setEnabled(m_list && !atCapacity);
}
void FormList::onAdd()
{
if (!m_list || (maxItemCount != -1 && m_list->count() >= maxItemCount))
return;
Item *tempItem = m_list->createItem(m_list->getNextAvailableName(m_list->name()));
FormItem dialog(this);
dialog.setItem(tempItem);
if (dialog.exec() == QDialog::Accepted) {
m_list->add(tempItem);
updateList();
updateInterface();
} else {
delete tempItem;
}
}
void FormList::onModify()
{
QTreeWidgetItem *selected = ui->listView1->currentItem();
if (!selected)
return;
auto *item = static_cast<Item *>(selected->data(0, Qt::UserRole).value<Item *>());
Item *tempItem = m_list->createItem();
tempItem->assign(*item);
FormItem dialog(this);
dialog.setItem(tempItem);
if (dialog.exec() == QDialog::Accepted) {
item->assign(*tempItem);
updateList();
updateInterface();
}
delete tempItem;
}
void FormList::onClone()
{
QTreeWidgetItem *selected = ui->listView1->currentItem();
if (!selected || (maxItemCount != -1 && m_list->count() >= maxItemCount))
return;
auto *sourceItem = static_cast<Item *>(selected->data(0, Qt::UserRole).value<Item *>());
Item *tempItem = m_list->createItem();
tempItem->assign(*sourceItem);
tempItem->name = m_list->getNextAvailableName(tempItem->name);
FormItem dialog(this);
dialog.setItem(tempItem);
if (dialog.exec() == QDialog::Accepted) {
m_list->add(tempItem);
updateList();
updateInterface();
} else {
delete tempItem;
}
}
void FormList::onRemove()
{
const QList<QTreeWidgetItem *> selected = ui->listView1->selectedItems();
if (selected.isEmpty())
return;
if (QMessageBox::question(this, tr("Remove items"), tr("Do you want to remove selected items?")) !=
QMessageBox::Yes)
return;
for (QTreeWidgetItem *row : selected) {
if (m_list->count() <= minItemCount)
break;
m_list->remove(row->data(0, Qt::UserRole).value<Item *>());
}
updateList();
updateInterface();
}
void FormList::onSelectAll()
{
ui->listView1->selectAll();
}
void FormList::onSelectionChanged()
{
updateInterface();
}
} // namespace Cevo
+41
View File
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FormList</class>
<widget class="QDialog" name="FormList">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>List</string>
</property>
<layout class="QVBoxLayout" name="mainLayout">
<item>
<widget class="QTreeWidget" name="listView1">
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<column>
<property name="text">
<string>Name</string>
</property>
</column>
</widget>
</item>
<item>
<widget class="QToolBar" name="toolBar1"/>
</item>
</layout>
</widget>
<resources/>
</ui>
+36
View File
@@ -0,0 +1,36 @@
#include "Cevo/FormTest.h"
#include "ui_FormTest.h"
namespace Cevo {
FormTest::FormTest(QWidget *parent) : FormBase(parent), ui(new Ui::FormTest)
{
ui->setupUi(this);
connect(ui->buttonRun, &QPushButton::clicked, this, &FormTest::onRunClicked);
// Matches the original .lfm: ButtonClose's OnClick is also wired to the
// run handler (so closing re-runs the test first) - kept as-is even
// though it looks like it may have been unintentional in the source.
connect(ui->buttonClose, &QPushButton::clicked, this, &FormTest::onRunClicked);
}
FormTest::~FormTest()
{
delete ui;
}
void FormTest::showEvent(QShowEvent *event)
{
FormBase::showEvent(event);
if (m_testCase)
ui->memoLog->setPlainText(m_testCase->log);
}
void FormTest::onRunClicked()
{
if (m_testCase) {
m_testCase->run();
ui->memoLog->setPlainText(m_testCase->log);
}
}
} // namespace Cevo
+60
View File
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FormTest</class>
<widget class="QDialog" name="FormTest">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>640</width>
<height>420</height>
</rect>
</property>
<property name="windowTitle">
<string>Test</string>
</property>
<layout class="QVBoxLayout" name="mainLayout">
<item>
<widget class="QPlainTextEdit" name="memoLog">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="buttonLayout">
<item>
<spacer name="buttonSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="buttonRun">
<property name="text">
<string>Run</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonClose">
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonClose</sender>
<signal>clicked()</signal>
<receiver>FormTest</receiver>
<slot>accept()</slot>
</connection>
</connections>
</ui>
+134
View File
@@ -0,0 +1,134 @@
#include "Cevo/FormTests.h"
#include "Cevo/FormTest.h"
#include "ui_FormTests.h"
#include <QMenu>
namespace Cevo {
namespace {
TestCase *selectedTestCase(QTreeWidget *tree)
{
QTreeWidgetItem *item = tree->currentItem();
if (!item)
return nullptr;
return static_cast<TestCase *>(item->data(0, Qt::UserRole).value<void *>());
}
} // namespace
FormTests::FormTests(QWidget *parent) : FormBase(parent), ui(new Ui::FormTests)
{
ui->setupUi(this);
connect(ui->buttonRun, &QPushButton::clicked, this, &FormTests::onRunClicked);
// Matches the original .lfm's ButtonClose OnClick=ButtonRunClick quirk.
connect(ui->buttonClose, &QPushButton::clicked, this, &FormTests::onRunClicked);
connect(ui->listViewTestCases, &QTreeWidget::itemSelectionChanged, this, &FormTests::onSelectionChanged);
connect(ui->listViewTestCases, &QTreeWidget::itemDoubleClicked, this, &FormTests::onShowSelected);
connect(ui->listViewTestCases, &QTreeWidget::customContextMenuRequested, this, [this](const QPoint &pos) {
QMenu menu(this);
QAction *show = menu.addAction(tr("Show"), this, &FormTests::onShowSelected);
QAction *run = menu.addAction(tr("Run"), this, &FormTests::onRunSelected);
const bool hasSelection = ui->listViewTestCases->currentItem() != nullptr;
show->setEnabled(hasSelection);
run->setEnabled(hasSelection);
menu.exec(ui->listViewTestCases->viewport()->mapToGlobal(pos));
});
}
FormTests::~FormTests()
{
delete ui;
}
void FormTests::setTestCases(TestCases *value)
{
if (m_testCases == value)
return;
m_testCases = value;
reloadList();
updateInterface();
}
void FormTests::showEvent(QShowEvent *event)
{
FormBase::showEvent(event);
reloadList();
updateInterface();
}
void FormTests::reloadList()
{
ui->listViewTestCases->clear();
if (!m_testCases)
return;
for (int i = 0; i < m_testCases->count(); ++i) {
TestCase *testCase = m_testCases->at(i);
auto *item = new QTreeWidgetItem(ui->listViewTestCases);
item->setText(0, testCase->name);
item->setText(1, testResultText(testCase->testResult));
item->setData(0, Qt::UserRole, QVariant::fromValue(static_cast<void *>(testCase)));
}
}
void FormTests::updateInterface()
{
const bool selected = ui->listViewTestCases->currentItem() != nullptr;
ui->buttonRun->setEnabled(m_testCases != nullptr);
Q_UNUSED(selected);
int passed = 0, failed = 0;
if (m_testCases) {
for (int i = 0; i < m_testCases->count(); ++i) {
switch (m_testCases->at(i)->testResult) {
case TestResult::Passed:
++passed;
break;
case TestResult::Failed:
++failed;
break;
default:
break;
}
}
}
ui->labelResult->setText(tr("Passed") + ' ' + QString::number(passed) + ", " + tr("Failed") + ' ' +
QString::number(failed));
}
void FormTests::onRunClicked()
{
if (!m_testCases)
return;
for (int i = 0; i < m_testCases->count(); ++i)
m_testCases->at(i)->run();
reloadList();
updateInterface();
}
void FormTests::onSelectionChanged()
{
updateInterface();
}
void FormTests::onShowSelected()
{
TestCase *testCase = selectedTestCase(ui->listViewTestCases);
if (!testCase)
return;
FormTest dialog(this);
dialog.setTestCase(testCase);
dialog.exec();
reloadList();
}
void FormTests::onRunSelected()
{
TestCase *testCase = selectedTestCase(ui->listViewTestCases);
if (!testCase)
return;
testCase->run();
reloadList();
updateInterface();
}
} // namespace Cevo
+80
View File
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FormTests</class>
<widget class="QDialog" name="FormTests">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>480</height>
</rect>
</property>
<property name="windowTitle">
<string>Tests</string>
</property>
<layout class="QVBoxLayout" name="mainLayout">
<item>
<widget class="QTreeWidget" name="listViewTestCases">
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<column>
<property name="text">
<string>Name</string>
</property>
</column>
<column>
<property name="text">
<string>Result</string>
</property>
</column>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="buttonLayout">
<item>
<widget class="QLabel" name="labelResult">
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<spacer name="buttonSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="buttonRun">
<property name="text">
<string>Run</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonClose">
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonClose</sender>
<signal>clicked()</signal>
<receiver>FormTests</receiver>
<slot>accept()</slot>
</connection>
</connections>
</ui>
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include <QDate>
#include <QPixmap>
#include <QString>
namespace Cevo {
// Equivalent of ApplicationInfo.pas's TApplicationInfo, trimmed to the
// fields actually used by the ported dialogs (FormAbout): no registry-key
// persistence (Windows-only in the original, out of scope here).
struct ApplicationInfo {
QString appName;
int versionMajor = 1;
int versionMinor = 0;
int versionBugFix = 0;
QString versionSuffix; // alpha, beta, RC1, RC2, ...
QString authorsName;
QString emailContact;
QString companyName;
QString companyHomePage;
QString homePage;
QString description;
QDate releaseDate;
QString license;
QPixmap icon;
QString version() const
{
QString result = QString::number(versionMajor) + '.' + QString::number(versionMinor);
if (!versionSuffix.isEmpty())
result += ' ' + versionSuffix;
else
result += '.' + QString::number(versionBugFix);
return result;
}
};
} // namespace Cevo
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <QColor>
#include <QPushButton>
namespace Cevo {
// Minimal equivalent of Lazarus's TColorBox for editing a single color
// value (used by FormItem for dtColor fields): shows the current color as
// a flat swatch, opens a QColorDialog on click.
class ColorButton : public QPushButton {
Q_OBJECT
public:
explicit ColorButton(QWidget *parent = nullptr);
QColor color() const { return m_color; }
void setColor(const QColor &color);
signals:
void colorChanged(const QColor &color);
private slots:
void pickColor();
private:
void updateSwatch();
QColor m_color = Qt::white;
};
} // namespace Cevo
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <QObject>
#include <QString>
namespace Cevo {
// Equivalent of DataFile.pas's TDataFile: a base for serializable data
// objects (subclasses implement the actual load/save logic).
class DataFile : public QObject {
Q_OBJECT
public:
explicit DataFile(QObject *parent = nullptr);
virtual QString fileExt() const { return QStringLiteral(".dat"); }
// Equivalent of GetFileName: a human-readable type name (used to build
// the default file name), NOT the stored path - see fileName()/setFileName().
virtual QString fileTypeName() const;
virtual QString fileFilter() const;
virtual void assign(const DataFile &source);
virtual void loadFromFile(const QString &newFileName);
virtual void saveToFile(const QString &newFileName);
QString fileName() const { return m_fileName; }
void setFileName(const QString &value) { m_fileName = value; }
bool modified() const { return m_modified; }
void setModified(bool value);
signals:
void modifiedChanged();
private:
QString m_fileName;
bool m_modified = false;
};
} // namespace Cevo
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <QDateTime>
#include <QList>
#include <QMutex>
#include <QObject>
#include <QString>
namespace Cevo {
struct DebugLogItem {
QDateTime time;
QString group;
QString text;
};
// Equivalent of DebugLog.pas's TDebugLog: a thread-safe, capped, optionally
// file-backed log.
class DebugLog : public QObject {
Q_OBJECT
public:
explicit DebugLog(QObject *parent = nullptr);
void add(QString text, QString group = QString());
void writeToFile(QString text) const;
QList<DebugLogItem> items() const;
int maxCount() const { return m_maxCount; }
void setMaxCount(int value);
QString fileName = QStringLiteral("DebugLog.txt");
bool writeToFileEnable = false;
signals:
void newItem(const DebugLogItem &item);
private:
mutable QMutex m_lock;
QList<DebugLogItem> m_items;
int m_maxCount = 100;
};
} // namespace Cevo
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <QDateTime>
namespace Cevo {
// Equivalent of Common.Delay.pas's TDelay: a simple one-shot countdown.
class Delay {
public:
void start();
void stop();
bool isEnabled() const { return m_enabled; }
// NOTE: matches the original's TDelay.SetEnabled, which ignores its
// argument and always enables - kept as-is (transcribed literally).
void setEnabled(bool value);
bool isOverflowed() const;
bool isRunning() const;
int durationMs = 1000;
private:
QDateTime m_startTime;
bool m_enabled = false;
};
} // namespace Cevo
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include <QDialog>
namespace Cevo {
// Base for all ported Common/Forms dialogs (equivalent of FormEx.pas's
// TFormEx). Deliberately a thin stub for now: the original bundles
// persistent window geometry, theming, translation and DPI-scaling as
// cross-cutting base-class behavior (PersistentForm/ThemeManager/
// Translator/ScaleDPI) - none of that is implemented here yet, this is just
// the extension point to plug it into later without having to touch every
// derived dialog again.
class FormBase : public QDialog {
Q_OBJECT
public:
explicit FormBase(QWidget *parent = nullptr);
};
} // namespace Cevo
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <QPoint>
#include <QRect>
#include <QVector>
namespace Cevo {
// Equivalent of Geometric.pas. AddPoint/SubPoint/ComparePoint/RectEquals
// are NOT ported: QPoint/QRect already provide operator+/-/== directly.
struct Vector {
QPoint position;
QPoint direction;
double length() const;
double angle() const;
void setLength(double value);
static Vector create(QPoint p1, QPoint p2);
};
int distance(QPoint p1, QPoint p2);
double dot(QPoint p1, QPoint p2);
// Minimum distance between line segment vw and point p; intersect receives
// the closest point on the segment.
int pointToLineDistance(QPoint p, QPoint v, QPoint w, QPoint &intersect);
QPoint rotatePoint(QPoint center, QPoint p, double angle);
QVector<QPoint> rotatePoints(QPoint center, const QVector<QPoint> &points, double angle);
bool lineIntersect(QPoint lineAP1, QPoint lineAP2, QPoint lineBP1, QPoint lineBP2, QPoint &intersection);
double arcTan2Point(QPoint point);
double arcTanPoint(QPoint point);
QRect rectEnlarge(QRect rect, int value);
QRect shiftRect(QRect rect, QPoint delta);
} // namespace Cevo
+193
View File
@@ -0,0 +1,193 @@
#pragma once
#include <QColor>
#include <QMetaType>
#include <QString>
#include <QStringList>
#include <QVariant>
#include <QVector>
#include <algorithm>
#include <type_traits>
namespace Cevo {
// Equivalent of ItemList.pas's TDataType.
enum class DataType { None, String, Boolean, Integer, Float, Color, Time, Date, DateTime, Enumeration, Reference };
QString dataTypeStr(DataType dataType);
// Equivalent of ItemList.pas's TItemField (a value type here - the original
// needed a class only because of Object Pascal's TObjectList<T> plumbing).
struct ItemField {
QString sysName;
QString name;
int index = 0;
DataType dataType = DataType::None;
QStringList enumStates;
int visibleIfIndex = 0; // >0: only visible if field[visibleIfIndex]'s enum selection is > 0
};
// Equivalent of ItemList.pas's TItemFields.
class ItemFields : public QVector<ItemField> {
public:
ItemField &addField(int index, const QString &sysName, const QString &name, DataType dataType);
const ItemField *searchByIndex(int index) const;
};
class BaseItemList;
// Equivalent of ItemList.pas's TItem. XML load/save (LoadFromNode/
// SaveToNode in the original) is NOT ported: not used by any of the ported
// Common/Forms dialogs.
class Item {
public:
virtual ~Item() = default;
int id = 0;
QString name;
virtual ItemFields getFields() const; // base: just the "Name" field
const ItemField *getField(int index) const;
virtual QVariant getValue(int index) const;
virtual void setValue(int index, const QVariant &value);
int getValueInt(int index) const { return getValue(index).toInt(); }
QString getValueString(int index) const { return getValue(index).toString(); }
QColor getValueColor(int index) const { return getValue(index).value<QColor>(); }
bool getValueBool(int index) const { return getValue(index).toBool(); }
int getValueEnum(int index) const { return getValue(index).toInt(); }
Item *getValueReference(int index) const { return getValue(index).value<Item *>(); }
QString getValueAsText(int index) const;
void setValueInt(int index, int value) { setValue(index, value); }
void setValueString(int index, const QString &value) { setValue(index, value); }
void setValueColor(int index, const QColor &value) { setValue(index, QVariant::fromValue(value)); }
void setValueBool(int index, bool value) { setValue(index, value); }
void setValueEnum(int index, int value) { setValue(index, value); }
void setValueReference(int index, Item *value) { setValue(index, QVariant::fromValue(value)); }
virtual void assign(const Item &source);
virtual bool compare(const Item &other) const;
virtual QString className() const; // TItem.GetClassName
virtual BaseItemList *getReferenceList(int index) const { Q_UNUSED(index); return nullptr; }
};
// Equivalent of ItemList.pas's TBaseItemList: a type-erased view onto an
// ItemList<T> so UI code (FormItem/FormList) doesn't need to know T. Unlike
// the original (which needed a closure-based adapter because Object Pascal
// generics have no common runtime base), this is just a plain abstract
// interface - ItemList<T> below implements it directly.
class BaseItemList {
public:
virtual ~BaseItemList() = default;
virtual QString name() const = 0;
virtual int count() const = 0;
virtual Item *at(int index) const = 0;
virtual int add(Item *value) = 0; // takes ownership, returns the new index
virtual int remove(Item *value) = 0; // deletes value, returns its former index (-1 if not found)
virtual Item *createItem(const QString &name = QString()) const = 0; // does NOT add to the list
virtual QString getNextAvailableName(const QString &name) const = 0;
virtual ItemFields getItemFields() const = 0;
virtual Item *findById(int id) const = 0;
};
// Equivalent of ItemList.pas's TItemList<T>.
template <typename T>
class ItemList : public BaseItemList {
static_assert(std::is_base_of<Item, T>::value, "T must derive from Cevo::Item");
public:
~ItemList() override { qDeleteAll(m_items); }
QString name() const override { return T().className(); }
int count() const override { return m_items.count(); }
Item *at(int index) const override { return m_items.at(index); }
T *itemAt(int index) const { return m_items.at(index); }
int add(Item *value) override
{
auto *item = static_cast<T *>(value);
item->id = nextId();
m_items.append(item);
return m_items.size() - 1;
}
T *addItem(const QString &itemName = QString())
{
T *item = createTypedItem(itemName);
item->id = nextId();
m_items.append(item);
return item;
}
int remove(Item *value) override
{
const int index = m_items.indexOf(static_cast<T *>(value));
if (index >= 0)
delete m_items.takeAt(index);
return index;
}
T *createTypedItem(const QString &itemName) const
{
T *item = new T();
item->name = itemName;
return item;
}
Item *createItem(const QString &itemName) const override { return createTypedItem(itemName); }
QString getNextAvailableName(const QString &baseName) const override
{
QString candidate = baseName + QStringLiteral(" 1");
while (findByName(candidate))
candidate = incrementName(candidate);
return candidate;
}
ItemFields getItemFields() const override { return T().getFields(); }
Item *findById(int itemId) const override
{
for (T *item : m_items)
if (item->id == itemId)
return item;
return nullptr;
}
T *findByName(const QString &itemName) const
{
for (T *item : m_items)
if (item->name == itemName)
return item;
return nullptr;
}
private:
static QString incrementName(const QString &itemName)
{
const int i = itemName.lastIndexOf(' ');
if (i >= 0) {
bool ok = false;
const int num = itemName.mid(i + 1).toInt(&ok);
if (ok)
return itemName.left(i).trimmed() + ' ' + QString::number(num + 1);
}
return itemName + QStringLiteral(" 2");
}
int nextId()
{
int maxId = 0;
for (T *item : m_items)
maxId = std::max(maxId, item->id);
return maxId + 1;
}
QVector<T *> m_items;
};
} // namespace Cevo
Q_DECLARE_METATYPE(Cevo::Item *)
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <QPainter>
#include <QPicture>
#include <QPointF>
#include <QTransform>
namespace Cevo {
// Equivalent of MetaCanvas.pas's TMetaCanvas (+ its ~15 TCanvasObject
// subclasses): a "recorded, replayable, zoomable/movable" canvas. Backed by
// Qt's own QPicture, which already records and replays arbitrary QPainter
// commands - so drawing uses Qt's native QPainter API (painter()) rather
// than reimplementing a parallel set of Do*/TCanvasXxx wrapper classes.
// zoom()/move() accumulate into a QTransform applied at drawTo() time,
// instead of mutating each recorded primitive's stored geometry in place
// (the original's approach, which loses precision over repeated Zoom
// calls).
//
// Usage: draw via painter(), call finishRecording() once done, then
// zoom()/move()/drawTo() any number of times; reset() clears everything to
// record again.
class MetaCanvas {
public:
MetaCanvas();
QPainter &painter() { return m_painter; }
void finishRecording();
void zoom(double factor);
void move(QPointF delta);
void reset();
// Replays every recorded command onto `target`, with the accumulated
// zoom/move transform applied.
void drawTo(QPainter &target) const;
private:
QPicture m_picture;
QPainter m_painter;
QTransform m_transform;
};
} // namespace Cevo
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <QRect>
#include <QString>
class QWidget;
namespace Cevo {
// Equivalent of PersistentForm.pas's TPersistentForm: window geometry
// persistence across sessions. Re-architected around Qt's native
// QWidget::save/restoreGeometry() + QSettings instead of the original's
// Windows-Registry-based TRect/WindowState bookkeeping - restoreGeometry()
// already clamps off-screen geometry to the current screen layout, which
// covers what CheckEntireVisible/CheckPartVisible did by hand. The
// original's recursive per-control persistence (TListView column widths,
// TPanel docked size) is NOT ported: LCL-specific widget introspection with
// no current consumer. Add a narrower, Qt-idiomatic equivalent (e.g.
// persisting a specific QTreeWidget's column widths) once a concrete form
// actually needs it.
class PersistentForm {
public:
// settingsGroup: QSettings group this form's state is stored under
// (e.g. "Forms/MainWindow") - assumes the application has already set
// QCoreApplication::setOrganizationName()/setApplicationName().
explicit PersistentForm(QString settingsGroup);
void load(QWidget *form, bool defaultMaximized = false, bool defaultFullScreen = false);
void save(QWidget *form) const;
bool isFullScreen() const { return m_fullScreen; }
void setFullScreen(QWidget *form, bool state);
private:
QString m_settingsGroup;
QRect m_restoredGeometry;
bool m_fullScreen = false;
};
} // namespace Cevo
+105
View File
@@ -0,0 +1,105 @@
#pragma once
#include <QMutex>
#include <QVector>
#include <QWaitCondition>
#include <stdexcept>
namespace Cevo {
// Equivalent of Pool.pas's TPool: a simple object pool (Acquire/Release).
// Override newItemObject() to customize item construction. NOT thread-safe
// by itself (matches the original) - see ThreadedPool below for that.
template <typename T>
class Pool {
public:
virtual ~Pool() { setTotalCount(0); }
int totalCount() const { return m_items.size(); }
void setTotalCount(int value)
{
if (value > m_items.size()) {
for (int i = m_items.size(); i < value; ++i) {
T *item = newItemObject();
m_items.append(item);
m_freeItems.append(item);
}
} else {
for (int i = m_items.size() - 1; i >= value; --i) {
T *item = m_items.at(i);
const int freeIndex = m_freeItems.indexOf(item);
if (freeIndex < 0)
throw std::logic_error("Pool: shrinking below a still-acquired item");
m_freeItems.removeAt(freeIndex);
m_items.removeAt(i);
delete item;
}
}
}
int usedCount() const { return m_items.size() - m_freeItems.size(); }
// NOTE: unlike the original (which busy-waits forever if empty, a
// same-thread deadlock risk since nothing else runs to free an item),
// this throws immediately - see ThreadedPool for the genuinely
// multi-threaded blocking-wait behavior.
virtual T *acquire()
{
if (m_freeItems.isEmpty())
throw std::runtime_error("Object pool is empty");
return m_freeItems.takeLast();
}
virtual void release(T *item)
{
if (!m_items.contains(item))
throw std::invalid_argument("Unknown object for release from pool");
m_freeItems.append(item);
}
protected:
virtual T *newItemObject() { return new T(); }
QVector<T *> m_items; // owns all
QVector<T *> m_freeItems; // non-owning subset
};
// Equivalent of Pool.pas's TThreadedPool: acquire() blocks (instead of
// throwing) while the pool has capacity but no free item, waking up once
// another thread calls release() - replaces the original's Sleep(1)
// busy-polling loop with a QWaitCondition.
template <typename T>
class ThreadedPool : public Pool<T> {
public:
int totalCount() const { QMutexLocker locker(&m_lock); return Pool<T>::totalCount(); }
void setTotalCount(int value)
{
QMutexLocker locker(&m_lock);
Pool<T>::setTotalCount(value);
}
int usedCount() const { QMutexLocker locker(&m_lock); return Pool<T>::usedCount(); }
T *acquire() override
{
QMutexLocker locker(&m_lock);
if (Pool<T>::totalCount() == 0)
throw std::runtime_error("Object pool is empty");
while (Pool<T>::m_freeItems.isEmpty())
m_releaseWait.wait(&m_lock);
return Pool<T>::m_freeItems.takeLast();
}
void release(T *item) override
{
QMutexLocker locker(&m_lock);
Pool<T>::release(item);
m_releaseWait.wakeOne();
}
private:
mutable QMutex m_lock;
QWaitCondition m_releaseWait;
};
} // namespace Cevo
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <QString>
#include <array>
namespace Cevo {
struct PrefixMultiplierItem {
QString shortText;
QString fullText;
double value;
};
using PrefixMultiplierDef = std::array<PrefixMultiplierItem, 17>;
extern const PrefixMultiplierDef BasePrefixMultipliers;
extern const PrefixMultiplierDef TimePrefixMultipliers;
double truncateDigits(double value, int digits = 3);
// Formats value scaled to the closest prefix in prefixMultipliers (e.g. "1.2 k" + unitText).
QString formatWithPrefix(double value, const PrefixMultiplierDef &prefixMultipliers, const QString &unitText,
int digits = 3);
} // namespace Cevo
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <QPoint>
#include <QString>
#include <QVector>
namespace Cevo {
// Equivalent of StringTable.pas's TStringTable: a resizable 2D string grid.
class StringTable {
public:
QString cell(int x, int y) const { return m_cells.at(y).at(x); }
void setCell(int x, int y, const QString &value) { m_cells[y][x] = value; }
int colCount() const { return m_size.x(); }
void setColCount(int value) { setSize(QPoint(value, rowCount())); }
int rowCount() const { return m_size.y(); }
void setRowCount(int value) { setSize(QPoint(colCount(), value)); }
QPoint size() const { return m_size; }
void setSize(QPoint value);
private:
QVector<QVector<QString>> m_cells;
QPoint m_size;
};
} // namespace Cevo
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <QMutex>
namespace Cevo {
// Equivalent of SyncCounter.pas's TSyncCounter: a thread-safe counter/ID allocator.
class SyncCounter {
public:
int allocate();
bool currentEqualTo(int value) const;
void increment();
// NOTE: matches the original, which copies Top/Current without locking.
void assign(const SyncCounter &source);
private:
mutable QMutex m_lock;
int m_top = 0;
int m_current = 0;
};
} // namespace Cevo
+59
View File
@@ -0,0 +1,59 @@
#pragma once
#include <QStringList>
#include <memory>
#include <vector>
class QTreeWidget;
namespace Cevo {
// Equivalent of Table.pas's TTableFormat/TTableFormats.
enum class TableFormat { Excel, Plain, Csv, Html, ListView, MediaWiki, Xml, Json };
QString tableFormatText(TableFormat format);
QString tableFormatExt(TableFormat format);
// Equivalent of Table.pas's TRow.
struct Row {
QStringList cells;
void addCell(const QString &text) { cells.append(text); }
};
// Equivalent of Table.pas's TTable: a generic string table with multi-format
// export/import. JSON (QJsonDocument) and XML (QDomDocument) use Qt's own
// parsers/serializers instead of the original's hand-rolled, line-based
// ones (the original's JSON "parser" assumes exactly one "key": "value" per
// line and no nesting; its HTML/JSON output also did not escape cell
// content at all, which is fixed here).
class Table {
public:
QString title;
QStringList columns;
std::vector<std::unique_ptr<Row>> rows;
bool firstRowIsHeader = false;
void clear();
Row &addRow();
QString outputTabs() const;
QString outputPlain() const;
QString outputCsv() const;
QString outputXml() const;
QString outputHtml() const;
QString outputMediaWiki() const;
QString outputJson() const;
void populateTreeWidget(QTreeWidget *tree) const;
QString output(TableFormat format) const;
void setInputCsv(const QString &text);
void setInputMediaWiki(const QString &text);
void setInputJson(const QString &text);
void setInputXml(const QString &text);
void setInput(TableFormat format, const QString &text);
static QList<TableFormat> inputFormats();
};
} // namespace Cevo
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include <QString>
#include <memory>
#include <vector>
namespace Cevo {
enum class TestResult { None, Passed, Failed };
QString testResultText(TestResult result);
// Equivalent of TestCase.pas's TTestCase: a single named test, logging its
// own output and result as it runs.
class TestCase {
public:
virtual ~TestCase() = default;
QString name;
TestResult testResult = TestResult::None;
QString log;
virtual void initialize() { testResult = TestResult::None; }
virtual void run() {}
virtual void finalize() {}
void evaluate(bool passed) { testResult = passed ? TestResult::Passed : TestResult::Failed; }
void pass() { testResult = TestResult::Passed; }
void fail() { testResult = TestResult::Failed; }
};
// Equivalent of TestCase.pas's TTestCases: an owning collection of test
// cases, run in sequence.
class TestCases {
public:
TestCase *addNew(const QString &name, std::unique_ptr<TestCase> testCase);
void run();
int count() const { return static_cast<int>(m_items.size()); }
TestCase *at(int index) const { return m_items.at(static_cast<size_t>(index)).get(); }
private:
std::vector<std::unique_ptr<TestCase>> m_items;
};
} // namespace Cevo
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include <functional>
namespace Cevo {
// Equivalent of Threading.pas's free functions (RunInThread/
// RunInThreadAsync/Synchronize). The TVirtualThread/TListedThread/
// TTermThread/TThreadList class hierarchy is NOT ported: it exists only to
// let a worker thread find "its own" wrapper object (via a global,
// mutex-guarded ThreadList keyed by TThreadID) so Synchronize() can call
// back into it - QThread + Qt::BlockingQueuedConnection already solve this
// natively, with no registry needed.
// Runs `method` on a new thread, blocking the caller until it finishes
// (pumping the Qt event loop meanwhile if called from the main thread).
// Re-throws whatever `method` threw.
void runInThread(const std::function<void()> &method);
// Runs `method` on a new thread without blocking; if given, `callback` runs
// (on that same worker thread) once `method` returns.
void runInThreadAsync(const std::function<void()> &method, const std::function<void()> &callback = {});
// Equivalent of TThread.Synchronize from a worker thread: runs `method` on
// the main/GUI thread, blocking the caller until it completes. Runs
// `method` directly, with no thread hop, if already on the main thread.
void synchronizeToMainThread(const std::function<void()> &method);
} // namespace Cevo
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <QDateTime>
#include <QDomDocument>
#include <QString>
namespace Cevo {
// Equivalent of XML.pas's node read/write helpers (each value is stored as
// a named child element's text content). XMLTimeToDateTime/
// DateTimeToXMLTime (+ their GetTimeZoneBias/LeftCutString helpers) are NOT
// ported: QDateTime already parses/formats ISO 8601 (incl. timezone offset
// and fractional seconds) natively and more robustly than the original's
// hand-rolled parser.
void writeInteger(QDomElement &node, const QString &name, int value);
void writeInt64(QDomElement &node, const QString &name, qint64 value);
void writeBoolean(QDomElement &node, const QString &name, bool value);
void writeString(QDomElement &node, const QString &name, const QString &value);
void writeDateTime(QDomElement &node, const QString &name, const QDateTime &value);
void writeDouble(QDomElement &node, const QString &name, double value);
int readInteger(const QDomElement &node, const QString &name, int defaultValue);
qint64 readInt64(const QDomElement &node, const QString &name, qint64 defaultValue);
bool readBoolean(const QDomElement &node, const QString &name, bool defaultValue);
QString readString(const QDomElement &node, const QString &name, const QString &defaultValue);
QDateTime readDateTime(const QDomElement &node, const QString &name, const QDateTime &defaultValue);
double readDouble(const QDomElement &node, const QString &name, double defaultValue);
// Parses fileName into a QDomDocument; throws std::runtime_error on failure.
QDomDocument readXmlFile(const QString &fileName);
} // namespace Cevo
+34
View File
@@ -0,0 +1,34 @@
#include "Cevo/ColorButton.h"
#include <QColorDialog>
namespace Cevo {
ColorButton::ColorButton(QWidget *parent) : QPushButton(parent)
{
connect(this, &QPushButton::clicked, this, &ColorButton::pickColor);
updateSwatch();
}
void ColorButton::setColor(const QColor &color)
{
if (m_color == color)
return;
m_color = color;
updateSwatch();
emit colorChanged(m_color);
}
void ColorButton::pickColor()
{
const QColor picked = QColorDialog::getColor(m_color, this);
if (picked.isValid())
setColor(picked);
}
void ColorButton::updateSwatch()
{
setStyleSheet(QStringLiteral("background-color: %1;").arg(m_color.name()));
}
} // namespace Cevo
+46
View File
@@ -0,0 +1,46 @@
#include "Cevo/DataFile.h"
namespace Cevo {
DataFile::DataFile(QObject *parent) : QObject(parent)
{
m_fileName = fileTypeName() + fileExt();
}
QString DataFile::fileTypeName() const
{
return tr("Data file");
}
QString DataFile::fileFilter() const
{
return tr("All files") + QStringLiteral("|*.*");
}
void DataFile::assign(const DataFile &source)
{
m_fileName = source.m_fileName;
m_modified = source.m_modified;
}
void DataFile::loadFromFile(const QString &newFileName)
{
setModified(false);
setFileName(newFileName);
}
void DataFile::saveToFile(const QString &newFileName)
{
setModified(false);
setFileName(newFileName);
}
void DataFile::setModified(bool value)
{
if (m_modified == value)
return;
m_modified = value;
emit modifiedChanged();
}
} // namespace Cevo
+69
View File
@@ -0,0 +1,69 @@
#include "Cevo/DebugLog.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QMutexLocker>
#include <QTextStream>
#include <stdexcept>
namespace Cevo {
DebugLog::DebugLog(QObject *parent) : QObject(parent) {}
void DebugLog::setMaxCount(int value)
{
if (m_maxCount == value)
return;
m_maxCount = value;
QMutexLocker locker(&m_lock);
while (m_items.count() > m_maxCount)
m_items.removeLast();
}
void DebugLog::add(QString text, QString group)
{
DebugLogItem item;
item.time = QDateTime::currentDateTime();
item.group = group;
item.text = text;
{
QMutexLocker locker(&m_lock);
m_items.prepend(item);
while (m_items.count() > m_maxCount)
m_items.removeLast();
if (writeToFileEnable) {
// Matches the original literally: Group is folded into itself
// ("Foo" -> "[Foo] "), which looks like it may be an upstream
// copy-paste bug, but is kept as-is (debug-log-only impact).
if (!group.isEmpty())
group = group + '[' + group + QStringLiteral("] ");
writeToFile(group + text);
}
}
emit newItem(item);
}
void DebugLog::writeToFile(QString text) const
{
if (fileName.isEmpty())
throw std::invalid_argument("Filename not defined");
const QFileInfo info(fileName);
if (!info.path().isEmpty())
QDir().mkpath(info.path());
QFile file(fileName);
if (!file.open(QIODevice::Append | QIODevice::Text))
throw std::runtime_error(("Could not open " + fileName).toStdString());
QTextStream stream(&file);
stream << QDateTime::currentDateTime().toString(QStringLiteral("hh:mm:ss.zzz")) << ": " << text << '\n';
}
QList<DebugLogItem> DebugLog::items() const
{
QMutexLocker locker(&m_lock);
return m_items;
}
} // namespace Cevo
+32
View File
@@ -0,0 +1,32 @@
#include "Cevo/Delay.h"
namespace Cevo {
void Delay::start()
{
m_startTime = QDateTime::currentDateTime();
m_enabled = true;
}
void Delay::stop()
{
m_enabled = false;
}
void Delay::setEnabled(bool value)
{
Q_UNUSED(value);
m_enabled = true;
}
bool Delay::isOverflowed() const
{
return m_enabled && m_startTime.msecsTo(QDateTime::currentDateTime()) > durationMs;
}
bool Delay::isRunning() const
{
return m_enabled && m_startTime.msecsTo(QDateTime::currentDateTime()) <= durationMs;
}
} // namespace Cevo
+7
View File
@@ -0,0 +1,7 @@
#include "Cevo/FormBase.h"
namespace Cevo {
FormBase::FormBase(QWidget *parent) : QDialog(parent) {}
} // namespace Cevo
+126
View File
@@ -0,0 +1,126 @@
#include "Cevo/Geometric.h"
#include <cmath>
#include <limits>
namespace Cevo {
int distance(QPoint p1, QPoint p2)
{
const QPoint d = p2 - p1;
return static_cast<int>(std::sqrt(static_cast<double>(d.x() * d.x() + d.y() * d.y())));
}
double dot(QPoint p1, QPoint p2)
{
return static_cast<double>(p1.x()) * p2.x() + static_cast<double>(p1.y()) * p2.y();
}
int pointToLineDistance(QPoint p, QPoint v, QPoint w, QPoint &intersect)
{
// l2 is computed via the truncating integer distance() first (matches
// the original's own precision loss - Distance(V, W) then squared).
double l2 = distance(v, w);
l2 = l2 * l2;
if (l2 == 0) {
intersect = v;
return distance(p, v); // v == w case
}
const double t = dot(p - v, w - v) / l2;
if (t < 0) {
intersect = v; // beyond the 'v' end of the segment
return distance(p, v);
}
if (t > 1) {
intersect = w; // beyond the 'w' end of the segment
return distance(p, w);
}
const QPoint tt(static_cast<int>(v.x() + t * (w.x() - v.x())), static_cast<int>(v.y() + t * (w.y() - v.y())));
intersect = tt;
return distance(p, tt);
}
QPoint rotatePoint(QPoint center, QPoint p, double angle)
{
p -= center;
return QPoint(center.x() + qRound(p.x() * std::cos(angle) - p.y() * std::sin(angle)),
center.y() + qRound(p.x() * std::sin(angle) + p.y() * std::cos(angle)));
}
QVector<QPoint> rotatePoints(QPoint center, const QVector<QPoint> &points, double angle)
{
QVector<QPoint> result;
result.reserve(points.size());
for (const QPoint &p : points)
result.append(rotatePoint(center, p, angle));
return result;
}
bool lineIntersect(QPoint lineAP1, QPoint lineAP2, QPoint lineBP1, QPoint lineBP2, QPoint &intersection)
{
if (lineAP1 == lineAP2 || lineBP1 == lineBP2)
return false;
const double detLineA = static_cast<double>(lineAP1.x()) * lineAP2.y() - static_cast<double>(lineAP1.y()) * lineAP2.x();
const double detLineB = static_cast<double>(lineBP1.x()) * lineBP2.y() - static_cast<double>(lineBP1.y()) * lineBP2.x();
const QPoint diffLA = lineAP1 - lineAP2;
const QPoint diffLB = lineBP1 - lineBP2;
const double d = static_cast<double>(diffLA.x()) * diffLB.y() - static_cast<double>(diffLA.y()) * diffLB.x();
if (d == 0)
return false; // parallel lines without intersection
const double detDivInv = 1 / d;
intersection.setX(static_cast<int>((detLineA * diffLB.x() - diffLA.x() * detLineB) * detDivInv));
intersection.setY(static_cast<int>((detLineA * diffLB.y() - diffLA.y() * detLineB) * detDivInv));
return true;
}
double arcTan2Point(QPoint point)
{
return std::atan2(static_cast<double>(point.y()), static_cast<double>(point.x()));
}
double arcTanPoint(QPoint point)
{
if (point.y() == 0)
return std::numeric_limits<double>::infinity();
return std::atan(static_cast<double>(point.x()) / point.y());
}
QRect rectEnlarge(QRect rect, int value)
{
return QRect(QPoint(rect.left() - value, rect.top() - value), QPoint(rect.right() + value, rect.bottom() + value));
}
QRect shiftRect(QRect rect, QPoint delta)
{
return rect.translated(delta);
}
double Vector::length() const
{
return std::sqrt(static_cast<double>(direction.x() * direction.x() + direction.y() * direction.y()));
}
double Vector::angle() const
{
return arcTan2Point(direction);
}
void Vector::setLength(double value)
{
const double a = angle();
direction = QPoint(qRound(std::cos(a) * value), qRound(std::sin(a) * value));
}
Vector Vector::create(QPoint p1, QPoint p2)
{
Vector v;
v.position = p1;
v.direction = p2 - p1;
return v;
}
} // namespace Cevo
+177
View File
@@ -0,0 +1,177 @@
#include "Cevo/Item.h"
#include <QCoreApplication>
#include <stdexcept>
namespace Cevo {
QString dataTypeStr(DataType dataType)
{
switch (dataType) {
case DataType::None:
return QStringLiteral("None");
case DataType::String:
return QStringLiteral("String");
case DataType::Boolean:
return QStringLiteral("Boolean");
case DataType::Integer:
return QStringLiteral("Integer");
case DataType::Float:
return QStringLiteral("Float");
case DataType::Color:
return QStringLiteral("Color");
case DataType::Time:
return QStringLiteral("Time");
case DataType::Date:
return QStringLiteral("Date");
case DataType::DateTime:
return QStringLiteral("DateTime");
case DataType::Enumeration:
return QStringLiteral("Enumeration");
case DataType::Reference:
return QStringLiteral("Reference");
}
return {};
}
ItemField &ItemFields::addField(int index, const QString &sysName, const QString &name, DataType dataType)
{
ItemField field;
field.index = index;
field.sysName = sysName;
field.name = name;
field.dataType = dataType;
append(field);
return last();
}
const ItemField *ItemFields::searchByIndex(int index) const
{
for (const ItemField &field : *this)
if (field.index == index)
return &field;
return nullptr;
}
ItemFields Item::getFields() const
{
ItemFields fields;
fields.addField(1, QStringLiteral("Name"), QCoreApplication::translate("Item", "Name"), DataType::String);
return fields;
}
const ItemField *Item::getField(int index) const
{
return getFields().searchByIndex(index);
}
QVariant Item::getValue(int index) const
{
throw std::out_of_range(QStringLiteral("Unsupported value index %1").arg(index).toStdString());
}
void Item::setValue(int index, const QVariant &value)
{
Q_UNUSED(value);
throw std::out_of_range(QStringLiteral("Unsupported value index %1").arg(index).toStdString());
}
QString Item::getValueAsText(int index) const
{
const ItemField *field = getField(index);
if (!field)
throw std::invalid_argument("Unknown field index");
switch (field->dataType) {
case DataType::Integer:
return QString::number(getValueInt(index));
case DataType::String:
return getValueString(index);
case DataType::Color:
return {};
case DataType::Enumeration:
return field->enumStates.value(getValueEnum(index));
case DataType::Reference: {
const Item *item = getValueReference(index);
return item ? item->name : QString();
}
case DataType::Boolean:
return getValueBool(index) ? QCoreApplication::translate("Item", "Yes")
: QCoreApplication::translate("Item", "No");
default:
throw std::invalid_argument(("Unsupported field value data type " + dataTypeStr(field->dataType)).toStdString());
}
}
void Item::assign(const Item &source)
{
id = source.id;
const ItemFields fields = getFields();
for (const ItemField &field : fields) {
switch (field.dataType) {
case DataType::String:
setValueString(field.index, source.getValueString(field.index));
break;
case DataType::Color:
setValueColor(field.index, source.getValueColor(field.index));
break;
case DataType::Integer:
setValueInt(field.index, source.getValueInt(field.index));
break;
case DataType::Boolean:
setValueBool(field.index, source.getValueBool(field.index));
break;
case DataType::Enumeration:
setValueEnum(field.index, source.getValueEnum(field.index));
break;
case DataType::Reference:
setValueReference(field.index, source.getValueReference(field.index));
break;
default:
throw std::invalid_argument(
("Unsupported field value data type " + dataTypeStr(field.dataType)).toStdString());
}
}
}
bool Item::compare(const Item &other) const
{
if (id != other.id)
return false;
const ItemFields fields = getFields();
for (const ItemField &field : fields) {
bool equal = true;
switch (field.dataType) {
case DataType::String:
equal = getValueString(field.index) == other.getValueString(field.index);
break;
case DataType::Color:
equal = getValueColor(field.index) == other.getValueColor(field.index);
break;
case DataType::Integer:
equal = getValueInt(field.index) == other.getValueInt(field.index);
break;
case DataType::Boolean:
equal = getValueBool(field.index) == other.getValueBool(field.index);
break;
case DataType::Enumeration:
equal = getValueEnum(field.index) == other.getValueEnum(field.index);
break;
case DataType::Reference:
equal = getValueReference(field.index) == other.getValueReference(field.index);
break;
default:
throw std::invalid_argument(
("Unsupported field value data type " + dataTypeStr(field.dataType)).toStdString());
}
if (!equal)
return false;
}
return true;
}
QString Item::className() const
{
return QCoreApplication::translate("Item", "Item");
}
} // namespace Cevo
+42
View File
@@ -0,0 +1,42 @@
#include "Cevo/MetaCanvas.h"
namespace Cevo {
MetaCanvas::MetaCanvas()
{
m_painter.begin(&m_picture);
}
void MetaCanvas::finishRecording()
{
if (m_painter.isActive())
m_painter.end();
}
void MetaCanvas::zoom(double factor)
{
m_transform.scale(factor, factor);
}
void MetaCanvas::move(QPointF delta)
{
m_transform.translate(delta.x(), delta.y());
}
void MetaCanvas::reset()
{
finishRecording();
m_picture = QPicture();
m_transform = QTransform();
m_painter.begin(&m_picture);
}
void MetaCanvas::drawTo(QPainter &target) const
{
target.save();
target.setTransform(m_transform, true);
target.drawPicture(0, 0, m_picture);
target.restore();
}
} // namespace Cevo
+52
View File
@@ -0,0 +1,52 @@
#include "Cevo/PersistentForm.h"
#include <QSettings>
#include <QWidget>
namespace Cevo {
PersistentForm::PersistentForm(QString settingsGroup) : m_settingsGroup(std::move(settingsGroup)) {}
void PersistentForm::load(QWidget *form, bool defaultMaximized, bool defaultFullScreen)
{
QSettings settings;
settings.beginGroup(m_settingsGroup);
const QByteArray geometry = settings.value(QStringLiteral("geometry")).toByteArray();
if (!geometry.isEmpty())
form->restoreGeometry(geometry);
m_fullScreen = settings.value(QStringLiteral("fullScreen"), defaultFullScreen).toBool();
const bool maximized = settings.value(QStringLiteral("maximized"), defaultMaximized).toBool();
settings.endGroup();
m_restoredGeometry = form->normalGeometry();
if (m_fullScreen)
form->showFullScreen();
else if (maximized)
form->showMaximized();
}
void PersistentForm::save(QWidget *form) const
{
QSettings settings;
settings.beginGroup(m_settingsGroup);
settings.setValue(QStringLiteral("geometry"), form->saveGeometry());
settings.setValue(QStringLiteral("maximized"), form->isMaximized());
settings.setValue(QStringLiteral("fullScreen"), m_fullScreen);
settings.endGroup();
}
void PersistentForm::setFullScreen(QWidget *form, bool state)
{
if (state == m_fullScreen)
return;
m_fullScreen = state;
if (state) {
m_restoredGeometry = form->normalGeometry();
form->showFullScreen();
} else {
form->showNormal();
form->setGeometry(m_restoredGeometry);
}
}
} // namespace Cevo
+80
View File
@@ -0,0 +1,80 @@
#include "Cevo/PrefixMultiplier.h"
#include <cmath>
namespace Cevo {
const PrefixMultiplierDef BasePrefixMultipliers = { {
{ QStringLiteral("y"), QStringLiteral("yocto"), 1e-24 },
{ QStringLiteral("z"), QStringLiteral("zepto"), 1e-21 },
{ QStringLiteral("a"), QStringLiteral("atto"), 1e-18 },
{ QStringLiteral("f"), QStringLiteral("femto"), 1e-15 },
{ QStringLiteral("p"), QStringLiteral("piko"), 1e-12 },
{ QStringLiteral("n"), QStringLiteral("nano"), 1e-9 },
{ QStringLiteral("u"), QStringLiteral("mikro"), 1e-6 },
{ QStringLiteral("m"), QStringLiteral("mili"), 1e-3 },
{ QString(), QString(), 1e0 },
{ QStringLiteral("k"), QStringLiteral("kilo"), 1e3 },
{ QStringLiteral("M"), QStringLiteral("mega"), 1e6 },
{ QStringLiteral("G"), QStringLiteral("giga"), 1e9 },
{ QStringLiteral("T"), QStringLiteral("tera"), 1e12 },
{ QStringLiteral("P"), QStringLiteral("peta"), 1e15 },
{ QStringLiteral("E"), QStringLiteral("exa"), 1e18 },
{ QStringLiteral("Z"), QStringLiteral("zetta"), 1e21 },
{ QStringLiteral("Y"), QStringLiteral("yotta"), 1e24 },
} };
const PrefixMultiplierDef TimePrefixMultipliers = { {
{ QStringLiteral("ys"), QStringLiteral("yocto"), 1e-24 },
{ QStringLiteral("zs"), QStringLiteral("zepto"), 1e-21 },
{ QStringLiteral("as"), QStringLiteral("atto"), 1e-18 },
{ QStringLiteral("fs"), QStringLiteral("femto"), 1e-15 },
{ QStringLiteral("ps"), QStringLiteral("piko"), 1e-12 },
{ QStringLiteral("ns"), QStringLiteral("nano"), 1e-9 },
{ QStringLiteral("us"), QStringLiteral("mikro"), 1e-6 },
{ QStringLiteral("ms"), QStringLiteral("mili"), 1e-3 },
{ QStringLiteral("s"), QStringLiteral("sekunda"), 1 },
{ QStringLiteral("min"), QStringLiteral("minuta"), 60 },
{ QStringLiteral("hod"), QStringLiteral("hodina"), 3600 },
{ QStringLiteral("den"), QStringLiteral("den"), 24 * 3600 },
{ QStringLiteral("t\u00FDd"), QStringLiteral("t\u00FDden"), 7 * 24 * 3600 },
{ QStringLiteral("m\u011Bs"), QStringLiteral("m\u011Bs\u00EDc"), 30 * 24 * 3600 },
{ QStringLiteral("rok"), QStringLiteral("rok"), 365 * 24 * 3600 },
{ QStringLiteral("stolet\u00ED"), QStringLiteral("stolet\u00ED"), 3153600000.0 },
{ QStringLiteral("tis\u00EDcilet\u00ED"), QStringLiteral("tis\u00EDcilet\u00ED"), 3153600000.0 },
} };
double truncateDigits(double value, int digits)
{
for (int ii = 2; ii >= -1; --ii) {
if (value >= std::pow(10.0, ii)) {
const int realDigits = digits < (ii + 1) ? ii + 1 : digits;
const double scale = std::pow(10.0, ii - realDigits + 1);
return std::round(value / scale) * scale;
}
}
return 0;
}
QString formatWithPrefix(double value, const PrefixMultiplierDef &prefixMultipliers, const QString &unitText,
int digits)
{
const int size = static_cast<int>(prefixMultipliers.size());
int i = 8;
if (value == 0) {
// stays at the base-unit entry
} else if (value > 1) {
// bounds check moved before the array access (the original checks
// it after, which can read one element past the end of the array).
while (i + 1 < size && i + 1 >= 0 && (value / prefixMultipliers[i + 1].value) > 1)
++i;
} else {
while (i - 1 >= 0 && i - 1 < size && (value / prefixMultipliers[i - 1].value) < 1)
--i;
++i;
}
value = value / prefixMultipliers[i].value;
return QString::number(truncateDigits(value, digits)) + ' ' + prefixMultipliers[i].shortText + unitText;
}
} // namespace Cevo
+15
View File
@@ -0,0 +1,15 @@
#include "Cevo/StringTable.h"
namespace Cevo {
void StringTable::setSize(QPoint value)
{
if (m_size == value)
return;
m_size = value;
m_cells.resize(m_size.y());
for (QVector<QString> &row : m_cells)
row.resize(m_size.x());
}
} // namespace Cevo
+29
View File
@@ -0,0 +1,29 @@
#include "Cevo/SyncCounter.h"
namespace Cevo {
int SyncCounter::allocate()
{
QMutexLocker locker(&m_lock);
return m_top++;
}
bool SyncCounter::currentEqualTo(int value) const
{
QMutexLocker locker(&m_lock);
return value == m_current;
}
void SyncCounter::increment()
{
QMutexLocker locker(&m_lock);
++m_current;
}
void SyncCounter::assign(const SyncCounter &source)
{
m_current = source.m_current;
m_top = source.m_top;
}
} // namespace Cevo
+428
View File
@@ -0,0 +1,428 @@
#include "Cevo/Table.h"
#include <QDomDocument>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTreeWidget>
#include <algorithm>
#include <stdexcept>
namespace Cevo {
namespace {
QString quoteString(const QString &text, const QString &quote)
{
return text.isEmpty() ? text : quote + text + quote;
}
QString escapeHtml(const QString &text)
{
QString result = text;
result.replace('&', QStringLiteral("&amp;")); // must come first
result.replace('<', QStringLiteral("&lt;"));
result.replace('>', QStringLiteral("&gt;"));
return result;
}
// Parses one CSV line (comma-separated, "-quoted fields with "" as the
// escaped-quote sequence) - matches Lazarus TStringList's
// StrictDelimiter+DelimitedText convention the original relied on.
QStringList parseCsvLine(const QString &line)
{
QStringList fields;
QString field;
bool inQuotes = false;
int i = 0;
while (i < line.size()) {
const QChar c = line.at(i);
if (inQuotes) {
if (c == '"') {
if (i + 1 < line.size() && line.at(i + 1) == '"') {
field += '"';
i += 2;
continue;
}
inQuotes = false;
++i;
} else {
field += c;
++i;
}
} else if (c == '"') {
inQuotes = true;
++i;
} else if (c == ',') {
fields.append(field);
field.clear();
++i;
} else {
field += c;
++i;
}
}
fields.append(field);
return fields;
}
QStringList splitLines(const QString &text)
{
QStringList lines = text.split('\n');
while (!lines.isEmpty() && lines.last().trimmed().isEmpty())
lines.removeLast();
return lines;
}
} // namespace
QString tableFormatText(TableFormat format)
{
switch (format) {
case TableFormat::Excel:
return QStringLiteral("Excel paste");
case TableFormat::Plain:
return QStringLiteral("Plain text");
case TableFormat::Csv:
return QStringLiteral("CSV");
case TableFormat::Html:
return QStringLiteral("HTML");
case TableFormat::ListView:
return QStringLiteral("ListView");
case TableFormat::MediaWiki:
return QStringLiteral("MediaWiki");
case TableFormat::Xml:
return QStringLiteral("XML");
case TableFormat::Json:
return QStringLiteral("JSON");
}
return {};
}
QString tableFormatExt(TableFormat format)
{
switch (format) {
case TableFormat::Excel:
case TableFormat::Plain:
case TableFormat::MediaWiki:
return QStringLiteral(".txt");
case TableFormat::Csv:
return QStringLiteral(".csv");
case TableFormat::Html:
return QStringLiteral(".htm");
case TableFormat::ListView:
return QString();
case TableFormat::Xml:
return QStringLiteral(".xml");
case TableFormat::Json:
return QStringLiteral(".json");
}
return {};
}
void Table::clear()
{
columns.clear();
rows.clear();
}
Row &Table::addRow()
{
rows.push_back(std::make_unique<Row>());
return *rows.back();
}
QString Table::outputTabs() const
{
QString result = columns.join('\t') + '\n';
for (const auto &row : rows)
result += row->cells.join('\t') + '\n';
return result;
}
QString Table::outputPlain() const
{
QString result;
for (const auto &row : rows)
result += row->cells.join('\n') + QStringLiteral("\n\n===========================\n\n");
return result;
}
QString Table::outputCsv() const
{
QString result;
for (int j = 0; j < columns.size(); ++j) {
if (j > 0)
result += ',';
if (!columns.at(j).isEmpty())
result += quoteString(columns.at(j), QStringLiteral("\""));
}
result += '\n';
for (const auto &row : rows) {
for (int j = 0; j < row->cells.size(); ++j) {
if (j > 0)
result += ',';
if (!row->cells.at(j).isEmpty())
result += quoteString(row->cells.at(j), QStringLiteral("\""));
}
result += '\n';
}
return result;
}
QString Table::outputXml() const
{
QDomDocument doc;
doc.appendChild(
doc.createProcessingInstruction(QStringLiteral("xml"), QStringLiteral("version=\"1.0\" encoding=\"UTF-8\"")));
QDomElement tableElement = doc.createElement(QStringLiteral("table"));
doc.appendChild(tableElement);
if (!title.isEmpty()) {
QDomElement titleElement = doc.createElement(QStringLiteral("title"));
titleElement.appendChild(doc.createTextNode(title));
tableElement.appendChild(titleElement);
}
QDomElement rowsElement = doc.createElement(QStringLiteral("rows"));
tableElement.appendChild(rowsElement);
for (const auto &row : rows) {
QDomElement rowElement = doc.createElement(QStringLiteral("row"));
rowsElement.appendChild(rowElement);
for (int j = 0; j < row->cells.size(); ++j) {
if (row->cells.at(j).isEmpty())
continue;
QDomElement cellElement = doc.createElement(QStringLiteral("cell"));
cellElement.setAttribute(QStringLiteral("name"), columns.value(j));
cellElement.appendChild(doc.createTextNode(row->cells.at(j)));
rowElement.appendChild(cellElement);
}
}
return doc.toString(2);
}
QString Table::outputHtml() const
{
QString result = QStringLiteral("<html>\n <head>\n <title>") + escapeHtml(title) +
QStringLiteral("</title>\n </head>\n <body>\n <table border=\"1\">\n <tr>\n");
for (const QString &column : columns)
result += QStringLiteral(" <th>") + escapeHtml(column).replace('\n', QStringLiteral("<br/>")) +
QStringLiteral("</th>\n");
result += QStringLiteral(" </tr>\n");
for (const auto &row : rows) {
result += QStringLiteral(" <tr>\n");
for (const QString &cell : row->cells)
result += QStringLiteral(" <td>") + escapeHtml(cell).replace('\n', QStringLiteral("<br/>")) +
QStringLiteral("</td>\n");
result += QStringLiteral(" </tr>\n");
}
result += QStringLiteral(" </table>\n </body>\n</html>");
return result;
}
QString Table::outputMediaWiki() const
{
QString result = QStringLiteral("{| class=\"wikitable sortable\"\n");
for (int j = 0; j < columns.size(); ++j)
result += (j == 0 ? QStringLiteral("! ") : QStringLiteral(" !! ")) + columns.at(j);
result += QStringLiteral("\n|-\n");
for (size_t i = 0; i < rows.size(); ++i) {
const Row &row = *rows[i];
for (int j = 0; j < row.cells.size(); ++j)
result += (j == 0 ? QStringLiteral("| ") : QStringLiteral(" || ")) + row.cells.at(j);
if (i + 1 < rows.size())
result += QStringLiteral("\n|-\n");
}
result += QStringLiteral("\n|}");
return result;
}
QString Table::outputJson() const
{
QJsonArray array;
for (const auto &row : rows) {
QJsonObject object;
for (int j = 0; j < row->cells.size() && j < columns.size(); ++j)
if (!row->cells.at(j).isEmpty())
object.insert(columns.at(j), row->cells.at(j));
array.append(object);
}
return QString::fromUtf8(QJsonDocument(array).toJson(QJsonDocument::Indented));
}
void Table::populateTreeWidget(QTreeWidget *tree) const
{
constexpr int minWidth = 120;
tree->setColumnCount(columns.size());
const int newWidth = std::max(minWidth, tree->width() / std::max(1, static_cast<int>(columns.size())));
for (int i = 0; i < columns.size(); ++i) {
tree->headerItem()->setText(i, columns.at(i));
tree->setColumnWidth(i, newWidth);
}
tree->clear();
for (const auto &row : rows) {
auto *item = new QTreeWidgetItem(tree);
for (int j = 0; j < row->cells.size(); ++j)
item->setText(j, row->cells.at(j));
}
}
QString Table::output(TableFormat format) const
{
switch (format) {
case TableFormat::Excel:
return outputTabs();
case TableFormat::Plain:
return outputPlain();
case TableFormat::Csv:
return outputCsv();
case TableFormat::Html:
return outputHtml();
case TableFormat::MediaWiki:
return outputMediaWiki();
case TableFormat::Xml:
return outputXml();
case TableFormat::Json:
return outputJson();
case TableFormat::ListView:
break;
}
throw std::invalid_argument("Unsupported format");
}
void Table::setInputCsv(const QString &text)
{
clear();
const QStringList lines = splitLines(text);
for (int i = 0; i < lines.size(); ++i) {
if (i == 0)
columns = parseCsvLine(lines.at(i).trimmed());
else
addRow().cells = parseCsvLine(lines.at(i).trimmed());
}
}
void Table::setInputMediaWiki(const QString &text)
{
clear();
Row *row = nullptr;
bool insideTable = false;
for (const QString &rawLine : splitLines(text)) {
const QString line = rawLine.trimmed();
if (!insideTable) {
if (line.startsWith(QStringLiteral("{|")))
insideTable = true;
continue;
}
if (line.startsWith(QStringLiteral("|}"))) {
insideTable = false;
} else if (line.startsWith('!')) {
QString remaining = line.mid(1).trimmed();
for (;;) {
const int index = remaining.indexOf(QStringLiteral("!!"));
if (index < 0) {
columns.append(remaining.trimmed());
break;
}
columns.append(remaining.left(index).trimmed());
remaining = remaining.mid(index + 2);
}
} else if (line.startsWith(QStringLiteral("|-"))) {
row = &addRow();
} else if (line.startsWith('|')) {
if (row) {
QString remaining = line.mid(1).trimmed();
for (;;) {
const int index = remaining.indexOf(QStringLiteral("||"));
if (index < 0) {
row->cells.append(remaining.trimmed());
break;
}
row->cells.append(remaining.left(index).trimmed());
remaining = remaining.mid(index + 2);
}
while (row->cells.size() < columns.size())
row->cells.append(QString());
}
}
}
}
void Table::setInputJson(const QString &text)
{
clear();
const QJsonDocument doc = QJsonDocument::fromJson(text.toUtf8());
if (!doc.isArray())
return;
for (const QJsonValue &rowValue : doc.array()) {
if (!rowValue.isObject())
continue;
const QJsonObject object = rowValue.toObject();
Row &row = addRow();
for (auto it = object.constBegin(); it != object.constEnd(); ++it) {
int columnIndex = columns.indexOf(it.key());
if (columnIndex < 0) {
columns.append(it.key());
columnIndex = columns.size() - 1;
}
while (row.cells.size() <= columnIndex)
row.cells.append(QString());
row.cells[columnIndex] = it.value().toVariant().toString();
}
}
}
void Table::setInputXml(const QString &text)
{
clear();
QDomDocument doc;
if (!doc.setContent(text))
return;
const QDomElement tableElement = doc.documentElement();
if (tableElement.tagName() != QStringLiteral("table"))
return;
QDomElement rowElement = tableElement.firstChildElement(QStringLiteral("rows")).firstChildElement(QStringLiteral("row"));
while (!rowElement.isNull()) {
Row &row = addRow();
QDomElement cellElement = rowElement.firstChildElement(QStringLiteral("cell"));
while (!cellElement.isNull()) {
const QString cellName = cellElement.attribute(QStringLiteral("name"));
int columnIndex = columns.indexOf(cellName);
if (columnIndex < 0) {
columns.append(cellName);
columnIndex = columns.size() - 1;
}
while (row.cells.size() <= columnIndex)
row.cells.append(QString());
row.cells[columnIndex] = cellElement.text();
cellElement = cellElement.nextSiblingElement(QStringLiteral("cell"));
}
rowElement = rowElement.nextSiblingElement(QStringLiteral("row"));
}
}
void Table::setInput(TableFormat format, const QString &text)
{
switch (format) {
case TableFormat::Csv:
setInputCsv(text);
return;
case TableFormat::MediaWiki:
setInputMediaWiki(text);
return;
case TableFormat::Json:
setInputJson(text);
return;
case TableFormat::Xml:
setInputXml(text);
return;
default:
throw std::invalid_argument("Unsupported format");
}
}
QList<TableFormat> Table::inputFormats()
{
return { TableFormat::Csv, TableFormat::Json, TableFormat::MediaWiki, TableFormat::Xml };
}
} // namespace Cevo
+47
View File
@@ -0,0 +1,47 @@
#include "Cevo/TestCase.h"
#include <QCoreApplication>
#include <QDebug>
namespace Cevo {
QString testResultText(TestResult result)
{
switch (result) {
case TestResult::None:
return QCoreApplication::translate("TestCase", "None");
case TestResult::Passed:
return QCoreApplication::translate("TestCase", "Passed");
case TestResult::Failed:
return QCoreApplication::translate("TestCase", "Failed");
}
return {};
}
TestCase *TestCases::addNew(const QString &name, std::unique_ptr<TestCase> testCase)
{
testCase->name = name;
TestCase *result = testCase.get();
m_items.push_back(std::move(testCase));
return result;
}
void TestCases::run()
{
int passed = 0, failed = 0;
for (const auto &testCase : m_items) {
qDebug().noquote() << "== " << testCase->name << " ======= ";
testCase->initialize();
testCase->run();
testCase->finalize();
if (testCase->testResult == TestResult::Passed)
++passed;
else if (testCase->testResult == TestResult::Failed)
++failed;
}
for (const auto &testCase : m_items)
qDebug().noquote() << testCase->name << ": " << testResultText(testCase->testResult);
qDebug().noquote() << "Total: " << count() << ", Passed: " << passed << ", Failed: " << failed;
}
} // namespace Cevo
+55
View File
@@ -0,0 +1,55 @@
#include "Cevo/Threading.h"
#include <QCoreApplication>
#include <QEventLoop>
#include <QThread>
#include <exception>
namespace Cevo {
void runInThread(const std::function<void()> &method)
{
std::exception_ptr failure;
QThread *thread = QThread::create([&method, &failure]() {
try {
method();
} catch (...) {
failure = std::current_exception();
}
});
if (QThread::currentThread() == qApp->thread()) {
QEventLoop loop;
QObject::connect(thread, &QThread::finished, &loop, &QEventLoop::quit);
thread->start();
loop.exec();
} else {
thread->start();
thread->wait();
}
delete thread;
if (failure)
std::rethrow_exception(failure);
}
void runInThreadAsync(const std::function<void()> &method, const std::function<void()> &callback)
{
QThread *thread = QThread::create(method);
if (callback)
QObject::connect(thread, &QThread::finished, thread, callback);
QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater);
thread->start();
}
void synchronizeToMainThread(const std::function<void()> &method)
{
if (QThread::currentThread() == qApp->thread()) {
method();
return;
}
QMetaObject::invokeMethod(qApp, method, Qt::BlockingQueuedConnection);
}
} // namespace Cevo
+111
View File
@@ -0,0 +1,111 @@
#include "Cevo/XML.h"
#include <QFile>
#include <stdexcept>
namespace Cevo {
namespace {
void writeChild(QDomElement &node, const QString &name, const QString &text)
{
QDomElement child = node.ownerDocument().createElement(name);
child.appendChild(node.ownerDocument().createTextNode(text));
node.appendChild(child);
}
} // namespace
void writeInteger(QDomElement &node, const QString &name, int value)
{
writeChild(node, name, QString::number(value));
}
void writeInt64(QDomElement &node, const QString &name, qint64 value)
{
writeChild(node, name, QString::number(value));
}
void writeBoolean(QDomElement &node, const QString &name, bool value)
{
writeChild(node, name, value ? QStringLiteral("True") : QStringLiteral("False"));
}
void writeString(QDomElement &node, const QString &name, const QString &value)
{
writeChild(node, name, value);
}
void writeDateTime(QDomElement &node, const QString &name, const QDateTime &value)
{
writeChild(node, name, value.toString(Qt::ISODateWithMs));
}
void writeDouble(QDomElement &node, const QString &name, double value)
{
writeChild(node, name, QString::number(value));
}
int readInteger(const QDomElement &node, const QString &name, int defaultValue)
{
const QDomElement child = node.firstChildElement(name);
return child.isNull() ? defaultValue : child.text().toInt();
}
qint64 readInt64(const QDomElement &node, const QString &name, qint64 defaultValue)
{
const QDomElement child = node.firstChildElement(name);
return child.isNull() ? defaultValue : child.text().toLongLong();
}
bool readBoolean(const QDomElement &node, const QString &name, bool defaultValue)
{
const QDomElement child = node.firstChildElement(name);
return child.isNull() ? defaultValue : (child.text().compare(QStringLiteral("True"), Qt::CaseInsensitive) == 0);
}
QString readString(const QDomElement &node, const QString &name, const QString &defaultValue)
{
const QDomElement child = node.firstChildElement(name);
return child.isNull() ? defaultValue : child.text();
}
QDateTime readDateTime(const QDomElement &node, const QString &name, const QDateTime &defaultValue)
{
const QDomElement child = node.firstChildElement(name);
if (child.isNull())
return defaultValue;
const QDateTime value = QDateTime::fromString(child.text(), Qt::ISODateWithMs);
return value.isValid() ? value : defaultValue;
}
double readDouble(const QDomElement &node, const QString &name, double defaultValue)
{
const QDomElement child = node.firstChildElement(name);
return child.isNull() ? defaultValue : child.text().toDouble();
}
QDomDocument readXmlFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
throw std::runtime_error(("Could not open " + fileName).toStdString());
QDomDocument doc;
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
const QDomDocument::ParseResult result = doc.setContent(&file);
if (!result)
throw std::runtime_error(QStringLiteral("XML parse error at %1:%2: %3")
.arg(result.errorLine)
.arg(result.errorColumn)
.arg(result.errorMessage)
.toStdString());
#else
QString errorMessage;
int errorLine = 0, errorColumn = 0;
if (!doc.setContent(&file, &errorMessage, &errorLine, &errorColumn))
throw std::runtime_error(
QStringLiteral("XML parse error at %1:%2: %3").arg(errorLine).arg(errorColumn).arg(errorMessage).toStdString());
#endif
return doc;
}
} // namespace Cevo