initial port for Cevo game in C++ (libs)
No files matched your search
@@ -0,0 +1,82 @@
|
|||||||
|
# This file is used to ignore files which are generated
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
*~
|
||||||
|
*.autosave
|
||||||
|
*.a
|
||||||
|
*.core
|
||||||
|
*.moc
|
||||||
|
*.o
|
||||||
|
*.obj
|
||||||
|
*.orig
|
||||||
|
*.rej
|
||||||
|
*.so
|
||||||
|
*.so.*
|
||||||
|
*_pch.h.cpp
|
||||||
|
*_resource.rc
|
||||||
|
*.qm
|
||||||
|
.#*
|
||||||
|
*.*#
|
||||||
|
core
|
||||||
|
!core/
|
||||||
|
tags
|
||||||
|
.DS_Store
|
||||||
|
.directory
|
||||||
|
*.debug
|
||||||
|
Makefile*
|
||||||
|
*.prl
|
||||||
|
*.app
|
||||||
|
moc_*.cpp
|
||||||
|
ui_*.h
|
||||||
|
qrc_*.cpp
|
||||||
|
Thumbs.db
|
||||||
|
*.res
|
||||||
|
*.rc
|
||||||
|
/.qmake.cache
|
||||||
|
/.qmake.stash
|
||||||
|
|
||||||
|
# qtcreator generated files
|
||||||
|
*.pro.user*
|
||||||
|
*.qbs.user*
|
||||||
|
CMakeLists.txt.user*
|
||||||
|
|
||||||
|
# xemacs temporary files
|
||||||
|
*.flc
|
||||||
|
|
||||||
|
# Vim temporary files
|
||||||
|
.*.swp
|
||||||
|
|
||||||
|
# Visual Studio generated files
|
||||||
|
*.ib_pdb_index
|
||||||
|
*.idb
|
||||||
|
*.ilk
|
||||||
|
*.pdb
|
||||||
|
*.sln
|
||||||
|
*.suo
|
||||||
|
*.vcproj
|
||||||
|
*vcproj.*.*.user
|
||||||
|
*.ncb
|
||||||
|
*.sdf
|
||||||
|
*.opensdf
|
||||||
|
*.vcxproj
|
||||||
|
*vcxproj.*
|
||||||
|
|
||||||
|
# MinGW generated files
|
||||||
|
*.Debug
|
||||||
|
*.Release
|
||||||
|
|
||||||
|
# Python byte code
|
||||||
|
*.pyc
|
||||||
|
|
||||||
|
# Binaries
|
||||||
|
# --------
|
||||||
|
*.dll
|
||||||
|
*.exe
|
||||||
|
|
||||||
|
# Directories with generated files
|
||||||
|
.moc/
|
||||||
|
.obj/
|
||||||
|
.pch/
|
||||||
|
.rcc/
|
||||||
|
.uic/
|
||||||
|
/build*/
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.16)
|
||||||
|
|
||||||
|
project(cevo-evo VERSION 0.1 LANGUAGES CXX)
|
||||||
|
|
||||||
|
option(CEVO_WITH_APP "Build the game application (widget/media + cevo-evo executable)" ON)
|
||||||
|
option(CEVO_WITH_AI "Build and install the bundled stdai AI plugin (turn off to rely on a third-party AI module instead)" ON)
|
||||||
|
if(NOT CEVO_WITH_APP AND NOT CEVO_WITH_AI)
|
||||||
|
message(FATAL_ERROR "Nothing to build: enable at least one of CEVO_WITH_APP or CEVO_WITH_AI")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(CMAKE_AUTOUIC ON)
|
||||||
|
set(CMAKE_AUTOMOC ON)
|
||||||
|
set(CMAKE_AUTORCC ON)
|
||||||
|
|
||||||
|
set(CMAKE_CXX_STANDARD 17)
|
||||||
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
|
|
||||||
|
# ai/stdai has no Qt dependency, so only require Qt when building the app.
|
||||||
|
if(CEVO_WITH_APP)
|
||||||
|
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets Multimedia Xml LinguistTools)
|
||||||
|
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets Multimedia Xml LinguistTools)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
include(GNUInstallDirs)
|
||||||
|
|
||||||
|
# Extra install dirs, following GNUInstallDirs' own CACHE PATH convention
|
||||||
|
# (relative to CMAKE_INSTALL_PREFIX unless given as an absolute path).
|
||||||
|
set(CMAKE_INSTALL_AIDIR "${CMAKE_INSTALL_LIBDIR}/cevo-evo/ai" CACHE PATH
|
||||||
|
"AI plugin modules (e.g. stdai) - where the game looks for loadable AI brains")
|
||||||
|
set(CMAKE_INSTALL_RESOURCEDIR "${CMAKE_INSTALL_DATADIR}/cevo-evo" CACHE PATH
|
||||||
|
"Game resources (graphics, music, sounds, resource translations)")
|
||||||
|
foreach(_cevo_dir AIDIR RESOURCEDIR)
|
||||||
|
if(IS_ABSOLUTE "${CMAKE_INSTALL_${_cevo_dir}}")
|
||||||
|
set(CMAKE_INSTALL_FULL_${_cevo_dir} "${CMAKE_INSTALL_${_cevo_dir}}")
|
||||||
|
else()
|
||||||
|
set(CMAKE_INSTALL_FULL_${_cevo_dir} "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_${_cevo_dir}}")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
# ai/ is the generic AI-plugin interface: needed by the app (to load AI
|
||||||
|
# modules at runtime) and by the bundled stdai plugin (as its base classes).
|
||||||
|
if(CEVO_WITH_APP OR CEVO_WITH_AI)
|
||||||
|
add_subdirectory(ai)
|
||||||
|
endif()
|
||||||
|
# stdai is a dynamically-loaded AI plugin (see ai/stdai/CMakeLists.txt): built
|
||||||
|
# here but deliberately NOT linked into the cevo-evo target below.
|
||||||
|
if(CEVO_WITH_AI)
|
||||||
|
add_subdirectory(ai/stdai)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(CEVO_WITH_APP)
|
||||||
|
add_subdirectory(widget)
|
||||||
|
add_subdirectory(media)
|
||||||
|
add_subdirectory(common)
|
||||||
|
add_subdirectory(resources)
|
||||||
|
|
||||||
|
set(TS_FILES cevo-evo_en_US.ts)
|
||||||
|
|
||||||
|
set(PROJECT_SOURCES
|
||||||
|
main.cpp
|
||||||
|
mainwindow.cpp
|
||||||
|
mainwindow.h
|
||||||
|
mainwindow.ui
|
||||||
|
${TS_FILES}
|
||||||
|
)
|
||||||
|
|
||||||
|
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
|
||||||
|
qt_add_executable(cevo-evo
|
||||||
|
MANUAL_FINALIZATION
|
||||||
|
${PROJECT_SOURCES}
|
||||||
|
)
|
||||||
|
# Define target properties for Android with Qt 6 as:
|
||||||
|
# set_property(TARGET cevo-evo APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
|
||||||
|
# ${CMAKE_CURRENT_SOURCE_DIR}/android)
|
||||||
|
# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation
|
||||||
|
|
||||||
|
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||||
|
else()
|
||||||
|
if(ANDROID)
|
||||||
|
add_library(cevo-evo SHARED
|
||||||
|
${PROJECT_SOURCES}
|
||||||
|
)
|
||||||
|
# Define properties for Android with Qt 5 after find_package() calls as:
|
||||||
|
# set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
|
||||||
|
else()
|
||||||
|
add_executable(cevo-evo
|
||||||
|
${PROJECT_SOURCES}
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
target_link_libraries(cevo-evo PRIVATE Qt${QT_VERSION_MAJOR}::Widgets dpiwidgets cevowidgets uosmedia cevocommon cevoai)
|
||||||
|
|
||||||
|
# dpiwidgets/cevowidgets/uosmedia are installed to lib/cevo-evo (not the
|
||||||
|
# default library directory), so the installed binary needs an explicit
|
||||||
|
# rpath to find them at runtime.
|
||||||
|
set_target_properties(cevo-evo PROPERTIES
|
||||||
|
INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}/cevo-evo"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Default, compile-time-known locations the game looks for its AI plugins
|
||||||
|
# and its resources (graphics/music/sounds/translations) at runtime.
|
||||||
|
target_compile_definitions(cevo-evo PRIVATE
|
||||||
|
CEVO_AI_DIR="${CMAKE_INSTALL_FULL_AIDIR}"
|
||||||
|
CEVO_RESOURCE_DIR="${CMAKE_INSTALL_FULL_RESOURCEDIR}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1.
|
||||||
|
# If you are developing for iOS or macOS you should consider setting an
|
||||||
|
# explicit, fixed bundle identifier manually though.
|
||||||
|
if(${QT_VERSION} VERSION_LESS 6.1.0)
|
||||||
|
set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.cevo-evo)
|
||||||
|
endif()
|
||||||
|
set_target_properties(cevo-evo PROPERTIES
|
||||||
|
${BUNDLE_ID_OPTION}
|
||||||
|
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
|
||||||
|
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
|
||||||
|
MACOSX_BUNDLE TRUE
|
||||||
|
WIN32_EXECUTABLE TRUE
|
||||||
|
)
|
||||||
|
|
||||||
|
install(TARGETS cevo-evo
|
||||||
|
BUNDLE DESTINATION .
|
||||||
|
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||||
|
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||||
|
)
|
||||||
|
|
||||||
|
if(QT_VERSION_MAJOR EQUAL 6)
|
||||||
|
qt_finalize_executable(cevo-evo)
|
||||||
|
endif()
|
||||||
|
endif() # CEVO_WITH_APP
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# CevoAI: C++ port of the C-evo AI plugin protocol (AI Template/Protocol.pas
|
||||||
|
# + CustomAI.pas), used to load/host AI "brain" modules (StdAI, Capital AI,
|
||||||
|
# KIAI, SETI, Shah, Crystal, ...) and to write new ones. Deliberately has NO
|
||||||
|
# dependency on Qt (or any other framework): the original protocol is a plain
|
||||||
|
# C ABI (stdcall function pointers + C-aligned structs), and this port keeps
|
||||||
|
# it that way so existing precompiled AI .dll/.so files stay loadable and new
|
||||||
|
# AI modules can be built as plain, portable C++ shared libraries.
|
||||||
|
#
|
||||||
|
# Concrete AI "brain" implementations (StdAI, ...) live in their own
|
||||||
|
# subdirectory below this one (e.g. stdai/), each built as a separate
|
||||||
|
# shared-library plugin on top of this interface - see stdai/CMakeLists.txt.
|
||||||
|
|
||||||
|
set(CEVO_AI_HEADERS
|
||||||
|
include/Cevo/AiModule.h
|
||||||
|
include/Cevo/AiModuleHost.h
|
||||||
|
include/Cevo/CustomAI.h
|
||||||
|
include/Cevo/Geometry.h
|
||||||
|
include/Cevo/Pile.h
|
||||||
|
include/Cevo/Protocol.h
|
||||||
|
include/Cevo/ToolAI.h
|
||||||
|
)
|
||||||
|
|
||||||
|
set(CEVO_AI_SOURCES
|
||||||
|
src/AiModule.cpp
|
||||||
|
src/AiModuleHost.cpp
|
||||||
|
src/CustomAI.cpp
|
||||||
|
src/Geometry.cpp
|
||||||
|
src/Pile.cpp
|
||||||
|
src/Protocol.cpp
|
||||||
|
src/ToolAI.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
add_library(cevoai STATIC ${CEVO_AI_SOURCES} ${CEVO_AI_HEADERS})
|
||||||
|
|
||||||
|
target_include_directories(cevoai PUBLIC
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(cevoai PUBLIC ${CMAKE_DL_LIBS})
|
||||||
|
|
||||||
|
set_target_properties(cevoai PROPERTIES
|
||||||
|
CXX_STANDARD 17
|
||||||
|
CXX_STANDARD_REQUIRED ON
|
||||||
|
POSITION_INDEPENDENT_CODE ON
|
||||||
|
)
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Cevo/Protocol.h"
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
// Cross-platform dynamic-library loader for brain modules (AI plugins, and
|
||||||
|
// in principle any other module speaking the same protocol) exporting the
|
||||||
|
// "client" entry point defined by Protocol.h (TClientCall). This is the
|
||||||
|
// host-side counterpart of AIProject.lpr's `library` wrapper: it lets the
|
||||||
|
// game load precompiled AI .dll/.so files (StdAI, Capital AI, KIAI, ...)
|
||||||
|
// exactly as the original Pascal game did, with no dependency on Qt or any
|
||||||
|
// other framework - just the platform's native dynamic-loading API
|
||||||
|
// (LoadLibrary/GetProcAddress on Windows, dlopen/dlsym on POSIX).
|
||||||
|
class AiModule {
|
||||||
|
public:
|
||||||
|
AiModule() = default;
|
||||||
|
~AiModule();
|
||||||
|
AiModule(const AiModule &) = delete;
|
||||||
|
AiModule &operator=(const AiModule &) = delete;
|
||||||
|
|
||||||
|
// fileName: a .dll on Windows, .so on Linux/BSD, .dylib on macOS.
|
||||||
|
// Returns false (with errorMessage() set) if the file can't be loaded or
|
||||||
|
// doesn't export a "client" symbol.
|
||||||
|
bool load(const std::string &fileName);
|
||||||
|
void unload();
|
||||||
|
bool isLoaded() const { return m_client != nullptr; }
|
||||||
|
const std::string &errorMessage() const { return m_error; }
|
||||||
|
|
||||||
|
// Invokes the module's Client(Command, Player, Data) entry point.
|
||||||
|
void call(int command, int player, void *data) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
void *m_handle = nullptr;
|
||||||
|
TClientCall m_client = nullptr;
|
||||||
|
std::string m_error;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Cevo/CustomAI.h"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <functional>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
// Generic module-level harness: owns one CustomAI-derived instance per
|
||||||
|
// nation and dispatches every command a brain module's exported "client"
|
||||||
|
// entry point can receive, mirroring StdAI.lpr's `Client` procedure exactly
|
||||||
|
// (lifecycle commands, turn/negotiation via CustomAI::process(), map
|
||||||
|
// geometry setup, and the cmShowAttacking/cmShowCapturing/cmShowAfterAttack/
|
||||||
|
// cmShowAfterMove enemy-move notifications with their TShowMove->TUnitInfo
|
||||||
|
// conversion and cross-call "Defender" tracking). A concrete AI module's
|
||||||
|
// exported "client" entry point just forwards every call here via
|
||||||
|
// CEVO_EXPORT_AI_CLIENT below - this class *is* the reusable "common
|
||||||
|
// interface"; StdAI.lpr (or an equivalent for a new AI) only needs to supply
|
||||||
|
// the CustomAI subclass.
|
||||||
|
class AiModuleHost {
|
||||||
|
public:
|
||||||
|
using Factory = std::function<std::unique_ptr<CustomAI>(int nation)>;
|
||||||
|
|
||||||
|
// rwDataSize: extra per-nation read/write scratch size (in bytes) this
|
||||||
|
// module asks the server to allocate, reported back via
|
||||||
|
// TInitModuleData.DataSize at cmInitModule (0 if the module keeps no
|
||||||
|
// persistent per-nation data beyond what CustomAI already tracks).
|
||||||
|
explicit AiModuleHost(Factory factory, int rwDataSize = 0)
|
||||||
|
: m_factory(std::move(factory)), m_rwDataSize(rwDataSize)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns true if `command` was recognized and handled here.
|
||||||
|
bool handle(int command, int player, void *data);
|
||||||
|
|
||||||
|
CustomAI *ai(int nation) const { return m_ai[static_cast<size_t>(nation)].get(); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
Factory m_factory;
|
||||||
|
int m_rwDataSize;
|
||||||
|
std::array<std::unique_ptr<CustomAI>, nPl> m_ai;
|
||||||
|
TNewGameData m_game{};
|
||||||
|
int m_defender = -1;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
|
|
||||||
|
// Place once in a plugin's main translation unit to export the required C
|
||||||
|
// ABI "client" entry point, forwarding every call to a (file-scope)
|
||||||
|
// Cevo::AiModuleHost instance:
|
||||||
|
//
|
||||||
|
// Cevo::AiModuleHost host([](int nation) { return std::make_unique<MyAI>(nation); });
|
||||||
|
// CEVO_EXPORT_AI_CLIENT(host)
|
||||||
|
#define CEVO_EXPORT_AI_CLIENT(hostVar) \
|
||||||
|
extern "C" void CEVO_ABI_CALL client(std::int32_t command, std::int32_t player, void *data) \
|
||||||
|
{ \
|
||||||
|
(hostVar).handle(command, player, data); \
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Cevo/Protocol.h"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <bitset>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
enum class NegoTime { BeginOfTurn, EndOfTurn, EnemyCalled };
|
||||||
|
|
||||||
|
constexpr int CityOwnTile = 13; // = ab_to_V21(0, 0)
|
||||||
|
|
||||||
|
// C++ equivalent of CustomAI.pas's TCustomAI: the base class for a single
|
||||||
|
// player's AI "brain". Mirrors the original's full Process() dispatch and
|
||||||
|
// its protected Unit_*/City_*/general Server-call wrappers, so ported AI
|
||||||
|
// logic (StdAI's TAI, etc.) plugs in the same way.
|
||||||
|
class CustomAI {
|
||||||
|
public:
|
||||||
|
explicit CustomAI(int nation) : me(nation) {}
|
||||||
|
virtual ~CustomAI();
|
||||||
|
|
||||||
|
// Attaches the player context handed out by the server at
|
||||||
|
// cmNewGame/cmLoadGame (TNewGameData.RO[nation]).
|
||||||
|
void bind(TPlayerContext *playerContext);
|
||||||
|
|
||||||
|
// Set once per module from cmInitModule's TInitModuleData.Server; shared
|
||||||
|
// by every CustomAI instance in this process, matching the original's
|
||||||
|
// single unit-level `Server` global.
|
||||||
|
static void setServerCall(TServerCall call) { s_server = call; }
|
||||||
|
|
||||||
|
// Dispatches a single Command/Data pair received from the host (mirrors
|
||||||
|
// TCustomAI.Process in full: turn/negotiation loop, scContact probing,
|
||||||
|
// scDipStart..scDipBreak). cmShowAttacking/cmShowCapturing/
|
||||||
|
// cmShowAfterAttack/cmShowAfterMove are NOT dispatched through here
|
||||||
|
// (unlike cmTurn etc.): the original's library wrapper (StdAI.lpr)
|
||||||
|
// intercepts them directly to call onBeforeEnemyAttack() and friends, see
|
||||||
|
// AiModuleHost.
|
||||||
|
void process(int command, void *data);
|
||||||
|
|
||||||
|
virtual void setDataDefaults() {}
|
||||||
|
virtual void setDataRandom() {}
|
||||||
|
virtual void onBeforeEnemyAttack(const TUnitInfo &unitInfo, int toLoc, int endHealth, int endHealthDef) {}
|
||||||
|
virtual void onBeforeEnemyCapture(const TUnitInfo &unitInfo, int toLoc) {}
|
||||||
|
virtual void onAfterEnemyAttack() {}
|
||||||
|
virtual void onAfterEnemyCapture() {}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
int me; // index of the controlled nation
|
||||||
|
TPlayerContext *ro = nullptr;
|
||||||
|
std::uint32_t *map = nullptr; // ro->Map, indexable as map[loc]
|
||||||
|
TUn *myUnit = nullptr; // ro->Un, indexable as myUnit[uix]
|
||||||
|
TCity *myCity = nullptr; // ro->City, indexable as myCity[cix]
|
||||||
|
TModel *myModel = nullptr; // ro->Model, indexable as myModel[mix]
|
||||||
|
|
||||||
|
// cix of the city that built a given "state" (unique per empire)
|
||||||
|
// improvement, indexed by iix - imPalace; -1 if none. Refreshed once per
|
||||||
|
// cmTurn.
|
||||||
|
std::array<int, imSpacePort - imPalace + 1> cixStateImp{};
|
||||||
|
|
||||||
|
// negotiation
|
||||||
|
int opponent = -1; // nation i'm in negotiation with, -1 = no negotiation
|
||||||
|
int myAction = 0, myLastAction = 0, oppoAction = 0;
|
||||||
|
TOffer myOffer{}, myLastOffer{}, oppoOffer{};
|
||||||
|
|
||||||
|
virtual void doTurn() {}
|
||||||
|
virtual void doNegotiation() {}
|
||||||
|
virtual int chooseResearchAdvance() { return -1; }
|
||||||
|
virtual int chooseStealAdvance() { return -1; }
|
||||||
|
virtual int chooseGovernment() { return gDespotism; }
|
||||||
|
virtual bool wantNegotiation(int nation, NegoTime negoTime) { return false; }
|
||||||
|
virtual bool onNegoRejected_CancelTreaty() { return false; }
|
||||||
|
|
||||||
|
// ---- general functions ----
|
||||||
|
bool isResearched(int advance) const
|
||||||
|
{
|
||||||
|
return advance == preNone || (advance != preNA && ro->Tech[advance] >= tsApplicable);
|
||||||
|
}
|
||||||
|
int researchCost() const;
|
||||||
|
int changeAttitude(int nation, int attitude) const;
|
||||||
|
int revolution() const;
|
||||||
|
int changeRates(int tax, int lux) const;
|
||||||
|
int prepareNewModel(int domain) const;
|
||||||
|
int setNewModelFeature(int feature, int count) const;
|
||||||
|
bool advanceResearchable(int advance) const;
|
||||||
|
bool advanceStealable(int advance) const;
|
||||||
|
bool getJobProgress(int loc, TJobProgressData &jobProgress) const;
|
||||||
|
bool debugMessage(int level, const std::string &text) const;
|
||||||
|
bool setDebugMap(void *debugMap) const;
|
||||||
|
|
||||||
|
// ---- unit functions ----
|
||||||
|
int unit_FindMyDefender(int loc) const;
|
||||||
|
int unit_FindEnemyDefender(int loc) const;
|
||||||
|
int unit_Move(int uix, int toLoc);
|
||||||
|
int unit_Step(int uix, int toLoc);
|
||||||
|
int unit_Attack(int uix, int toLoc) const;
|
||||||
|
int unit_DoMission(int uix, int missionType, int toLoc) const;
|
||||||
|
bool unit_MoveForecast(int uix, int toLoc, int &remainingMovement) const;
|
||||||
|
bool unit_AttackForecast(int uix, int toLoc, int attackMovement, int &remainingHealth) const;
|
||||||
|
bool unit_DefenseForecast(int euix, int toLoc, int &remainingHealth) const;
|
||||||
|
int unit_Disband(int uix) const;
|
||||||
|
int unit_StartJob(int uix, int newJob) const;
|
||||||
|
int unit_SetHomeHere(int uix) const;
|
||||||
|
int unit_Load(int uix) const;
|
||||||
|
int unit_Unload(int uix) const;
|
||||||
|
int unit_SelectTransport(int uix) const;
|
||||||
|
int unit_AddToCity(int uix) const;
|
||||||
|
|
||||||
|
// ---- city functions ----
|
||||||
|
int city_FindMyCity(int loc) const;
|
||||||
|
int city_FindEnemyCity(int loc) const;
|
||||||
|
bool city_HasProject(int cix) const;
|
||||||
|
int city_CurrentImprovementProject(int cix) const;
|
||||||
|
int city_CurrentUnitProject(int cix) const;
|
||||||
|
int city_GetTileInfo(int cix, int tileLoc, TTileInfo &tileInfo) const;
|
||||||
|
int city_GetReport(int cix, TCityReport &report) const;
|
||||||
|
int city_GetHypoReport(int cix, int hypoTiles, int hypoTax, int hypoLux, TCityReport &report) const;
|
||||||
|
int city_GetReportNew(int cix, TCityReportNew &report) const;
|
||||||
|
int city_GetHypoReportNew(int cix, int hypoTiles, int hypoTaxRate, int hypoLuxuryRate,
|
||||||
|
TCityReportNew &report) const;
|
||||||
|
int city_GetAreaInfo(int cix, TCityAreaInfo &areaInfo) const;
|
||||||
|
int city_StartUnitProduction(int cix, int mix) const;
|
||||||
|
int city_StartEmigration(int cix, int mix, bool allowDisbandCity, bool asConscripts) const;
|
||||||
|
int city_StartImprovement(int cix, int iix) const;
|
||||||
|
bool city_Improvable(int cix, int iix) const;
|
||||||
|
int city_StopProduction(int cix) const;
|
||||||
|
int city_BuyProject(int cix) const;
|
||||||
|
int city_SellImprovement(int cix, int iix) const;
|
||||||
|
int city_RebuildImprovement(int cix, int iix) const;
|
||||||
|
int city_SetTiles(int cix, int newTiles) const;
|
||||||
|
void city_OptimizeTiles(int cix, std::uint32_t resourceWeights = rwMaxGrowth) const;
|
||||||
|
|
||||||
|
// ---- negotiation ----
|
||||||
|
int nego_CheckMyAction() const;
|
||||||
|
|
||||||
|
// Direct Server() call: Server(command, me, subject, data).
|
||||||
|
int rawServerCall(int command, int subject, void *data) const
|
||||||
|
{
|
||||||
|
return s_server ? s_server(command, me, subject, data) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
void stealAdvance();
|
||||||
|
|
||||||
|
static TServerCall s_server;
|
||||||
|
bool haveTurned = false;
|
||||||
|
std::bitset<nPl> unwantedNego;
|
||||||
|
std::bitset<nPl> contacted;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
|
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Cevo/Protocol.h"
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
using TVicinity8Loc = std::int32_t[8];
|
||||||
|
using TVicinity21Loc = std::int32_t[28];
|
||||||
|
|
||||||
|
// Map-geometry helpers ported from CustomAI.pas's free functions (ab_to_Loc,
|
||||||
|
// Loc_to_ab, ...). Call InitGeometry() once per game (cmNewGame/cmLoadGame,
|
||||||
|
// before any CustomAI instances are created) - mirrors CustomAI.pas's
|
||||||
|
// Init(NewGameData). Process-global, like the original's unit-level G/MapSize.
|
||||||
|
void InitGeometry(const TNewGameData &newGameData);
|
||||||
|
int MapWidth();
|
||||||
|
int MapHeight();
|
||||||
|
int MapSize();
|
||||||
|
// G.Difficulty[nation] from the same TNewGameData passed to InitGeometry().
|
||||||
|
int Difficulty(int nation);
|
||||||
|
|
||||||
|
// Relative location from Loc0, in (A, B) hex-offset coordinates; -0x1000 if
|
||||||
|
// off the (south-pole-capped) map.
|
||||||
|
void ab_to_Loc(int Loc0, int A, int B, int &Loc);
|
||||||
|
void Loc_to_ab(int Loc0, int Loc, int &A, int &B);
|
||||||
|
void ab_to_V8(int A, int B, int &V8);
|
||||||
|
void V8_to_ab(int V8, int &A, int &B);
|
||||||
|
void ab_to_V21(int A, int B, int &V21);
|
||||||
|
void V21_to_ab(int V21, int &A, int &B);
|
||||||
|
void V8_to_Loc(int Loc0, TVicinity8Loc &VicinityLoc);
|
||||||
|
void V21_to_Loc(int Loc0, TVicinity21Loc &VicinityLoc);
|
||||||
|
int Distance(int Loc0, int Loc1);
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
// Indexed binary min-heap (decrease-key capable priority queue), ported from
|
||||||
|
// Pile.pas ("single instance priority queue; main parts contributed by
|
||||||
|
// Rassim Eminli"). The original was a single global instance reused across
|
||||||
|
// callers via Create()/Free(); this port lifts that restriction (each
|
||||||
|
// instance owns its storage) but keeps the same Create/Free/Empty/Put/
|
||||||
|
// TestPut/Get API so a port of ToolAI.pas's usage is mechanical.
|
||||||
|
class Pile {
|
||||||
|
public:
|
||||||
|
static constexpr int MaxSize = 9600;
|
||||||
|
|
||||||
|
// (Re)initializes the pile for items in [0, size). Must be called
|
||||||
|
// before put()/get().
|
||||||
|
void create(int size);
|
||||||
|
void free() {} // kept for API parity; nothing to release
|
||||||
|
void empty();
|
||||||
|
|
||||||
|
// Inserts/decreases the priority of `item` to `value`. Returns false
|
||||||
|
// (no change made) if `item` is already queued with a value <= `value`.
|
||||||
|
bool put(int item, int value);
|
||||||
|
// Like put(), without the side effect: would it actually change anything?
|
||||||
|
bool testPut(int item, int value) const;
|
||||||
|
// Removes and returns the lowest-value item. Returns false if empty.
|
||||||
|
bool get(int &item, int &value);
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct HeapItem {
|
||||||
|
int item;
|
||||||
|
int value;
|
||||||
|
};
|
||||||
|
|
||||||
|
HeapItem bh_[MaxSize];
|
||||||
|
int ix_[MaxSize];
|
||||||
|
int n_ = 0;
|
||||||
|
int currentSize_ = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Cevo/CustomAI.h"
|
||||||
|
#include "Cevo/Pile.h"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
// no-formation sentinel values (Formation[]/map analysis)
|
||||||
|
constexpr int nfUndiscovered = -1;
|
||||||
|
constexpr int nfPole = -2;
|
||||||
|
constexpr int nfPeace = -3;
|
||||||
|
|
||||||
|
// return codes of checkStep()
|
||||||
|
constexpr int csOk = 0; // step is valid, timeAfterStep has been calculated
|
||||||
|
constexpr int csForbiddenTile = 1; // unit can not move onto this tile
|
||||||
|
constexpr int csForbiddenStep = 2; // (ZoC unit only) unit can not do this step because of ZoC violation
|
||||||
|
constexpr int csCheckTerritory = 3; // move within other nation's territory shortly after peace
|
||||||
|
|
||||||
|
constexpr int mxAdjacent = 0x00000001; // unit_MoveEx option
|
||||||
|
|
||||||
|
struct GroupTransportPlan {
|
||||||
|
int LoadLoc = -1;
|
||||||
|
int uixTransport = 0;
|
||||||
|
int nLoad = 0;
|
||||||
|
int TurnsEmpty = 0;
|
||||||
|
int TurnsLoaded = 0;
|
||||||
|
int uixLoad[16] = {};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Total number of prerequisites for each advance; computed once at process
|
||||||
|
// startup (mirrors ToolAI.pas's SetAdvancedness(), run from its
|
||||||
|
// `initialization` section).
|
||||||
|
extern const std::array<int, nAdv> Advancedness;
|
||||||
|
|
||||||
|
// C++ equivalent of ToolAI.pas's TToolAI: map analysis, job assignment,
|
||||||
|
// pathfinding and sea-transport planning helpers built on top of CustomAI's
|
||||||
|
// raw Server-call wrappers.
|
||||||
|
//
|
||||||
|
// Like the original, the scratch state below (formation/district/cityResult,
|
||||||
|
// job-assignment and sea-transport working buffers, the Pile instance) is
|
||||||
|
// process-shared (static), not per-nation: AI turn processing is strictly
|
||||||
|
// sequential (one nation's DoTurn() completes before another's starts), so
|
||||||
|
// the original reused unit-level globals instead of per-instance buffers.
|
||||||
|
class ToolAI : public CustomAI {
|
||||||
|
public:
|
||||||
|
using CustomAI::CustomAI;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
int centerOfEmpire() const; // tile that is in the middle of all own cities
|
||||||
|
|
||||||
|
// Exact difference of income and maintenance cost for a single city;
|
||||||
|
// positive = income higher than maintenance. cityReport must have been
|
||||||
|
// prepared (city_GetReport/city_GetHypoReport) before calling this.
|
||||||
|
int cityTaxBalance(int cix, const TCityReport &cityReport) const;
|
||||||
|
// Exact total tax and science income; tax is reduced by maintenance (so
|
||||||
|
// might be negative). Luxury not supported.
|
||||||
|
void sumCities(int taxRate, int &taxSum, int &scienceSum) const;
|
||||||
|
|
||||||
|
void optimizeCityTiles() const; // obsolete; use city_OptimizeTiles instead
|
||||||
|
void getCityProdPotential(); // fills cityResult[cix] with production potential
|
||||||
|
void getCityTradePotential(); // fills cityResult[cix] with trade potential
|
||||||
|
|
||||||
|
// Settler job assignment: initialize, add jobs/units, then go; assigns
|
||||||
|
// each job to one settler, moves the settlers and makes them work.
|
||||||
|
void jobAssignment_Initialize();
|
||||||
|
void jobAssignment_AddJob(int loc, int job, int score);
|
||||||
|
void jobAssignment_AddUnit(int uix);
|
||||||
|
void jobAssignment_Go();
|
||||||
|
bool jobAssignment_GotJob(int uix) const;
|
||||||
|
|
||||||
|
void analyzeMap(); // calculates formations (continents/oceans) and districts
|
||||||
|
|
||||||
|
// Forecast a single unit move between adjacent tiles. fromTile/toTile
|
||||||
|
// must be Map[FromLoc]/Map[ToLoc] (not location codes). crossCorner=1 for
|
||||||
|
// long moves crossing the tile corner, 0 for short ones that don't.
|
||||||
|
int checkStep(int moveStyle, int timeBeforeStep, int crossCorner, int &timeAfterStep, int &recoverTurns,
|
||||||
|
std::uint32_t fromTile, std::uint32_t toTile, bool isCapture) const;
|
||||||
|
int getMyMoveStyle(int mix, int health) const;
|
||||||
|
int unit_MoveEx(int uix, int toLoc, int options = 0);
|
||||||
|
|
||||||
|
// Sea transport, obligatory call order: beginInitialize; [addLoad/
|
||||||
|
// addTransport/addDestination]*; endInitialize; [makeGroupPlan]*.
|
||||||
|
void seaTransport_BeginInitialize();
|
||||||
|
void seaTransport_EndInitialize();
|
||||||
|
void seaTransport_AddLoad(int uix);
|
||||||
|
void seaTransport_AddTransport(int uix);
|
||||||
|
void seaTransport_AddDestination(int loc);
|
||||||
|
bool seaTransport_MakeGroupPlan(GroupTransportPlan &transportPlan);
|
||||||
|
|
||||||
|
int currentMStrength(int domain) const;
|
||||||
|
|
||||||
|
static int nContinent, nOcean, nDistrict;
|
||||||
|
// water: ocean index, land: continent index, sorted by size; territory
|
||||||
|
// unpassable due to peace treaty divides a continent.
|
||||||
|
static std::array<int, lxmax * lymax> formation;
|
||||||
|
// index of coherent own territory, sorted by size.
|
||||||
|
static std::array<int, lxmax * lymax> district;
|
||||||
|
static std::array<int, nCmax> cityResult;
|
||||||
|
// Shared single-instance priority queue (mirrors Pile.pas being its own
|
||||||
|
// unit used directly by both ToolAI.pas and Barbarina.pas); protected so
|
||||||
|
// Barbarina can use it for its own pathfinding (attack/patrol scoring).
|
||||||
|
static Pile pile;
|
||||||
|
|
||||||
|
private:
|
||||||
|
// JobAssignment state
|
||||||
|
static int maxScore;
|
||||||
|
static std::array<std::uint8_t, lxmax * lymax> tileJob;
|
||||||
|
static std::array<std::uint8_t, lxmax * lymax> tileJobScore;
|
||||||
|
static std::array<int, nUmax> jobLocOfSettler; // ToAssign sentinel = find job
|
||||||
|
|
||||||
|
// SeaTransport state
|
||||||
|
static int transportMoveStyle, transportCapacity, nTransportLoad;
|
||||||
|
static bool initComplete, haveDestinations;
|
||||||
|
static std::array<int, nUmax> uixTransportLoad;
|
||||||
|
static std::array<int, nUmax> transportAvailable;
|
||||||
|
static std::array<std::int8_t, lxmax * lymax> turnsAfterLoad;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
#include "Cevo/AiModule.h"
|
||||||
|
|
||||||
|
#if defined(_WIN32)
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#include <windows.h>
|
||||||
|
#else
|
||||||
|
#include <dlfcn.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
AiModule::~AiModule()
|
||||||
|
{
|
||||||
|
unload();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool AiModule::load(const std::string &fileName)
|
||||||
|
{
|
||||||
|
unload();
|
||||||
|
|
||||||
|
#if defined(_WIN32)
|
||||||
|
m_handle = LoadLibraryA(fileName.c_str());
|
||||||
|
if (!m_handle) {
|
||||||
|
m_error = "LoadLibrary failed for " + fileName;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
m_client = reinterpret_cast<TClientCall>(reinterpret_cast<void *>(
|
||||||
|
GetProcAddress(static_cast<HMODULE>(m_handle), "client")));
|
||||||
|
#else
|
||||||
|
m_handle = dlopen(fileName.c_str(), RTLD_NOW);
|
||||||
|
if (!m_handle) {
|
||||||
|
m_error = dlerror();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
dlerror(); // clear any pending error before dlsym
|
||||||
|
m_client = reinterpret_cast<TClientCall>(dlsym(m_handle, "client"));
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if (!m_client) {
|
||||||
|
m_error = "module " + fileName + " does not export a \"client\" entry point";
|
||||||
|
unload();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void AiModule::unload()
|
||||||
|
{
|
||||||
|
if (m_handle) {
|
||||||
|
#if defined(_WIN32)
|
||||||
|
FreeLibrary(static_cast<HMODULE>(m_handle));
|
||||||
|
#else
|
||||||
|
dlclose(m_handle);
|
||||||
|
#endif
|
||||||
|
m_handle = nullptr;
|
||||||
|
}
|
||||||
|
m_client = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void AiModule::call(int command, int player, void *data) const
|
||||||
|
{
|
||||||
|
if (m_client)
|
||||||
|
m_client(command, player, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
#include "Cevo/AiModuleHost.h"
|
||||||
|
#include "Cevo/Geometry.h"
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
bool AiModuleHost::handle(int command, int player, void *data)
|
||||||
|
{
|
||||||
|
switch (command) {
|
||||||
|
case cmInitModule: {
|
||||||
|
auto &init = *static_cast<TInitModuleData *>(data);
|
||||||
|
CustomAI::setServerCall(init.Server);
|
||||||
|
init.DataSize = m_rwDataSize;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case cmNewGame:
|
||||||
|
case cmLoadGame: {
|
||||||
|
m_game = *static_cast<TNewGameData *>(data);
|
||||||
|
InitGeometry(m_game);
|
||||||
|
for (int p = nPl - 1; p >= 0; --p) {
|
||||||
|
if (m_game.RO[p]) {
|
||||||
|
m_ai[static_cast<size_t>(p)] = m_factory(p);
|
||||||
|
m_ai[static_cast<size_t>(p)]->bind(m_game.RO[p]);
|
||||||
|
m_ai[static_cast<size_t>(p)]->setDataDefaults();
|
||||||
|
} else {
|
||||||
|
m_ai[static_cast<size_t>(p)].reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m_defender = -1;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case cmGetReady:
|
||||||
|
for (auto &a : m_ai)
|
||||||
|
if (a)
|
||||||
|
a->setDataRandom();
|
||||||
|
return true;
|
||||||
|
case cmBreakGame:
|
||||||
|
for (auto &a : m_ai)
|
||||||
|
a.reset();
|
||||||
|
return true;
|
||||||
|
case cmShowAttacking:
|
||||||
|
case cmShowCapturing: {
|
||||||
|
const auto &move = *static_cast<const TShowMove *>(data);
|
||||||
|
const int y0 = move.FromLoc / m_game.lx;
|
||||||
|
const int toLoc =
|
||||||
|
(move.FromLoc + ((move.dx + (y0 & 1) + m_game.lx + m_game.lx) >> 1)) % m_game.lx +
|
||||||
|
m_game.lx * (y0 + move.dy);
|
||||||
|
if (player >= 0 && player < nPl && m_game.RO[player] && m_game.RO[player]->Map &&
|
||||||
|
((*m_game.RO[player]->Map)[toLoc] & fOwned) != 0) {
|
||||||
|
TUnitInfo unitInfo{};
|
||||||
|
unitInfo.Loc = move.FromLoc;
|
||||||
|
unitInfo.mix = static_cast<std::uint16_t>(move.mix);
|
||||||
|
unitInfo.emix = static_cast<std::uint16_t>(move.emix);
|
||||||
|
unitInfo.Owner = static_cast<std::uint8_t>(move.Owner);
|
||||||
|
unitInfo.Health = static_cast<std::int8_t>(move.Health);
|
||||||
|
unitInfo.Fuel = static_cast<std::int8_t>(move.Fuel);
|
||||||
|
unitInfo.Job = jNone;
|
||||||
|
unitInfo.Exp = static_cast<std::uint8_t>(move.Exp);
|
||||||
|
unitInfo.Load = static_cast<std::uint8_t>(move.Load);
|
||||||
|
unitInfo.Flags = static_cast<std::uint16_t>(move.Flags);
|
||||||
|
if (m_ai[static_cast<size_t>(player)]) {
|
||||||
|
if (command == cmShowAttacking)
|
||||||
|
m_ai[static_cast<size_t>(player)]->onBeforeEnemyAttack(unitInfo, toLoc, move.EndHealth,
|
||||||
|
move.EndHealthDef);
|
||||||
|
else
|
||||||
|
m_ai[static_cast<size_t>(player)]->onBeforeEnemyCapture(unitInfo, toLoc);
|
||||||
|
}
|
||||||
|
m_defender = player;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case cmShowAfterAttack:
|
||||||
|
if (player == m_defender) {
|
||||||
|
if (m_ai[static_cast<size_t>(player)])
|
||||||
|
m_ai[static_cast<size_t>(player)]->onAfterEnemyAttack();
|
||||||
|
m_defender = -1;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
case cmShowAfterMove:
|
||||||
|
if (player == m_defender) {
|
||||||
|
if (m_ai[static_cast<size_t>(player)])
|
||||||
|
m_ai[static_cast<size_t>(player)]->onAfterEnemyCapture();
|
||||||
|
m_defender = -1;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (player < 0 || player >= nPl || !m_ai[static_cast<size_t>(player)])
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (command == cmTurn || command == cmContinue || command == cmShowNego || command == cmShowEndContact ||
|
||||||
|
(command >= scContact && command <= scDipBreak)) {
|
||||||
|
m_ai[static_cast<size_t>(player)]->process(command, data);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
|
|
||||||
@@ -0,0 +1,574 @@
|
|||||||
|
#include "Cevo/CustomAI.h"
|
||||||
|
#include "Cevo/Geometry.h"
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
TServerCall CustomAI::s_server = nullptr;
|
||||||
|
|
||||||
|
CustomAI::~CustomAI()
|
||||||
|
{
|
||||||
|
rawServerCall(sSetDebugMap, 0, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CustomAI::bind(TPlayerContext *playerContext)
|
||||||
|
{
|
||||||
|
ro = playerContext;
|
||||||
|
map = *ro->Map;
|
||||||
|
myUnit = *ro->Un;
|
||||||
|
myCity = *ro->City;
|
||||||
|
myModel = *ro->Model;
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
int randomInt(int n) // Pascal's RTL Random(n); not ABI/determinism-relevant
|
||||||
|
{
|
||||||
|
return n > 0 ? std::rand() % n : 0;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void CustomAI::process(int command, void *data)
|
||||||
|
{
|
||||||
|
switch (command) {
|
||||||
|
case cmTurn:
|
||||||
|
case cmContinue: {
|
||||||
|
if ((ro->Alive & (1 << me)) == 0) { // I'm dead
|
||||||
|
rawServerCall(sTurn, 0, nullptr);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (command == cmTurn) {
|
||||||
|
cixStateImp.fill(-1);
|
||||||
|
for (int cix = 0; cix < ro->nCity; ++cix)
|
||||||
|
if (myCity[cix].Loc >= 0)
|
||||||
|
for (int iix = imPalace; iix <= imSpacePort; ++iix)
|
||||||
|
if (myCity[cix].Built[iix] > 0)
|
||||||
|
cixStateImp[static_cast<size_t>(iix - imPalace)] = cix;
|
||||||
|
if (ro->Happened & phChangeGov) {
|
||||||
|
const int newGov = chooseGovernment();
|
||||||
|
if (newGov > gAnarchy)
|
||||||
|
rawServerCall(sSetGovernment, newGov, nullptr);
|
||||||
|
}
|
||||||
|
haveTurned = false;
|
||||||
|
contacted.reset();
|
||||||
|
}
|
||||||
|
if (command == cmContinue && myAction == scContact) {
|
||||||
|
if (onNegoRejected_CancelTreaty())
|
||||||
|
if (ro->Treaty[opponent] >= trPeace)
|
||||||
|
rawServerCall(sCancelTreaty, 0, nullptr);
|
||||||
|
} else {
|
||||||
|
unwantedNego.reset();
|
||||||
|
}
|
||||||
|
opponent = -1;
|
||||||
|
for (;;) {
|
||||||
|
const NegoTime negoTime = haveTurned ? NegoTime::EndOfTurn : NegoTime::BeginOfTurn;
|
||||||
|
if (ro->Government != gAnarchy) {
|
||||||
|
for (int nation = 0; nation < nPl; ++nation) {
|
||||||
|
if (nation != me && (ro->Alive & (1 << nation)) != 0 && ro->Treaty[nation] >= trNone &&
|
||||||
|
!contacted[static_cast<size_t>(nation)] && !unwantedNego[static_cast<size_t>(nation)] &&
|
||||||
|
rawServerCall(scContact - sExecute + (nation << 4), 0, nullptr) >= rExecuted) {
|
||||||
|
if (wantNegotiation(nation, negoTime)) {
|
||||||
|
if (rawServerCall(scContact + (nation << 4), 0, nullptr) >= rExecuted) {
|
||||||
|
contacted.set(static_cast<size_t>(nation));
|
||||||
|
opponent = nation;
|
||||||
|
myAction = scContact;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
unwantedNego.set(static_cast<size_t>(nation));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (negoTime == NegoTime::BeginOfTurn) {
|
||||||
|
doTurn();
|
||||||
|
haveTurned = true;
|
||||||
|
contacted.reset();
|
||||||
|
unwantedNego.reset();
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ro->Happened & phTech) {
|
||||||
|
int newResearch = chooseResearchAdvance();
|
||||||
|
if (newResearch < 0) { // choose random research
|
||||||
|
int count = 0;
|
||||||
|
for (int ad = 0; ad < nAdv; ++ad)
|
||||||
|
if (advanceResearchable(ad)) {
|
||||||
|
++count;
|
||||||
|
if (randomInt(count) == 0)
|
||||||
|
newResearch = ad;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rawServerCall(sSetResearch, newResearch, nullptr);
|
||||||
|
}
|
||||||
|
rawServerCall(sTurn, 0, nullptr);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case scContact: {
|
||||||
|
const int nation = static_cast<int>(reinterpret_cast<std::intptr_t>(data));
|
||||||
|
if (wantNegotiation(nation, NegoTime::EnemyCalled)) {
|
||||||
|
rawServerCall(scDipStart, 0, nullptr);
|
||||||
|
opponent = nation;
|
||||||
|
myAction = scDipStart;
|
||||||
|
} else {
|
||||||
|
rawServerCall(scReject, 0, nullptr);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case scDipStart:
|
||||||
|
case scDipNotice:
|
||||||
|
case scDipAccept:
|
||||||
|
case scDipCancelTreaty:
|
||||||
|
case scDipOffer:
|
||||||
|
case scDipBreak: {
|
||||||
|
oppoAction = command;
|
||||||
|
if (command == scDipOffer)
|
||||||
|
oppoOffer = *static_cast<TOffer *>(data);
|
||||||
|
if (command == scDipStart) {
|
||||||
|
myLastAction = scContact;
|
||||||
|
} else {
|
||||||
|
myLastAction = myAction;
|
||||||
|
myLastOffer = myOffer;
|
||||||
|
}
|
||||||
|
if (oppoAction == scDipCancelTreaty || oppoAction == scDipBreak) {
|
||||||
|
myAction = scDipNotice;
|
||||||
|
} else {
|
||||||
|
myAction = scDipOffer;
|
||||||
|
myOffer.nDeliver = 0;
|
||||||
|
myOffer.nCost = 0;
|
||||||
|
}
|
||||||
|
doNegotiation();
|
||||||
|
if (myAction == scDipOffer)
|
||||||
|
rawServerCall(myAction, 0, &myOffer);
|
||||||
|
else
|
||||||
|
rawServerCall(myAction, 0, nullptr);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case cmShowEndContact:
|
||||||
|
opponent = -1;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- general functions ----
|
||||||
|
|
||||||
|
int CustomAI::researchCost() const
|
||||||
|
{
|
||||||
|
int result = 0;
|
||||||
|
rawServerCall(sGetTechCost, 0, &result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::changeAttitude(int nation, int attitude) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sSetAttitude + (nation << 4), attitude, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::revolution() const
|
||||||
|
{
|
||||||
|
return rawServerCall(sRevolution, 0, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::changeRates(int tax, int lux) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sSetRates, (tax / 10 & 0xF) + ((lux / 10 & 0xF) << 4), nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::prepareNewModel(int domain) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sCreateDevModel, domain, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::setNewModelFeature(int feature, int count) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sSetDevModelCap + (count << 4), feature, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::advanceResearchable(int advance) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sSetResearch - sExecute, advance, nullptr) >= rExecuted;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::advanceStealable(int advance) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sStealTech - sExecute, advance, nullptr) >= rExecuted;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::getJobProgress(int loc, TJobProgressData &jobProgress) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sGetJobProgress, loc, jobProgress) >= rExecuted;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::debugMessage(int level, const std::string &text) const
|
||||||
|
{
|
||||||
|
std::string prefixed = "P" + std::to_string(me) + " " + text;
|
||||||
|
if (prefixed.size() > 254)
|
||||||
|
prefixed.resize(254);
|
||||||
|
rawServerCall(sMessage, level, const_cast<char *>(prefixed.c_str()));
|
||||||
|
return true; // always true, so callers can write assert(debugMessage(...))
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::setDebugMap(void *debugMap) const
|
||||||
|
{
|
||||||
|
rawServerCall(sSetDebugMap, 0, debugMap);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- unit functions ----
|
||||||
|
|
||||||
|
int CustomAI::unit_FindMyDefender(int loc) const
|
||||||
|
{
|
||||||
|
int uix = -1;
|
||||||
|
return rawServerCall(sGetDefender, loc, &uix) < rExecuted ? -1 : uix;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_FindEnemyDefender(int loc) const
|
||||||
|
{
|
||||||
|
int euix = ro->nEnemyUn - 1;
|
||||||
|
while (euix >= 0 && (*ro->EnemyUn)[euix].Loc != loc)
|
||||||
|
--euix;
|
||||||
|
return euix;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CustomAI::stealAdvance()
|
||||||
|
{
|
||||||
|
int steal = chooseStealAdvance();
|
||||||
|
if (steal < 0) {
|
||||||
|
int count = 0;
|
||||||
|
for (int ad = 0; ad < nAdv; ++ad)
|
||||||
|
if (advanceStealable(ad)) {
|
||||||
|
++count;
|
||||||
|
if (randomInt(count) == 0)
|
||||||
|
steal = ad;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (steal >= 0)
|
||||||
|
rawServerCall(sStealTech, steal, nullptr);
|
||||||
|
ro->Happened &= ~phStealTech;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_Move(int uix, int toLoc)
|
||||||
|
{
|
||||||
|
TMoveAdviceData advice{};
|
||||||
|
advice.ToLoc = toLoc;
|
||||||
|
advice.MoreTurns = 9999;
|
||||||
|
advice.MaxHostile_MovementLeft = 100;
|
||||||
|
int result = rawServerCall(sGetMoveAdvice, uix, &advice);
|
||||||
|
if (result != eOK)
|
||||||
|
return result;
|
||||||
|
|
||||||
|
bool destinationReached = false;
|
||||||
|
int step = 0;
|
||||||
|
for (;;) {
|
||||||
|
if ((result & (rExecuted | rUnitRemoved)) == rExecuted) {
|
||||||
|
if (toLoc >= 0 && advice.MoreTurns == 0 && step == advice.nStep - 1 &&
|
||||||
|
((map[toLoc] & (fUnit | fOwned)) == fUnit || // attack
|
||||||
|
((map[toLoc] & (fCity | fOwned)) == fCity &&
|
||||||
|
(myModel[myUnit[uix].mix].Domain != dGround || // bombardment
|
||||||
|
(myModel[myUnit[uix].mix].Flags & mdCivil) != 0)))) { // can't capture
|
||||||
|
destinationReached = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (step == advice.nStep) {
|
||||||
|
destinationReached = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (step == advice.nStep || (result != eOK && result != eLoaded))
|
||||||
|
break;
|
||||||
|
|
||||||
|
result = rawServerCall(sMoveUnit + ((advice.dx[step] & 7) << 4) + ((advice.dy[step] & 7) << 7), uix,
|
||||||
|
nullptr);
|
||||||
|
++step;
|
||||||
|
if (ro->Happened & phStealTech)
|
||||||
|
stealAdvance();
|
||||||
|
}
|
||||||
|
if (destinationReached) {
|
||||||
|
if (advice.nStep == 25)
|
||||||
|
result = unit_Move(uix, toLoc); // Shinkansen
|
||||||
|
else if (advice.MoreTurns == 0)
|
||||||
|
result |= rLocationReached;
|
||||||
|
else
|
||||||
|
result |= rMoreTurns;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_Step(int uix, int toLoc)
|
||||||
|
{
|
||||||
|
int a, b;
|
||||||
|
Loc_to_ab(myUnit[uix].Loc, toLoc, a, b);
|
||||||
|
int result = rawServerCall(sMoveUnit + (((a - b) & 7) << 4) + (((a + b) & 7) << 7), uix, nullptr);
|
||||||
|
if (ro->Happened & phStealTech)
|
||||||
|
stealAdvance();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_Attack(int uix, int toLoc) const
|
||||||
|
{
|
||||||
|
int a, b;
|
||||||
|
Loc_to_ab(myUnit[uix].Loc, toLoc, a, b);
|
||||||
|
return rawServerCall(sMoveUnit + (((a - b) & 7) << 4) + (((a + b) & 7) << 7), uix, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_DoMission(int uix, int missionType, int toLoc) const
|
||||||
|
{
|
||||||
|
int result = rawServerCall(sSetSpyMission + (missionType << 4), 0, nullptr);
|
||||||
|
if (result < rExecuted)
|
||||||
|
return result;
|
||||||
|
int a, b;
|
||||||
|
Loc_to_ab(myUnit[uix].Loc, toLoc, a, b);
|
||||||
|
result =
|
||||||
|
rawServerCall(sMoveUnit - sExecute + (((a - b) & 7) << 4) + (((a + b) & 7) << 7), uix, nullptr);
|
||||||
|
if (result == eMissionDone)
|
||||||
|
result = rawServerCall(sMoveUnit + (((a - b) & 7) << 4) + (((a + b) & 7) << 7), uix, nullptr);
|
||||||
|
else if (result != eNoTime_Move && result != eTreaty && result != eNoTurn)
|
||||||
|
result = eInvalid; // not a special commando mission!
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::unit_MoveForecast(int uix, int toLoc, int &remainingMovement) const
|
||||||
|
{
|
||||||
|
TMoveAdviceData advice{};
|
||||||
|
advice.ToLoc = toLoc;
|
||||||
|
advice.MoreTurns = 0;
|
||||||
|
advice.MaxHostile_MovementLeft = 100;
|
||||||
|
if (rawServerCall(sGetMoveAdvice, uix, &advice) == eOK) {
|
||||||
|
remainingMovement = advice.MaxHostile_MovementLeft;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
remainingMovement = -1;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::unit_AttackForecast(int uix, int toLoc, int attackMovement, int &remainingHealth) const
|
||||||
|
{
|
||||||
|
remainingHealth = -0x100;
|
||||||
|
if (attackMovement < 0)
|
||||||
|
return false;
|
||||||
|
TBattleForecast forecast{};
|
||||||
|
forecast.pAtt = me;
|
||||||
|
forecast.mixAtt = myUnit[uix].mix;
|
||||||
|
forecast.HealthAtt = myUnit[uix].Health;
|
||||||
|
forecast.ExpAtt = myUnit[uix].Exp;
|
||||||
|
forecast.FlagsAtt = static_cast<int>(myUnit[uix].Flags);
|
||||||
|
forecast.Movement = attackMovement;
|
||||||
|
if (rawServerCall(sGetBattleForecast, toLoc, &forecast) < rExecuted)
|
||||||
|
return false;
|
||||||
|
remainingHealth = forecast.EndHealthAtt > 0 ? forecast.EndHealthAtt : -forecast.EndHealthDef;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::unit_DefenseForecast(int euix, int toLoc, int &remainingHealth) const
|
||||||
|
{
|
||||||
|
remainingHealth = 0x100;
|
||||||
|
const TUnitInfo &enemy = (*ro->EnemyUn)[euix];
|
||||||
|
TBattleForecast forecast{};
|
||||||
|
forecast.pAtt = enemy.Owner;
|
||||||
|
forecast.mixAtt = enemy.mix;
|
||||||
|
forecast.HealthAtt = enemy.Health;
|
||||||
|
forecast.ExpAtt = enemy.Exp;
|
||||||
|
forecast.FlagsAtt = enemy.Flags;
|
||||||
|
forecast.Movement = 100;
|
||||||
|
if (rawServerCall(sGetBattleForecast, toLoc, &forecast) < rExecuted)
|
||||||
|
return false;
|
||||||
|
remainingHealth = forecast.EndHealthDef > 0 ? forecast.EndHealthDef : -forecast.EndHealthAtt;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_Disband(int uix) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sRemoveUnit, uix, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_StartJob(int uix, int newJob) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sStartJob + (newJob << 4), uix, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_SetHomeHere(int uix) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sSetUnitHome, uix, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_Load(int uix) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sLoadUnit, uix, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_Unload(int uix) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sUnloadUnit, uix, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_SelectTransport(int uix) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sSelectTransport, uix, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::unit_AddToCity(int uix) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sAddToCity, uix, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- city functions ----
|
||||||
|
|
||||||
|
int CustomAI::city_FindMyCity(int loc) const
|
||||||
|
{
|
||||||
|
if ((map[loc] & (fCity | fOwned)) != (fCity | fOwned))
|
||||||
|
return -1;
|
||||||
|
int cix = ro->nCity - 1;
|
||||||
|
while (cix >= 0 && myCity[cix].Loc != loc)
|
||||||
|
--cix;
|
||||||
|
return cix;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_FindEnemyCity(int loc) const
|
||||||
|
{
|
||||||
|
if ((map[loc] & (fCity | fOwned)) != fCity)
|
||||||
|
return -1;
|
||||||
|
int ecix = ro->nEnemyCity - 1;
|
||||||
|
while (ecix >= 0 && (*ro->EnemyCity)[ecix].Loc != loc)
|
||||||
|
--ecix;
|
||||||
|
return ecix;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::city_HasProject(int cix) const
|
||||||
|
{
|
||||||
|
return (myCity[cix].Project & (cpImp + cpIndex)) != cpImp + imTrGoods;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_CurrentImprovementProject(int cix) const
|
||||||
|
{
|
||||||
|
if ((myCity[cix].Project & cpImp) == 0)
|
||||||
|
return -1;
|
||||||
|
const int result = myCity[cix].Project & cpIndex;
|
||||||
|
return result == imTrGoods ? -1 : result;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_CurrentUnitProject(int cix) const
|
||||||
|
{
|
||||||
|
return (myCity[cix].Project & cpImp) != 0 ? -1 : myCity[cix].Project & cpIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_GetTileInfo(int cix, int tileLoc, TTileInfo &tileInfo) const
|
||||||
|
{
|
||||||
|
tileInfo.ExplCity = cix;
|
||||||
|
return rawServerCall(sGetHypoCityTileInfo, tileLoc, &tileInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_GetReport(int cix, TCityReport &report) const
|
||||||
|
{
|
||||||
|
report.HypoTiles = -1;
|
||||||
|
report.HypoTax = -1;
|
||||||
|
report.HypoLux = -1;
|
||||||
|
return rawServerCall(sGetCityReport, cix, &report);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_GetHypoReport(int cix, int hypoTiles, int hypoTax, int hypoLux, TCityReport &report) const
|
||||||
|
{
|
||||||
|
report.HypoTiles = hypoTiles;
|
||||||
|
report.HypoTax = hypoTax;
|
||||||
|
report.HypoLux = hypoLux;
|
||||||
|
return rawServerCall(sGetCityReport, cix, &report);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_GetReportNew(int cix, TCityReportNew &report) const
|
||||||
|
{
|
||||||
|
report.HypoTiles = -1;
|
||||||
|
report.HypoTaxRate = -1;
|
||||||
|
report.HypoLuxuryRate = -1;
|
||||||
|
return rawServerCall(sGetCityReportNew, cix, &report);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_GetHypoReportNew(int cix, int hypoTiles, int hypoTaxRate, int hypoLuxuryRate,
|
||||||
|
TCityReportNew &report) const
|
||||||
|
{
|
||||||
|
report.HypoTiles = hypoTiles;
|
||||||
|
report.HypoTaxRate = hypoTaxRate;
|
||||||
|
report.HypoLuxuryRate = hypoLuxuryRate;
|
||||||
|
return rawServerCall(sGetCityReportNew, cix, &report);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_GetAreaInfo(int cix, TCityAreaInfo &areaInfo) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sGetCityAreaInfo, cix, &areaInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_StartUnitProduction(int cix, int mix) const
|
||||||
|
{
|
||||||
|
if ((myCity[cix].Project & (cpImp + cpIndex)) == mix)
|
||||||
|
return eNotChanged;
|
||||||
|
return rawServerCall(sSetCityProject, cix, &mix);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_StartEmigration(int cix, int mix, bool allowDisbandCity, bool asConscripts) const
|
||||||
|
{
|
||||||
|
int newProject = mix;
|
||||||
|
if (allowDisbandCity)
|
||||||
|
newProject |= cpDisbandCity;
|
||||||
|
if (asConscripts)
|
||||||
|
newProject |= cpConscripts;
|
||||||
|
return rawServerCall(sSetCityProject, cix, &newProject);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_StartImprovement(int cix, int iix) const
|
||||||
|
{
|
||||||
|
int newProject = iix + cpImp;
|
||||||
|
if ((myCity[cix].Project & (cpImp + cpIndex)) == newProject)
|
||||||
|
return eNotChanged;
|
||||||
|
return rawServerCall(sSetCityProject, cix, &newProject);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CustomAI::city_Improvable(int cix, int iix) const
|
||||||
|
{
|
||||||
|
int newProject = iix + cpImp;
|
||||||
|
return rawServerCall(sSetCityProject - sExecute, cix, &newProject) >= rExecuted;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_StopProduction(int cix) const
|
||||||
|
{
|
||||||
|
int newProject = imTrGoods + cpImp;
|
||||||
|
return rawServerCall(sSetCityProject, cix, &newProject);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_BuyProject(int cix) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sBuyCityProject, cix, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_SellImprovement(int cix, int iix) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sSellCityImprovement, cix, &iix);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_RebuildImprovement(int cix, int iix) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sRebuildCityImprovement, cix, &iix);
|
||||||
|
}
|
||||||
|
|
||||||
|
int CustomAI::city_SetTiles(int cix, int newTiles) const
|
||||||
|
{
|
||||||
|
return rawServerCall(sSetCityTiles, cix, &newTiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CustomAI::city_OptimizeTiles(int cix, std::uint32_t resourceWeights) const
|
||||||
|
{
|
||||||
|
TCityTileAdviceData advice{};
|
||||||
|
advice.ResourceWeights = resourceWeights;
|
||||||
|
rawServerCall(sGetCityTileAdvice, cix, &advice);
|
||||||
|
city_SetTiles(cix, static_cast<int>(advice.Tiles));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- negotiation ----
|
||||||
|
|
||||||
|
int CustomAI::nego_CheckMyAction() const
|
||||||
|
{
|
||||||
|
if (myAction == scDipOffer)
|
||||||
|
return rawServerCall(myAction - sExecute, 0, const_cast<TOffer *>(&myOffer));
|
||||||
|
return rawServerCall(myAction - sExecute, 0, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
#include "Cevo/Geometry.h"
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
int g_lx = 1;
|
||||||
|
int g_ly = 1;
|
||||||
|
int g_mapSize = 1;
|
||||||
|
std::int32_t g_difficulty[nPl] = {};
|
||||||
|
|
||||||
|
constexpr int ab_v8[9] = { 5, 6, 7, 4, -1, 0, 3, 2, 1 }; // index = 3*B + A + 4
|
||||||
|
constexpr int v8_a[8] = { 1, 1, 0, -1, -1, -1, 0, 1 };
|
||||||
|
constexpr int v8_b[8] = { 0, 1, 1, 1, 0, -1, -1, -1 };
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void InitGeometry(const TNewGameData &newGameData)
|
||||||
|
{
|
||||||
|
g_lx = newGameData.lx;
|
||||||
|
g_ly = newGameData.ly;
|
||||||
|
g_mapSize = g_lx * g_ly;
|
||||||
|
for (int i = 0; i < nPl; ++i)
|
||||||
|
g_difficulty[i] = newGameData.Difficulty[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
int MapWidth() { return g_lx; }
|
||||||
|
int MapHeight() { return g_ly; }
|
||||||
|
int MapSize() { return g_mapSize; }
|
||||||
|
int Difficulty(int nation) { return g_difficulty[nation]; }
|
||||||
|
|
||||||
|
void ab_to_Loc(int Loc0, int A, int B, int &Loc)
|
||||||
|
{
|
||||||
|
const int y0 = Loc0 / g_lx;
|
||||||
|
Loc = (Loc0 + ((A - B + (y0 & 1) + g_lx + g_lx) >> 1)) % g_lx + g_lx * (y0 + A + B);
|
||||||
|
if (Loc >= g_mapSize)
|
||||||
|
Loc = -0x1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Loc_to_ab(int Loc0, int Loc, int &A, int &B)
|
||||||
|
{
|
||||||
|
const int dx = ((Loc % g_lx * 2 + (Loc / g_lx & 1)) - (Loc0 % g_lx * 2 + (Loc0 / g_lx & 1)) + 3 * g_lx) %
|
||||||
|
(2 * g_lx) -
|
||||||
|
g_lx;
|
||||||
|
const int dy = Loc / g_lx - Loc0 / g_lx;
|
||||||
|
A = (dx + dy) / 2;
|
||||||
|
B = (dy - dx) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ab_to_V8(int A, int B, int &V8)
|
||||||
|
{
|
||||||
|
V8 = ab_v8[3 * B + A + 4];
|
||||||
|
}
|
||||||
|
|
||||||
|
void V8_to_ab(int V8, int &A, int &B)
|
||||||
|
{
|
||||||
|
A = v8_a[V8];
|
||||||
|
B = v8_b[V8];
|
||||||
|
}
|
||||||
|
|
||||||
|
void ab_to_V21(int A, int B, int &V21)
|
||||||
|
{
|
||||||
|
V21 = ((A + B + 3) << 2) + ((A - B + 3) >> 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void V21_to_ab(int V21, int &A, int &B)
|
||||||
|
{
|
||||||
|
const int dy = (V21 >> 2) - 3;
|
||||||
|
const int dx = (((V21 & 3) << 1) - 3) + ((dy + 3) & 1);
|
||||||
|
A = (dx + dy) / 2;
|
||||||
|
B = (dy - dx) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
void V8_to_Loc(int Loc0, TVicinity8Loc &VicinityLoc)
|
||||||
|
{
|
||||||
|
const int lx = g_lx;
|
||||||
|
const int y0 = Loc0 / lx;
|
||||||
|
const int x0 = Loc0 - y0 * lx;
|
||||||
|
VicinityLoc[1] = Loc0 + lx * 2;
|
||||||
|
VicinityLoc[3] = Loc0 - 1;
|
||||||
|
VicinityLoc[5] = Loc0 - lx * 2;
|
||||||
|
VicinityLoc[7] = Loc0 + 1;
|
||||||
|
Loc0 += y0 & 1;
|
||||||
|
VicinityLoc[0] = Loc0 + lx;
|
||||||
|
VicinityLoc[2] = Loc0 + lx - 1;
|
||||||
|
VicinityLoc[4] = Loc0 - lx - 1;
|
||||||
|
VicinityLoc[6] = Loc0 - lx;
|
||||||
|
|
||||||
|
// world is round!
|
||||||
|
if (x0 < lx - 1) {
|
||||||
|
if (x0 == 0) {
|
||||||
|
VicinityLoc[3] += lx;
|
||||||
|
if ((y0 & 1) == 0) {
|
||||||
|
VicinityLoc[2] += lx;
|
||||||
|
VicinityLoc[4] += lx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
VicinityLoc[7] -= lx;
|
||||||
|
if ((y0 & 1) == 1) {
|
||||||
|
VicinityLoc[0] -= lx;
|
||||||
|
VicinityLoc[6] -= lx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// check south pole
|
||||||
|
switch (g_ly - y0) {
|
||||||
|
case 1:
|
||||||
|
VicinityLoc[0] = -0x1000;
|
||||||
|
VicinityLoc[1] = -0x1000;
|
||||||
|
VicinityLoc[2] = -0x1000;
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
VicinityLoc[1] = -0x1000;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void V21_to_Loc(int Loc0, TVicinity21Loc &VicinityLoc)
|
||||||
|
{
|
||||||
|
const int y0 = Loc0 / g_lx;
|
||||||
|
int xComp0 = Loc0 - y0 * g_lx - 1;
|
||||||
|
int xCompSwitch = xComp0 - 1 + (y0 & 1);
|
||||||
|
if (xComp0 < 0)
|
||||||
|
xComp0 += g_lx;
|
||||||
|
if (xCompSwitch < 0)
|
||||||
|
xCompSwitch += g_lx;
|
||||||
|
xCompSwitch ^= xComp0;
|
||||||
|
int yComp = g_lx * (y0 - 3);
|
||||||
|
int *dst = VicinityLoc;
|
||||||
|
unsigned bit = 1;
|
||||||
|
for (int dy = 0; dy <= 6; ++dy) {
|
||||||
|
if (yComp < g_mapSize) {
|
||||||
|
xComp0 ^= xCompSwitch;
|
||||||
|
int xComp = xComp0;
|
||||||
|
for (int dx = 0; dx <= 3; ++dx) {
|
||||||
|
*dst = (bit & 0x67F7F76u) ? xComp + yComp : -1;
|
||||||
|
++xComp;
|
||||||
|
if (xComp >= g_lx)
|
||||||
|
xComp -= g_lx;
|
||||||
|
++dst;
|
||||||
|
bit <<= 1;
|
||||||
|
}
|
||||||
|
yComp += g_lx;
|
||||||
|
} else {
|
||||||
|
for (int dx = 0; dx <= 3; ++dx) {
|
||||||
|
*dst = -0x1000;
|
||||||
|
++dst;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int Distance(int Loc0, int Loc1)
|
||||||
|
{
|
||||||
|
int A, B;
|
||||||
|
Loc_to_ab(Loc0, Loc1, A, B);
|
||||||
|
const int dx = std::abs(A - B);
|
||||||
|
const int dy = std::abs(A + B);
|
||||||
|
return dx + dy + (std::abs(dx - dy) >> 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
#include "Cevo/Pile.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cassert>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
void Pile::create(int size)
|
||||||
|
{
|
||||||
|
assert(size <= MaxSize);
|
||||||
|
if (n_ != 0 || size > currentSize_) {
|
||||||
|
std::fill_n(ix_, size, -1);
|
||||||
|
n_ = 0;
|
||||||
|
}
|
||||||
|
currentSize_ = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Pile::empty()
|
||||||
|
{
|
||||||
|
if (n_ != 0) {
|
||||||
|
std::fill_n(ix_, currentSize_, -1);
|
||||||
|
n_ = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parent(i) = (i-1)/2.
|
||||||
|
bool Pile::put(int item, int value) // O(lg(n))
|
||||||
|
{
|
||||||
|
assert(item < currentSize_);
|
||||||
|
int i = ix_[item];
|
||||||
|
if (i >= 0) {
|
||||||
|
if (bh_[i].value <= value)
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
i = n_;
|
||||||
|
++n_;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i > 0) {
|
||||||
|
const int j = (i - 1) >> 1; // Parent(i) = (i-1)/2
|
||||||
|
if (value >= bh_[j].value)
|
||||||
|
break;
|
||||||
|
bh_[i] = bh_[j];
|
||||||
|
ix_[bh_[i].item] = i;
|
||||||
|
i = j;
|
||||||
|
}
|
||||||
|
// Insert the new item at the insertion point found.
|
||||||
|
bh_[i].value = value;
|
||||||
|
bh_[i].item = item;
|
||||||
|
ix_[bh_[i].item] = i;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Pile::testPut(int item, int value) const
|
||||||
|
{
|
||||||
|
assert(item < currentSize_);
|
||||||
|
const int i = ix_[item];
|
||||||
|
return i < 0 || bh_[i].value > value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Left(i) = 2*i+1, Right(i) = Left(i)+1.
|
||||||
|
bool Pile::get(int &item, int &value) // O(lg(n))
|
||||||
|
{
|
||||||
|
if (n_ == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
item = bh_[0].item;
|
||||||
|
value = bh_[0].value;
|
||||||
|
ix_[item] = -1;
|
||||||
|
|
||||||
|
--n_;
|
||||||
|
if (n_ > 0) {
|
||||||
|
const HeapItem last = bh_[n_];
|
||||||
|
int i = 0;
|
||||||
|
int j = 1;
|
||||||
|
while (j < n_) {
|
||||||
|
if (j < n_ - 1 && bh_[j].value > bh_[j + 1].value)
|
||||||
|
++j; // Right(i) = Left(i)+1
|
||||||
|
if (last.value <= bh_[j].value)
|
||||||
|
break;
|
||||||
|
|
||||||
|
bh_[i] = bh_[j];
|
||||||
|
ix_[bh_[i].item] = i;
|
||||||
|
i = j;
|
||||||
|
j = (j << 1) + 1; // Left(j) = 2*j+1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert the root in the correct place in the heap.
|
||||||
|
bh_[i] = last;
|
||||||
|
ix_[last.item] = i;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
#include "Cevo/Protocol.h"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
void MakeUnitInfo(int P, const TUn &U, TUnitInfo &ui)
|
||||||
|
{
|
||||||
|
ui.Owner = static_cast<std::uint8_t>(P);
|
||||||
|
ui.Loc = U.Loc;
|
||||||
|
ui.Health = U.Health;
|
||||||
|
ui.Fuel = U.Fuel;
|
||||||
|
ui.Job = U.Job;
|
||||||
|
ui.Exp = U.Exp;
|
||||||
|
ui.Load = static_cast<std::uint8_t>(U.TroopLoad + U.AirLoad);
|
||||||
|
ui.mix = static_cast<std::uint16_t>(U.mix);
|
||||||
|
ui.Flags = static_cast<std::uint16_t>(U.Flags);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MakeModelInfo(int P, int mix, const TModel &M, TModelInfo &mi)
|
||||||
|
{
|
||||||
|
mi.Owner = static_cast<std::uint16_t>(P);
|
||||||
|
mi.mix = static_cast<std::uint16_t>(mix);
|
||||||
|
mi.ID = M.ID;
|
||||||
|
mi.Domain = M.Domain;
|
||||||
|
// Important for IsSameModel(): enemy-developed models compare equal to
|
||||||
|
// the same capability developed by ourselves.
|
||||||
|
mi.Kind = M.Kind == mkEnemyDeveloped ? mkSelfDeveloped : M.Kind;
|
||||||
|
mi.Attack = M.Attack;
|
||||||
|
mi.Defense = M.Defense;
|
||||||
|
mi.Speed = M.Speed;
|
||||||
|
mi.Cost = M.Cost;
|
||||||
|
if (mi.Domain == dAir) {
|
||||||
|
mi.TTrans = static_cast<std::uint8_t>(M.Cap[mcAirTrans] * M.MTrans);
|
||||||
|
mi.ATrans_Fuel = M.Cap[mcFuel];
|
||||||
|
} else {
|
||||||
|
mi.TTrans = static_cast<std::uint8_t>(M.Cap[mcSeaTrans] * M.MTrans);
|
||||||
|
mi.ATrans_Fuel = static_cast<std::uint8_t>(M.Cap[mcCarrier] * M.MTrans);
|
||||||
|
}
|
||||||
|
mi.Bombs = static_cast<std::uint16_t>(M.Cap[mcBombs] * M.MStrength * 2);
|
||||||
|
mi.Cap = 0;
|
||||||
|
for (int i = mcFirstNonCap; i < nFeature; ++i)
|
||||||
|
if (M.Cap[i] > 0)
|
||||||
|
mi.Cap |= 1u << (i - mcFirstNonCap);
|
||||||
|
mi.MaxUpgrade = 0;
|
||||||
|
for (int i = 1; i < nUpgrade; ++i)
|
||||||
|
if (M.Upgrades & (1u << i))
|
||||||
|
mi.MaxUpgrade = static_cast<std::uint8_t>(i);
|
||||||
|
mi.Weight = M.Weight;
|
||||||
|
mi.Lost = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool IsSameModel(const TModelInfo &mi1, const TModelInfo &mi2)
|
||||||
|
{
|
||||||
|
// Mirrors the original's raw-word comparison: compares everything up to
|
||||||
|
// (and including) Cap, ignoring ID (only its high word, Kind+Domain, is
|
||||||
|
// compared) and ignoring MaxUpgrade/Weight/Lost entirely. Relies on
|
||||||
|
// TModelInfo having zero padding before Cap, which it does (every field
|
||||||
|
// already falls on its natural alignment boundary).
|
||||||
|
static_assert(offsetof(TModelInfo, Cap) == 20, "TModelInfo layout changed");
|
||||||
|
const auto *compare1 = reinterpret_cast<const std::uint32_t *>(&mi1);
|
||||||
|
const auto *compare2 = reinterpret_cast<const std::uint32_t *>(&mi2);
|
||||||
|
return (compare1[1] & 0xFFFF0000u) == (compare2[1] & 0xFFFF0000u) && compare1[2] == compare2[2] &&
|
||||||
|
compare1[3] == compare2[3] && compare1[4] == compare2[4] && compare1[5] == compare2[5];
|
||||||
|
}
|
||||||
|
|
||||||
|
int SpecialTile(int Loc, int TerrType, int lx)
|
||||||
|
{
|
||||||
|
if (TerrType == fOcean)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
const int y = Loc / lx;
|
||||||
|
const int x = Loc - y * lx;
|
||||||
|
if (TerrType == fGrass) { // formula for productive grassland
|
||||||
|
return (((lymax + x - (y >> 1)) >> 1) + x + ((y + 1) >> 1)) % 2 != 0 ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// formula for special resources
|
||||||
|
const int a = 4 * x - y + 9980;
|
||||||
|
const int qx = a / 10;
|
||||||
|
if (qx * 10 == a && (qx & 3) != 0) {
|
||||||
|
const int qy = (y + x) / 5;
|
||||||
|
if ((qy & 3) != (qx >> 2 & 1) * 2) {
|
||||||
|
if (TerrType == fArctic || TerrType == fSwamp)
|
||||||
|
return 1;
|
||||||
|
if (TerrType == fShore) {
|
||||||
|
if ((qx + qy) % 2 == 0)
|
||||||
|
return (qx & 3) == 2 ? 2 : 1;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return (qx + qy) % 2 + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int GetCommandDataSize(TCommand Command)
|
||||||
|
{
|
||||||
|
switch (Command) {
|
||||||
|
case cmInitModule:
|
||||||
|
return sizeof(TInitModuleData);
|
||||||
|
case cmGetReady:
|
||||||
|
return 0;
|
||||||
|
case cmTurn:
|
||||||
|
return 0;
|
||||||
|
case cmShowTurnChange:
|
||||||
|
return sizeof(std::int32_t);
|
||||||
|
case cmShowNego:
|
||||||
|
return sizeof(TShowNegoData);
|
||||||
|
case cmNewGame:
|
||||||
|
case cmLoadGame:
|
||||||
|
case cmMovie:
|
||||||
|
case cmNewMap:
|
||||||
|
return sizeof(TNewGameData);
|
||||||
|
case cmShowShipChange:
|
||||||
|
return sizeof(TShowShipChange);
|
||||||
|
case cmShowGreatLibTech:
|
||||||
|
return sizeof(std::int32_t);
|
||||||
|
case cmShowCityChanged:
|
||||||
|
return sizeof(std::int32_t);
|
||||||
|
case cmShowPeaceViolation:
|
||||||
|
return sizeof(std::int32_t);
|
||||||
|
case cmShowMoving:
|
||||||
|
return sizeof(TShowMove);
|
||||||
|
case cmShowUnitChanged:
|
||||||
|
return sizeof(std::int32_t);
|
||||||
|
case cmShowMissionResult:
|
||||||
|
return sizeof(std::uint32_t);
|
||||||
|
case cmShowAfterMove:
|
||||||
|
return sizeof(std::int32_t);
|
||||||
|
case cmShowAfterAttack:
|
||||||
|
return sizeof(std::int32_t);
|
||||||
|
case cmShowSupportAllianceAgainst:
|
||||||
|
return sizeof(std::int32_t);
|
||||||
|
case cmShowCancelTreatyByAlliance:
|
||||||
|
return sizeof(std::int32_t);
|
||||||
|
case cmShowEndContact:
|
||||||
|
return 0;
|
||||||
|
case cmShowGame:
|
||||||
|
return 0;
|
||||||
|
default:
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# StdAI: concrete AI "brain" plugin built on top of ../ (the generic
|
||||||
|
# AiModule/AiModuleHost/CustomAI/ToolAI protocol layer). Ported from
|
||||||
|
# perso/cevo/AI/StdAI/{Barbarina.pas, AI.pas} - class Cevo::AI (TAI) derives
|
||||||
|
# from Cevo::Barbarina (TBarbarina) derives from Cevo::ToolAI.
|
||||||
|
#
|
||||||
|
# Built as its own shared library (not linked into the cevo-evo executable):
|
||||||
|
# like the original's StdAI.dll/.so, it is meant to be loaded dynamically at
|
||||||
|
# runtime (via Cevo::AiModule) alongside other precompiled AI modules.
|
||||||
|
|
||||||
|
set(STDAI_HEADERS
|
||||||
|
include/Cevo/AI.h
|
||||||
|
include/Cevo/Barbarina.h
|
||||||
|
)
|
||||||
|
|
||||||
|
set(STDAI_SOURCES
|
||||||
|
src/AI.cpp
|
||||||
|
src/Barbarina.cpp
|
||||||
|
src/StdAIModule.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
add_library(stdai SHARED ${STDAI_SOURCES} ${STDAI_HEADERS})
|
||||||
|
|
||||||
|
target_include_directories(stdai PRIVATE
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(stdai PRIVATE cevoai)
|
||||||
|
|
||||||
|
set_target_properties(stdai PROPERTIES
|
||||||
|
CXX_STANDARD 17
|
||||||
|
CXX_STANDARD_REQUIRED ON
|
||||||
|
PREFIX ""
|
||||||
|
)
|
||||||
|
|
||||||
|
include(GNUInstallDirs)
|
||||||
|
install(TARGETS stdai
|
||||||
|
LIBRARY DESTINATION ${CMAKE_INSTALL_AIDIR}
|
||||||
|
RUNTIME DESTINATION ${CMAKE_INSTALL_AIDIR}
|
||||||
|
)
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Cevo/Barbarina.h"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
constexpr int nAIModelCat = 4;
|
||||||
|
constexpr int mctNone = -1;
|
||||||
|
constexpr int mctGroundDefender = 0;
|
||||||
|
constexpr int mctGroundAttacker = 1;
|
||||||
|
constexpr int mctTransport = 2;
|
||||||
|
constexpr int mctCruiser = 3;
|
||||||
|
|
||||||
|
constexpr int nRequestedTechs = 48;
|
||||||
|
|
||||||
|
enum class Suggestion { Contact, Peace, Friendly };
|
||||||
|
|
||||||
|
// Raw per-nation scratch memory the host allocates (rwDataSize bytes) and
|
||||||
|
// hands back via TPlayerContext::Data - reinterpreted in place, NOT
|
||||||
|
// constructed, so these fields must NOT rely on default member
|
||||||
|
// initializers (see setDataDefaults(), which is what actually initializes
|
||||||
|
// a fresh block on cmNewGame, mirroring the original's SetDataDefaults).
|
||||||
|
struct TPersistentData {
|
||||||
|
int LastResearchTech;
|
||||||
|
int BehaviorFlags;
|
||||||
|
int TheologyPartner;
|
||||||
|
std::int16_t RejectTurn[3][16]; // [Suggestion][0..15]
|
||||||
|
int RequestedTechs[nRequestedTechs]; // ad + p shl 8 + Turn shl 16
|
||||||
|
};
|
||||||
|
|
||||||
|
// C++ equivalent of AI.pas's TAI: the actual StdAI decision heuristics
|
||||||
|
// (research strategy, terraforming/settlers, production, combat/patrol,
|
||||||
|
// diplomacy), built on top of Barbarina's "barbarian mode" personality.
|
||||||
|
// This is the final/top-level AI class a StdAI plugin module instantiates.
|
||||||
|
class AI : public Barbarina {
|
||||||
|
public:
|
||||||
|
explicit AI(int nation);
|
||||||
|
|
||||||
|
void setDataDefaults() override;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
TPersistentData *data = nullptr;
|
||||||
|
int warNations = 0, bombardingNations = 0;
|
||||||
|
int mixSettlers = 0, mixCaravan = 0, mixTownGuard = 0, mixSlaves = 0, mixMilitia = 0, mixCruiser = 0;
|
||||||
|
int oceanWithShip = 0;
|
||||||
|
enum class AINegoCause { Routine, CheckBarbarina };
|
||||||
|
AINegoCause negoCause = AINegoCause::Routine;
|
||||||
|
std::array<int, maxCOD> settlerSurplus{};
|
||||||
|
std::array<int, maxCOD> uixPatrol{};
|
||||||
|
|
||||||
|
// Hides Barbarina's own continentPresence/oceanPresence (same name
|
||||||
|
// collision as the original Pascal: TAI declares its own, separate from
|
||||||
|
// TBarbarina's private fields).
|
||||||
|
std::array<int, maxCOD> continentPresence{};
|
||||||
|
std::array<int, maxCOD> oceanPresence{};
|
||||||
|
std::array<std::array<int, mctGroundAttacker - mctGroundDefender + 1>, maxCOD> unitLack{};
|
||||||
|
|
||||||
|
std::array<int, nPl> totalPopulation{};
|
||||||
|
std::array<std::array<int, maxCOD>, nPl> continentPopulation{};
|
||||||
|
std::array<int, maxCOD> districtPopulation{};
|
||||||
|
|
||||||
|
std::array<int, nMmax> modelCat{};
|
||||||
|
std::array<int, nMmax> modelQuality{};
|
||||||
|
std::array<int, nAIModelCat> modelBestQuality{};
|
||||||
|
|
||||||
|
std::array<int, nAdv> advanceValue{};
|
||||||
|
bool advanceValuesSet = false;
|
||||||
|
|
||||||
|
void doTurn() override;
|
||||||
|
void doNegotiation() override;
|
||||||
|
int chooseResearchAdvance() override;
|
||||||
|
int chooseStealAdvance() override;
|
||||||
|
int chooseGovernment() override;
|
||||||
|
bool wantNegotiation(int nation, NegoTime negoTime) override;
|
||||||
|
bool onNegoRejected_CancelTreaty() override;
|
||||||
|
|
||||||
|
void findBestTrade(int nation, int &adWanted, int &adGiveAway);
|
||||||
|
void checkGender();
|
||||||
|
// Hides Barbarina::analyzeMap()/ToolAI::analyzeMap() - calls
|
||||||
|
// Barbarina::analyzeMap() first (matches the original's `inherited;`).
|
||||||
|
// NOTE: ToolAI::analyzeMap() (Formation[]/District[] computation) is
|
||||||
|
// NEVER called anywhere in the original class hierarchy either - see
|
||||||
|
// AI.cpp's comment on this for a confirmed-via-source-grep explanation
|
||||||
|
// (genuine dead code / latent bug in upstream StdAI, ported faithfully).
|
||||||
|
void analyzeMap();
|
||||||
|
void collectModelCatStat();
|
||||||
|
// Hides Barbarina::attackAndPatrol() - a completely different algorithm.
|
||||||
|
void attackAndPatrol();
|
||||||
|
void moveUnitsHome();
|
||||||
|
void checkAttack(int uix);
|
||||||
|
void patrol(int uix);
|
||||||
|
// Hides Barbarina::barbarina_SetCityProduction() (different method name,
|
||||||
|
// no actual collision, but still TAI's own top-level production logic).
|
||||||
|
void setCityProduction();
|
||||||
|
void setAdvanceValues();
|
||||||
|
bool havePort() const;
|
||||||
|
|
||||||
|
void rateModel(const TModelInfo &mi, int &category, int &quality) const;
|
||||||
|
void rateMyModel(int mix, int &category, int &quality) const;
|
||||||
|
bool isBetterModel(const TModelInfo &mi) const;
|
||||||
|
|
||||||
|
void tileWorkPlan(int loc, int cix, int &value, int &nextJob, int &totalWork);
|
||||||
|
void processSettlers();
|
||||||
|
|
||||||
|
int mostWanted(int nation, int adGiveAway) const;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Cevo/ToolAI.h"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
constexpr int nModelCategory = 4;
|
||||||
|
constexpr int ctGroundSlow = 0;
|
||||||
|
constexpr int ctGroundFast = 1;
|
||||||
|
constexpr int ctSeaTrans = 2;
|
||||||
|
constexpr int ctSeaArt = 3;
|
||||||
|
|
||||||
|
constexpr int maxCOD = 256;
|
||||||
|
constexpr int maxModern = 16;
|
||||||
|
// maximum number of modern resources of one type being managed (for
|
||||||
|
// designed maps only, number is 2 in standard game)
|
||||||
|
|
||||||
|
struct ColonyShipPlanPart {
|
||||||
|
int cixProducing = -1;
|
||||||
|
int LocResource[maxModern] = {};
|
||||||
|
int nLocResource = 0;
|
||||||
|
int LocFoundCity[maxModern] = {};
|
||||||
|
int nLocFoundCity = 0;
|
||||||
|
};
|
||||||
|
using TColonyShipPlan = std::array<ColonyShipPlanPart, nShipPart>;
|
||||||
|
|
||||||
|
// C++ equivalent of Barbarina.pas's TBarbarina: the "barbarian" AI
|
||||||
|
// personality StdAI's TAI is built directly on top of (required base class,
|
||||||
|
// not an optional/alternate mode).
|
||||||
|
class Barbarina : public ToolAI {
|
||||||
|
public:
|
||||||
|
explicit Barbarina(int nation);
|
||||||
|
|
||||||
|
protected:
|
||||||
|
TColonyShipPlan ColonyShipPlan;
|
||||||
|
|
||||||
|
bool barbarina_GoHidden() const; // whether we should prepare for barbarina mode
|
||||||
|
bool barbarina_Go() const; // whether we should switch to barbarina mode now
|
||||||
|
void barbarina_DoTurn();
|
||||||
|
void barbarina_SetCityProduction();
|
||||||
|
int barbarina_ChooseResearchAdvance();
|
||||||
|
bool barbarina_WantCheckNegotiation(int nation) const;
|
||||||
|
void barbarina_DoCheckNegotiation();
|
||||||
|
bool barbarina_WantNegotiation(int nation, NegoTime negoTime);
|
||||||
|
void barbarina_DoNegotiation();
|
||||||
|
void makeColonyShipPlan();
|
||||||
|
// Hides (not overrides) ToolAI::analyzeMap(), matching the original's
|
||||||
|
// method hiding - TBarbarina.AnalyzeMap computes continent/ocean
|
||||||
|
// *presence* given Formation/District already populated; its own
|
||||||
|
// `// inherited;` is commented out in the original too. Protected (not
|
||||||
|
// private) so AI::analyzeMap() can call Barbarina::analyzeMap()
|
||||||
|
// explicitly, mirroring the original's `inherited;`.
|
||||||
|
void analyzeMap();
|
||||||
|
|
||||||
|
private:
|
||||||
|
int turnOfMapAnalysis = -1;
|
||||||
|
int neighbours = 0;
|
||||||
|
std::array<int, maxCOD> continentPresence{};
|
||||||
|
std::array<int, maxCOD> oceanPresence{};
|
||||||
|
std::array<int, maxCOD> continentSize{};
|
||||||
|
std::array<int, maxCOD> oceanSize{};
|
||||||
|
std::array<int, nModelCategory> mixBest{};
|
||||||
|
enum class NegoCauseKind { CancelTreaty };
|
||||||
|
NegoCauseKind negoCause = NegoCauseKind::CancelTreaty;
|
||||||
|
|
||||||
|
bool isModelAvailable(int rmix) const;
|
||||||
|
void findBestModels();
|
||||||
|
void rateAttack(int uix);
|
||||||
|
bool doAttack(int uix, int attackLoc);
|
||||||
|
bool processMove(int uix);
|
||||||
|
void attackAndPatrol();
|
||||||
|
|
||||||
|
static constexpr int neumax = 4096;
|
||||||
|
static std::array<bool, nUmax> moved;
|
||||||
|
static std::array<std::uint8_t, lxmax * lymax> unitPresence;
|
||||||
|
static std::array<std::int16_t, lxmax * lymax> euixMap;
|
||||||
|
static std::array<std::int16_t, neumax> uixAttack;
|
||||||
|
static std::array<int, neumax> attackScore;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
// Plugin entry point: exports the "client" C-ABI function a host (or this
|
||||||
|
// project's own cevo-evo, via AiModule) loads via dlopen/LoadLibrary to
|
||||||
|
// drive the StdAI brain. Mirrors StdAI.lpr's `exports client;` in the
|
||||||
|
// original Pascal project - everything else is implemented by the generic
|
||||||
|
// AiModuleHost (see ../../include/Cevo/AiModuleHost.h) plus Cevo::AI.
|
||||||
|
|
||||||
|
#include "Cevo/AI.h"
|
||||||
|
#include "Cevo/AiModuleHost.h"
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Cevo::AiModuleHost host([](int nation) { return std::make_unique<Cevo::AI>(nation); },
|
||||||
|
sizeof(Cevo::TPersistentData));
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
CEVO_EXPORT_AI_CLIENT(host)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!DOCTYPE TS>
|
||||||
|
<TS version="2.1" language="en_US"></TS>
|
||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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>
|
||||||
@@ -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
|
||||||
@@ -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>
|
||||||
@@ -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
|
||||||
@@ -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>
|
||||||
@@ -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
|
||||||
@@ -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>
|
||||||
@@ -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
|
||||||
@@ -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>
|
||||||
@@ -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
|
||||||
@@ -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>
|
||||||
@@ -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
|
||||||
@@ -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>
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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 *)
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#include "Cevo/FormBase.h"
|
||||||
|
|
||||||
|
namespace Cevo {
|
||||||
|
|
||||||
|
FormBase::FormBase(QWidget *parent) : QDialog(parent) {}
|
||||||
|
|
||||||
|
} // namespace Cevo
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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 "e)
|
||||||
|
{
|
||||||
|
return text.isEmpty() ? text : quote + text + quote;
|
||||||
|
}
|
||||||
|
|
||||||
|
QString escapeHtml(const QString &text)
|
||||||
|
{
|
||||||
|
QString result = text;
|
||||||
|
result.replace('&', QStringLiteral("&")); // must come first
|
||||||
|
result.replace('<', QStringLiteral("<"));
|
||||||
|
result.replace('>', QStringLiteral(">"));
|
||||||
|
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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
#include "mainwindow.h"
|
||||||
|
|
||||||
|
#include <QApplication>
|
||||||
|
#include <QLocale>
|
||||||
|
#include <QTranslator>
|
||||||
|
|
||||||
|
int main(int argc, char *argv[])
|
||||||
|
{
|
||||||
|
QApplication a(argc, argv);
|
||||||
|
|
||||||
|
QTranslator translator;
|
||||||
|
const QStringList uiLanguages = QLocale::system().uiLanguages();
|
||||||
|
for (const QString &locale : uiLanguages) {
|
||||||
|
const QString baseName = "cevo-evo_" + QLocale(locale).name();
|
||||||
|
if (translator.load(":/i18n/" + baseName)) {
|
||||||
|
a.installTranslator(&translator);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MainWindow w;
|
||||||
|
w.show();
|
||||||
|
return a.exec();
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#include "mainwindow.h"
|
||||||
|
#include "./ui_mainwindow.h"
|
||||||
|
|
||||||
|
MainWindow::MainWindow(QWidget *parent)
|
||||||
|
: QMainWindow(parent)
|
||||||
|
, ui(new Ui::MainWindow)
|
||||||
|
{
|
||||||
|
ui->setupUi(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
MainWindow::~MainWindow()
|
||||||
|
{
|
||||||
|
delete ui;
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
#ifndef MAINWINDOW_H
|
||||||
|
#define MAINWINDOW_H
|
||||||
|
|
||||||
|
#include <QMainWindow>
|
||||||
|
|
||||||
|
QT_BEGIN_NAMESPACE
|
||||||
|
namespace Ui {
|
||||||
|
class MainWindow;
|
||||||
|
}
|
||||||
|
QT_END_NAMESPACE
|
||||||
|
|
||||||
|
class MainWindow : public QMainWindow
|
||||||
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
|
||||||
|
public:
|
||||||
|
MainWindow(QWidget *parent = nullptr);
|
||||||
|
~MainWindow();
|
||||||
|
|
||||||
|
private:
|
||||||
|
Ui::MainWindow *ui;
|
||||||
|
};
|
||||||
|
#endif // MAINWINDOW_H
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<ui version="4.0">
|
||||||
|
<class>MainWindow</class>
|
||||||
|
<widget class="QMainWindow" name="MainWindow">
|
||||||
|
<property name="geometry">
|
||||||
|
<rect>
|
||||||
|
<x>0</x>
|
||||||
|
<y>0</y>
|
||||||
|
<width>800</width>
|
||||||
|
<height>600</height>
|
||||||
|
</rect>
|
||||||
|
</property>
|
||||||
|
<property name="windowTitle">
|
||||||
|
<string>MainWindow</string>
|
||||||
|
</property>
|
||||||
|
<widget class="QWidget" name="centralwidget"/>
|
||||||
|
<widget class="QMenuBar" name="menubar">
|
||||||
|
<property name="geometry">
|
||||||
|
<rect>
|
||||||
|
<x>0</x>
|
||||||
|
<y>0</y>
|
||||||
|
<width>800</width>
|
||||||
|
<height>23</height>
|
||||||
|
</rect>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
<widget class="QStatusBar" name="statusbar"/>
|
||||||
|
</widget>
|
||||||
|
<resources/>
|
||||||
|
<connections/>
|
||||||
|
</ui>
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# UosMedia: Qt Multimedia equivalent of the "United Openlibraries of Sound"
|
||||||
|
# (uos) Pascal package used by perso/cevo/Music.pas for background music
|
||||||
|
# playback. Unlike uos, Qt Multimedia resolves its codec backend (FFmpeg on
|
||||||
|
# most platforms) automatically, so there is no equivalent to uos's optional
|
||||||
|
# codec plugins (uos_opus, uos_mpg123, uos_libxmp, ...) or its manual
|
||||||
|
# uos_LoadLib runtime library probing.
|
||||||
|
|
||||||
|
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Multimedia)
|
||||||
|
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Multimedia)
|
||||||
|
|
||||||
|
set(UOS_MEDIA_HEADERS
|
||||||
|
include/Uos/Uos.h
|
||||||
|
include/Uos/UosPlayer.h
|
||||||
|
)
|
||||||
|
|
||||||
|
set(UOS_MEDIA_SOURCES
|
||||||
|
src/UosPlayer.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
add_library(uosmedia SHARED ${UOS_MEDIA_SOURCES} ${UOS_MEDIA_HEADERS})
|
||||||
|
|
||||||
|
target_include_directories(uosmedia PUBLIC
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(uosmedia PUBLIC Qt${QT_VERSION_MAJOR}::Multimedia)
|
||||||
|
|
||||||
|
set_target_properties(uosmedia PROPERTIES
|
||||||
|
AUTOMOC ON
|
||||||
|
CXX_STANDARD 17
|
||||||
|
CXX_STANDARD_REQUIRED ON
|
||||||
|
)
|
||||||
|
|
||||||
|
include(GNUInstallDirs)
|
||||||
|
install(TARGETS uosmedia
|
||||||
|
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/cevo-evo
|
||||||
|
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}/cevo-evo
|
||||||
|
)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Convenience umbrella header mirroring uos_flat.pas: `#include
|
||||||
|
// <Uos/Uos.h>` the same way Music.pas did `uses uos_flat`.
|
||||||
|
|
||||||
|
#include "Uos/UosPlayer.h"
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QMediaPlayer>
|
||||||
|
#include <QObject>
|
||||||
|
#include <QString>
|
||||||
|
#include <functional>
|
||||||
|
|
||||||
|
class QAudioOutput;
|
||||||
|
|
||||||
|
namespace Uos {
|
||||||
|
|
||||||
|
// uos_LoadLib / uos_TestLoadLibrary / uosLoadResult: Qt Multimedia resolves
|
||||||
|
// its backend automatically, so there is no equivalent runtime library
|
||||||
|
// probing step. This only checks that a usable audio output device exists,
|
||||||
|
// the one condition that could previously fail via uos_LoadLib's PortAudio
|
||||||
|
// error codes.
|
||||||
|
bool isAudioOutputAvailable();
|
||||||
|
|
||||||
|
// Qt equivalent of a uos_flat "player": one audio input routed to the
|
||||||
|
// default output device. uos_flat's integer PlayerIndex/InputIndex/
|
||||||
|
// OutputIndex handles (uos_CreatePlayer/uos_AddFromFile/uos_AddIntoDevOut)
|
||||||
|
// are replaced by a single object.
|
||||||
|
class Player : public QObject {
|
||||||
|
Q_OBJECT
|
||||||
|
public:
|
||||||
|
explicit Player(QObject *parent = nullptr);
|
||||||
|
|
||||||
|
// uos_AddFromFile: returns false if the file does not exist.
|
||||||
|
bool addFromFile(const QString &fileName);
|
||||||
|
|
||||||
|
// uos_InputSetPositionEnable: Qt always tracks position, kept only for
|
||||||
|
// API parity with call sites that used to gate it.
|
||||||
|
void setPositionEnable(bool enable) { Q_UNUSED(enable); }
|
||||||
|
// uos_InputLength: duration of the current input, in milliseconds.
|
||||||
|
qint64 inputLength() const;
|
||||||
|
|
||||||
|
// uos_InputAddDSPVolume / uos_InputSetDSPVolume: QAudioOutput exposes a
|
||||||
|
// single volume (0.0-1.0) with no instant/smooth ramp distinction, so
|
||||||
|
// left/right are averaged and "smooth" is accepted but not applied.
|
||||||
|
void setVolume(float left, float right, bool smooth = false);
|
||||||
|
float volume() const;
|
||||||
|
|
||||||
|
// uos_AddIntoDevOut: Qt Multimedia always targets the default output
|
||||||
|
// device; this just reports whether one is available.
|
||||||
|
bool addIntoDevOut();
|
||||||
|
|
||||||
|
// uos_Play / uos_Stop. loopCount <= 1 plays the input once, matching the
|
||||||
|
// uos_Play default of nloop = 0.
|
||||||
|
void play(int loopCount = 0);
|
||||||
|
void stop();
|
||||||
|
bool playing() const;
|
||||||
|
|
||||||
|
// uos_EndProc.
|
||||||
|
std::function<void()> onEnd;
|
||||||
|
|
||||||
|
private:
|
||||||
|
void handleMediaStatusChanged(QMediaPlayer::MediaStatus status);
|
||||||
|
|
||||||
|
QMediaPlayer *m_player;
|
||||||
|
QAudioOutput *m_audioOutput;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Uos
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
#include "Uos/UosPlayer.h"
|
||||||
|
|
||||||
|
#include <QAudioDevice>
|
||||||
|
#include <QAudioOutput>
|
||||||
|
#include <QFileInfo>
|
||||||
|
#include <QMediaDevices>
|
||||||
|
#include <QUrl>
|
||||||
|
|
||||||
|
namespace Uos {
|
||||||
|
|
||||||
|
bool isAudioOutputAvailable()
|
||||||
|
{
|
||||||
|
return !QMediaDevices::defaultAudioOutput().isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
Player::Player(QObject *parent) : QObject(parent)
|
||||||
|
{
|
||||||
|
m_player = new QMediaPlayer(this);
|
||||||
|
m_audioOutput = new QAudioOutput(this);
|
||||||
|
m_player->setAudioOutput(m_audioOutput);
|
||||||
|
connect(m_player, &QMediaPlayer::mediaStatusChanged, this, &Player::handleMediaStatusChanged);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Player::addFromFile(const QString &fileName)
|
||||||
|
{
|
||||||
|
if (!QFileInfo::exists(fileName))
|
||||||
|
return false;
|
||||||
|
m_player->setSource(QUrl::fromLocalFile(fileName));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
qint64 Player::inputLength() const
|
||||||
|
{
|
||||||
|
return m_player->duration();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Player::setVolume(float left, float right, bool smooth)
|
||||||
|
{
|
||||||
|
Q_UNUSED(smooth);
|
||||||
|
m_audioOutput->setVolume((left + right) / 2.0f);
|
||||||
|
}
|
||||||
|
|
||||||
|
float Player::volume() const
|
||||||
|
{
|
||||||
|
return m_audioOutput->volume();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Player::addIntoDevOut()
|
||||||
|
{
|
||||||
|
return isAudioOutputAvailable();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Player::play(int loopCount)
|
||||||
|
{
|
||||||
|
m_player->setLoops(loopCount <= 1 ? 1 : loopCount);
|
||||||
|
m_player->play();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Player::stop()
|
||||||
|
{
|
||||||
|
m_player->stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Player::playing() const
|
||||||
|
{
|
||||||
|
return m_player->playbackState() == QMediaPlayer::PlayingState;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Player::handleMediaStatusChanged(QMediaPlayer::MediaStatus status)
|
||||||
|
{
|
||||||
|
if (status == QMediaPlayer::EndOfMedia && onEnd)
|
||||||
|
onEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Uos
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Game resources (graphics, music, sounds, resource/help translations),
|
||||||
|
# imported as-is from the original Lazarus/Delphi project
|
||||||
|
# (perso/cevo/{Graphics,Music,Sounds,Localization}) - plain data, nothing to
|
||||||
|
# build, just installed next to the game so Qt::Multimedia/QPixmap etc. can
|
||||||
|
# load it from CMAKE_INSTALL_RESOURCEDIR (see CEVO_RESOURCE_DIR, defined for
|
||||||
|
# the cevo-evo target in the top-level CMakeLists.txt).
|
||||||
|
|
||||||
|
install(DIRECTORY Graphics Music Sounds Localization
|
||||||
|
DESTINATION ${CMAKE_INSTALL_RESOURCEDIR}
|
||||||
|
)
|
||||||
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 70 KiB |
@@ -0,0 +1 @@
|
|||||||
|
Steffen Gerlach [SG]
|
||||||
|
After Width: | Height: | Size: 134 KiB |
@@ -0,0 +1,2 @@
|
|||||||
|
Erwan [e]
|
||||||
|
Andrew Miller [AM]
|
||||||
|
After Width: | Height: | Size: 35 KiB |
@@ -0,0 +1 @@
|
|||||||
|
Steffen Gerlach [SG]
|
||||||
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 2.3 KiB |
|
After Width: | Height: | Size: 521 B |
@@ -0,0 +1 @@
|
|||||||
|
William H. Keith [future scenery]
|
||||||