init commit
This commit is contained in:
commit
1497f114e6
47 files changed
+8358
No files matched your search
@@ -0,0 +1 @@
|
||||
BasedOnStyle: Microsoft
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
# IDE/editor state
|
||||
.idea/
|
||||
.vs/
|
||||
.vscode/
|
||||
*.iml
|
||||
*.user
|
||||
*.suo
|
||||
|
||||
# Build trees and generated CMake files
|
||||
build/
|
||||
build-*/
|
||||
cmake-build-*/
|
||||
out/
|
||||
CMakeFiles/
|
||||
CMakeCache.txt
|
||||
cmake_install.cmake
|
||||
CTestTestfile.cmake
|
||||
compile_commands.json
|
||||
CMakeUserPresets.json
|
||||
.ninja_*
|
||||
|
||||
# Compiled artifacts
|
||||
*.obj
|
||||
*.o
|
||||
*.exe
|
||||
*.dll
|
||||
*.so
|
||||
*.so.*
|
||||
*.dylib
|
||||
*.a
|
||||
*.lib
|
||||
*.pdb
|
||||
*.ilk
|
||||
|
||||
# Local caches and temporary files
|
||||
.cache/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.log
|
||||
*.tmp
|
||||
*.swp
|
||||
*~
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Never commit credentials or local environment settings
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
botcraft_cached_credentials.json
|
||||
botcraft_cached_credentials.json.*
|
||||
user-defined/
|
||||
@@ -0,0 +1,6 @@
|
||||
[submodule "3rd/Botcraft"]
|
||||
path = 3rd/Botcraft
|
||||
url = https://github.com/adepierre/Botcraft.git
|
||||
[submodule "3rd/googletest"]
|
||||
path = 3rd/googletest
|
||||
url = https://github.com/google/googletest.git
|
||||
Submodule
+1
Submodule 3rd/Botcraft added at 0809455c61.
Submodule
+1
Submodule 3rd/googletest added at 063de7e957.
+116
@@ -0,0 +1,116 @@
|
||||
cmake_minimum_required(VERSION 3.30)
|
||||
project(bilicraft-bot VERSION 0.1.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 23)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_CXX_SCAN_FOR_MODULES OFF)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/3rd/Botcraft/CMakeLists.txt")
|
||||
message(FATAL_ERROR "Botcraft is missing. Run: git submodule update --init -- 3rd/Botcraft")
|
||||
endif()
|
||||
|
||||
# Pin the supported game version; never silently follow upstream's moving 'latest' version.
|
||||
set(BOTCRAFT_GAME_VERSION "1.21.11" CACHE STRING "Minecraft server version" FORCE)
|
||||
set(BOTCRAFT_OUTPUT_DIR "${CMAKE_BINARY_DIR}" CACHE PATH "Botcraft output directory" FORCE)
|
||||
set(BOTCRAFT_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
set(BOTCRAFT_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(BOTCRAFT_BUILD_TESTS_ONLINE OFF CACHE BOOL "" FORCE)
|
||||
set(BOTCRAFT_BUILD_DOC OFF CACHE BOOL "" FORCE)
|
||||
set(BOTCRAFT_USE_OPENGL_GUI OFF CACHE BOOL "" FORCE)
|
||||
set(BOTCRAFT_USE_IMGUI OFF CACHE BOOL "" FORCE)
|
||||
set(BOTCRAFT_COMPRESSION ON CACHE BOOL "" FORCE)
|
||||
set(BOTCRAFT_ENCRYPTION ON CACHE BOOL "" FORCE)
|
||||
if(MINGW)
|
||||
set(BOTCRAFT_WINDOWS_BETTER_SLEEP OFF CACHE BOOL "" FORCE)
|
||||
endif()
|
||||
include(cmake/ApplyBotcraftPatches.cmake)
|
||||
add_subdirectory(3rd/Botcraft EXCLUDE_FROM_ALL)
|
||||
|
||||
# Botcraft's public DLL interfaces exchange STL objects: match its MSVC CRT.
|
||||
if(MSVC)
|
||||
set(CMAKE_MSVC_RUNTIME_LIBRARY "$<TARGET_PROPERTY:botcraft,MSVC_RUNTIME_LIBRARY>")
|
||||
endif()
|
||||
|
||||
add_library(bilicraft_bot_config STATIC src/AppConfig.cpp)
|
||||
target_include_directories(bilicraft_bot_config PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_compile_definitions(bilicraft_bot_config PUBLIC BILICRAFT_BOT_GAME_VERSION="${BOTCRAFT_GAME_VERSION}")
|
||||
|
||||
add_library(bilicraft_bot_actions STATIC src/ActionFile.cpp src/ActionScheduler.cpp src/ConsoleCommand.cpp
|
||||
src/TerminalInput.cpp src/LineEditor.cpp src/TerminalConsole.cpp)
|
||||
target_include_directories(bilicraft_bot_actions PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(bilicraft_bot_actions PUBLIC Threads::Threads)
|
||||
|
||||
add_library(bilicraft_bot_client STATIC src/BilicraftClient.cpp src/ActionExecutor.cpp src/EntityInteraction.cpp)
|
||||
target_link_libraries(bilicraft_bot_client PUBLIC bilicraft_bot_config bilicraft_bot_actions botcraft)
|
||||
|
||||
add_executable(bilicraft-bot main.cpp)
|
||||
target_link_libraries(bilicraft-bot PRIVATE bilicraft_bot_client)
|
||||
# Use the same location for single- and multi-config generators, beside Assets/DLLs.
|
||||
set_target_properties(bilicraft-bot PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin$<0:>")
|
||||
set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT bilicraft-bot)
|
||||
set_target_properties(bilicraft-bot PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
foreach(target bilicraft_bot_config bilicraft_bot_actions bilicraft_bot_client bilicraft-bot)
|
||||
if(MSVC)
|
||||
target_compile_options(${target} PRIVATE /W4 /utf-8)
|
||||
else()
|
||||
target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
include(CTest)
|
||||
if(BUILD_TESTING)
|
||||
if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/3rd/googletest/CMakeLists.txt")
|
||||
message(FATAL_ERROR "GoogleTest is missing. Run: git submodule update --init -- 3rd/googletest")
|
||||
endif()
|
||||
set(BUILD_GMOCK OFF CACHE BOOL "" FORCE)
|
||||
set(INSTALL_GTEST OFF CACHE BOOL "" FORCE)
|
||||
if(MSVC)
|
||||
set(gtest_force_shared_crt OFF CACHE BOOL "" FORCE)
|
||||
else()
|
||||
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
|
||||
endif()
|
||||
add_subdirectory(3rd/googletest EXCLUDE_FROM_ALL)
|
||||
include(GoogleTest)
|
||||
add_executable(app_config_tests tests/AppConfigTests.cpp)
|
||||
target_link_libraries(app_config_tests PRIVATE bilicraft_bot_config GTest::gtest_main)
|
||||
gtest_discover_tests(app_config_tests)
|
||||
add_executable(action_file_tests tests/ActionFileTests.cpp)
|
||||
target_link_libraries(action_file_tests PRIVATE bilicraft_bot_actions GTest::gtest_main)
|
||||
gtest_discover_tests(action_file_tests)
|
||||
foreach(suite ActionScheduler ConsoleCommand TerminalInput LineEditor TerminalConsole)
|
||||
add_executable(${suite}_tests tests/${suite}Tests.cpp)
|
||||
target_link_libraries(${suite}_tests PRIVATE bilicraft_bot_actions GTest::gtest_main)
|
||||
gtest_discover_tests(${suite}_tests)
|
||||
endforeach()
|
||||
add_executable(bilicraft_client_tests tests/BilicraftClientTests.cpp)
|
||||
target_link_libraries(bilicraft_client_tests PRIVATE bilicraft_bot_client GTest::gtest_main)
|
||||
set_target_properties(bilicraft_client_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin$<0:>")
|
||||
gtest_discover_tests(bilicraft_client_tests WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
add_executable(action_executor_tests tests/ActionExecutorTests.cpp)
|
||||
target_link_libraries(action_executor_tests PRIVATE bilicraft_bot_client GTest::gtest_main)
|
||||
set_target_properties(action_executor_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin$<0:>")
|
||||
gtest_discover_tests(action_executor_tests WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
add_executable(inventory_sync_tests tests/InventorySyncTests.cpp)
|
||||
target_link_libraries(inventory_sync_tests PRIVATE bilicraft_bot_client GTest::gtest_main)
|
||||
set_target_properties(inventory_sync_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin$<0:>")
|
||||
gtest_discover_tests(inventory_sync_tests WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
foreach(suite EntityInteraction ItemFrameSpawn)
|
||||
add_executable(${suite}_tests tests/${suite}Tests.cpp)
|
||||
target_link_libraries(${suite}_tests PRIVATE bilicraft_bot_client GTest::gtest_main)
|
||||
set_target_properties(${suite}_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin$<0:>")
|
||||
gtest_discover_tests(${suite}_tests WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endforeach()
|
||||
# These smoke tests return before constructing a client or authenticating.
|
||||
add_test(NAME cli_help COMMAND bilicraft-bot --help)
|
||||
set_tests_properties(cli_help PROPERTIES PASS_REGULAR_EXPRESSION "mc.bilicraft.com:25577")
|
||||
add_test(NAME cli_check_action COMMAND bilicraft-bot --check-action "${CMAKE_CURRENT_SOURCE_DIR}/actions/demo.act")
|
||||
set_tests_properties(cli_check_action PROPERTIES PASS_REGULAR_EXPRESSION "3 commands validated")
|
||||
add_test(NAME cli_rejects_missing_action COMMAND bilicraft-bot --check-action "${CMAKE_CURRENT_BINARY_DIR}/missing.act")
|
||||
set_tests_properties(cli_rejects_missing_action PROPERTIES WILL_FAIL TRUE)
|
||||
add_test(NAME cli_rejects_unknown_option COMMAND bilicraft-bot --unknown)
|
||||
set_tests_properties(cli_rejects_unknown_option PROPERTIES WILL_FAIL TRUE)
|
||||
endif()
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"version": 6,
|
||||
"cmakeMinimumRequired": { "major": 3, "minor": 30, "patch": 0 },
|
||||
"configurePresets": [
|
||||
{
|
||||
"name": "dev",
|
||||
"displayName": "Development (Ninja, Debug)",
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"cacheVariables": { "CMAKE_BUILD_TYPE": "Debug", "BUILD_TESTING": "ON" }
|
||||
},
|
||||
{
|
||||
"name": "release",
|
||||
"displayName": "Release (Ninja)",
|
||||
"inherits": "dev",
|
||||
"binaryDir": "${sourceDir}/build-release",
|
||||
"cacheVariables": { "CMAKE_BUILD_TYPE": "Release" }
|
||||
}
|
||||
],
|
||||
"buildPresets": [
|
||||
{ "name": "dev", "configurePreset": "dev", "jobs": 2 },
|
||||
{ "name": "release", "configurePreset": "release", "jobs": 2 }
|
||||
],
|
||||
"testPresets": [
|
||||
{ "name": "dev", "configurePreset": "dev", "output": { "outputOnFailure": true }, "execution": { "noTestsAction": "error" } },
|
||||
{ "name": "release", "configurePreset": "release", "output": { "outputOnFailure": true }, "execution": { "noTestsAction": "error" } }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,262 @@
|
||||
# bilicraft-bot
|
||||
|
||||
基于 [Botcraft](https://github.com/adepierre/Botcraft) 的 Minecraft Java 机器人,默认连接 BiliCraft 服务器。使用 Microsoft 正版账号登录,通过交互终端或 `.act` 操作文件执行移动、方块与展示框交互、背包操作和聊天命令。
|
||||
|
||||
项目使用 C++23 和 CMake,提供离线脚本检查、合作式任务调度及终端命令编辑。目前的自动化由脚本驱动,尚未实现自主种植、自动重连或自动复活。
|
||||
|
||||
## 环境要求
|
||||
|
||||
| 项目 | 要求或默认值 |
|
||||
| --- | --- |
|
||||
| 游戏版本 | Minecraft Java **1.21.11**,协议 **774** |
|
||||
| 默认服务器 | **mc.bilicraft.com:25577**,可通过 `--server` 覆盖 |
|
||||
| 登录方式 | 拥有 Minecraft Java 的 Microsoft 账号 |
|
||||
| 工具链 | 支持 C++23 的编译器、CMake ≥ 3.30、Ninja、Git |
|
||||
| 系统依赖 | OpenSSL、zlib 开发库 |
|
||||
|
||||
Linux 可使用 GCC;Windows 可使用安装相应依赖的 MSYS2 MinGW64,或配置好 OpenSSL/zlib 的 MSVC 开发环境。Windows 当前支持管道和文件输入,原生 Windows console 尚不支持。
|
||||
|
||||
## 构建与测试
|
||||
|
||||
在项目根目录执行:
|
||||
|
||||
```sh
|
||||
git submodule update --init -- 3rd/Botcraft 3rd/googletest
|
||||
cmake --preset dev
|
||||
cmake --build --preset dev
|
||||
ctest --preset dev
|
||||
```
|
||||
|
||||
首次配置需要联网:Botcraft 会初始化 Asio 子模块,并下载 Mojang 版本元数据和客户端资源。
|
||||
|
||||
- `dev`:Debug 构建,输出到 `build/`。
|
||||
- `release`:Release 构建,输出到 `build-release/`。将上述命令中的 `dev` 换成 `release` 即可。
|
||||
- 构建预设使用 Ninja,默认并发数为 2。上游示例、测试、文档和图形渲染关闭,压缩和加密开启。
|
||||
- 只编译应用时可用 `cmake --preset dev -DBUILD_TESTING=OFF`,无需初始化 GoogleTest。
|
||||
|
||||
也可手动选择生成器:
|
||||
|
||||
```sh
|
||||
cmake -S . -B build-custom -DBUILD_TESTING=ON
|
||||
cmake --build build-custom --config Debug --parallel 2
|
||||
ctest --test-dir build-custom -C Debug --output-on-failure
|
||||
```
|
||||
|
||||
Botcraft 和 GoogleTest 通过 `3rd/` 中的 Git 子模块固定版本。CMake 配置时自动应用 `patches/` 下的背包同步与展示框生成修复;已应用的补丁会跳过,遇到冲突则停止配置。应用补丁后 Botcraft 子模块显示本地修改属于预期行为,请保留这些修改。
|
||||
|
||||
测试覆盖参数解析、脚本导入、任务调度、终端输入与编辑、客户端生命周期、背包同步和展示框定位。测试不连接服务器,也不进行 Microsoft 授权;实际服务器及插件行为仍需在线验证。
|
||||
|
||||
## 运行
|
||||
|
||||
**联网运行时,工作目录必须是构建目录下的 `bin/`**。Botcraft 相对于当前工作目录读取 `Assets/1.21.11/`,请保留该资源目录和同目录的共享库。Windows 还需确保相关依赖 DLL 位于 PATH 中。
|
||||
|
||||
Linux:
|
||||
|
||||
```sh
|
||||
(cd build/bin && ./bilicraft-bot)
|
||||
```
|
||||
|
||||
PowerShell(当前需使用管道或文件提供命令):
|
||||
|
||||
```powershell
|
||||
Push-Location build/bin
|
||||
Get-Content ../../commands.txt | .\bilicraft-bot.exe
|
||||
Pop-Location
|
||||
```
|
||||
|
||||
`commands.txt` 为自行创建的终端命令文件,每行一条命令,例如 `run ../../actions/demo.act`。输入结束后,程序会等待已排队任务完成并退出。
|
||||
|
||||
查看帮助或离线检查脚本不要求在 `bin/` 中执行:
|
||||
|
||||
```sh
|
||||
./build/bin/bilicraft-bot --help
|
||||
./build/bin/bilicraft-bot --check-action actions/demo.act
|
||||
```
|
||||
|
||||
### 命令行参数
|
||||
|
||||
```text
|
||||
bilicraft-bot [--server host:port] [--account cache-key]
|
||||
[--action file.act | --check-action file.act] [--help]
|
||||
```
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --- | --- |
|
||||
| `--server host:port` | 服务器地址,默认 `mc.bilicraft.com:25577` |
|
||||
| `--account cache-key` | Microsoft 凭据缓存区分键,默认空键;不是用户名、密码或 token |
|
||||
| `--action file.act` | 登录后将脚本加入初始任务队列,并进入交互终端 |
|
||||
| `--check-action file.act` | 离线解析脚本及全部导入,完成后退出,不加载资源或登录 |
|
||||
| `--help` / `-h` | 显示帮助并退出,不触发授权 |
|
||||
|
||||
`--action` 和 `--check-action` 互斥,每次仅接受一个入口文件。路径相对于启动工作目录:
|
||||
|
||||
```sh
|
||||
(cd build/bin && ./bilicraft-bot --server mc.bilicraft.com:25577 --account main)
|
||||
(cd build/bin && ./bilicraft-bot --action ../../actions/demo.act)
|
||||
```
|
||||
|
||||
首次登录按控制台提示完成 Microsoft 浏览器授权。凭据缓存在运行工作目录的 `botcraft_cached_credentials.json` 中,该文件已加入 Git 忽略规则,包含敏感令牌,请勿提交或共享。运行环境需能访问 Microsoft/Mojang 认证端点。
|
||||
|
||||
## 交互终端
|
||||
|
||||
入服后显示 `>>>`,可以提交单条游戏命令或使用以下控制命令:
|
||||
|
||||
```text
|
||||
>>> run ../../actions/demo.act
|
||||
>>> tasks
|
||||
>>> sw 2
|
||||
>>> help
|
||||
>>> quit
|
||||
```
|
||||
|
||||
| 命令 | 说明 |
|
||||
| --- | --- |
|
||||
| `run 路径.act` | 完整检查脚本及导入后入队,路径可用成对引号包裹 |
|
||||
| `tasks` | 显示任务编号、状态、命令进度和等待剩余时间 |
|
||||
| `help` | 显示终端帮助 |
|
||||
| `quit` / `exit` | 取消队列并断开连接 |
|
||||
|
||||
游戏命令与脚本共用下文语法,但 `wait` 和 `import` 仅能写在操作文件中。单条交互游戏命令提交后,终端会等它完成或失败,再接收下一条输入。
|
||||
|
||||
### 调度与退出
|
||||
|
||||
- 游戏操作在主线程串行执行。运行中的脚本会持续执行,直到完成、失败或遇到 `wait`;新任务不会抢占它。
|
||||
- 交互游戏命令在当前脚本完成或等待时优先执行。就绪脚本按最新入队优先(LIFO)选择,持续加入新任务可能推迟旧任务。
|
||||
- `wait` 挂起当前脚本,计时结束后重新入队;`import` 在当前脚本内展开,不创建独立任务。
|
||||
- 等待期间其他任务可能改变位置、手持格或背包;脚本恢复时不会自动还原状态。
|
||||
- 某个脚本失败会丢弃其剩余命令,其他任务和终端仍可继续使用;已完成的操作不回滚,也不自动重试。
|
||||
- Ctrl+C、SIGTERM 或 `quit` 取消任务并退出。EOF(如空行处 Ctrl+D)则等待队列排空,包括尚未结束的 `wait`,再断开连接。
|
||||
|
||||
### 输入编辑
|
||||
|
||||
在支持 ANSI 的 Linux/macOS 原生终端中,stdin/stdout 连接同一终端时会启用滚动日志区、状态行和固定输入栏。建议使用系统终端或 CLion Terminal。
|
||||
|
||||
- ↑ / ↓:浏览本次会话最近 200 条历史命令,仅保存在内存。
|
||||
- ← / →、Home / End:移动光标;Backspace / Delete:删除字符。
|
||||
- Ctrl+A / Ctrl+E:行首/行尾;Ctrl+U / Ctrl+K:删除光标前/后的内容。
|
||||
- Enter:提交;空行处 Ctrl+D:EOF;Ctrl+C:取消并退出。
|
||||
|
||||
非 TTY、输出重定向、`TERM=dumb` 或终端尺寸不合适时回退为逐行输入。单行长度上限为 64 KiB。编辑支持中文 UTF-8 字符边界,复杂 emoji 的显示宽度取决于终端。
|
||||
|
||||
## 操作文件(`.act`)
|
||||
|
||||
操作文件是 UTF-8 文本,支持 BOM 和 CRLF,一行一条命令,空行忽略。`#` 开始行尾注释,即使位于消息或引号中也一样,不支持转义保留 `#`。
|
||||
|
||||
每个文件在第一条命令前必须声明且仅声明一次名称:
|
||||
|
||||
```text
|
||||
# action: example
|
||||
sw 1
|
||||
goto 100 64 200
|
||||
wait 5 s
|
||||
sendmsg 操作完成
|
||||
```
|
||||
|
||||
名称是非空简单名称,不含目录、路径分隔符或 `.act` 扩展名。坐标均为绝对整数方块坐标,不支持 `~`、`^` 或小数。下表中的方括号表示可选参数,实际输入时不写方括号;标志区分大小写。
|
||||
|
||||
### 游戏命令
|
||||
|
||||
| 命令 | 说明 |
|
||||
| --- | --- |
|
||||
| `goto x y z` | 寻路到指定方块坐标,不可达或超时则失败 |
|
||||
| `rclick x y z [entry [方向]] [shift]` | 主手右击方块;`entry` 改为展示框交互,`shift` 仅本次蹲下 |
|
||||
| `lclick x y z [entry [方向]] [shift] [destory]` | 普通方块模式只挥手,`destory` 挖掘;展示框模式默认取物,`destory` 拆框;也接受 `destroy` |
|
||||
| `grclick row col` | 右击已打开容器的指定槽位 |
|
||||
| `glclick row col` | 左击已打开容器的指定槽位 |
|
||||
| `sw n` | 选择快捷栏第 `1..9` 格 |
|
||||
| `swb row col n` | 玩家背包主存储区第 `1..3` 行、第 `1..9` 列与快捷栏第 `1..9` 格交换 |
|
||||
| `drop [n] [all]` | 丢弃快捷栏指定格的 1 个物品;省略 n 使用当前手持格,`all` 丢弃该格整组 |
|
||||
| `wait times [s\|ms\|min\|h\|d]` | 等待并让出执行权,默认单位秒,仅操作文件可用 |
|
||||
| `sendcmd cmd` | 发送服务器命令,允许带一个开头 `/`,支持空格和参数 |
|
||||
| `sendmsg msg` | 发送公开聊天消息 |
|
||||
| `sendmsg @to msg` | 发送私信,等价于 `/msg to msg` |
|
||||
| `import action` | 执行同目录的 `action.act`,完成后继续当前文件,仅操作文件可用 |
|
||||
|
||||
点击命令不会自动寻路,请先用 `goto` 移到交互距离内。普通方块右击选择上表面;方块与实体点击均未实现完整视线遮挡检测。
|
||||
|
||||
### 容器与背包
|
||||
|
||||
行列从 **1** 开始,从上到下、从左到右。容器点击使用协议槽位,不需要图形界面,目前仅支持箱子等 9 列矩形容器的上部槽位,不包含下部玩家背包。工作台、熔炉等布局会报错。
|
||||
|
||||
`swb` 和 `drop` 要求容器已关闭且鼠标光标未拿起物品。它们等待服务器槽位回传确认,超时不重复发送。`drop 1 all` 始终操作快捷栏第 1 格;只有 `drop all` 才操作当前手持格,指定其他格不会切换主手:
|
||||
|
||||
```text
|
||||
drop # 当前手持格丢弃 1 个
|
||||
drop 3 # 快捷栏第 3 格丢弃 1 个
|
||||
drop all # 当前手持格丢弃整组
|
||||
drop 3 all # 快捷栏第 3 格丢弃整组
|
||||
swb 1 1 1 # 背包第一行第一列与快捷栏第一格交换
|
||||
```
|
||||
|
||||
### 展示框
|
||||
|
||||
`entry` 支持普通展示框和发光展示框。`x y z` 表示**支撑方块**坐标,方向指定该方块的哪一面:
|
||||
|
||||
| 方向 | 方块面 |
|
||||
| --- | --- |
|
||||
| `t` / `top` | 上面,+Y |
|
||||
| `b` / `bottom` | 下面,−Y |
|
||||
| `s` / `south` | 南面,+Z |
|
||||
| `n` / `north` | 北面,−Z |
|
||||
| `w` / `west` | 西面,−X |
|
||||
| `e` / `east` | 东面,+X |
|
||||
|
||||
```text
|
||||
rclick 100 64 200 entry n # 放入或旋转物品
|
||||
rclick 100 64 200 entry top shift
|
||||
lclick 100 64 200 entry s # 取下物品,保留空框
|
||||
lclick 100 64 200 entry e destory # 拆除展示框
|
||||
```
|
||||
|
||||
方向必须紧接 `entry`。省略方向时搜索六面,只有唯一匹配框才交互;多个框报歧义,找不到时最多等待 5 秒。失败日志包含支撑坐标、方向、已加载框数量和附近框信息,可用于核对坐标。
|
||||
|
||||
普通左击仅在本地已知框内有物品时攻击,并等待物品变空;创造模式下拒绝普通取物,以免直接拆框。`destory` 最多攻击两次:先取物,再拆除同一个空框。其他玩家或插件同时改变框状态仍可能影响结果,取下物品也不保证会被机器人拾取。
|
||||
|
||||
### 等待与导入
|
||||
|
||||
```text
|
||||
# action: example
|
||||
import prepare
|
||||
wait 500 ms
|
||||
wait 0.5 min
|
||||
sendmsg 等待结束
|
||||
```
|
||||
|
||||
`wait` 支持普通非负十进制数,时长必须精确到整毫秒,范围为 0 到 365 天;单位区分大小写。`wait 0` 也让出一次执行权。计时使用单调时钟,系统校时不影响等待时长。
|
||||
|
||||
`import prepare` 在当前位置展开同目录的 `prepare.act`,其声明必须为 `# action: prepare`。导入名称不带扩展名、不允许路径穿越。支持嵌套和重复导入,循环导入、文件缺失或名称不一致会报告文件和行号。
|
||||
|
||||
整个导入图在执行前完成语法检查。最大导入深度为 32、展开命令数为 100000,并限制文件大小和导入次数;语法检查通过不代表在线操作一定成功。
|
||||
|
||||
随附的 `actions/demo.act` 演示快捷栏、导入和聊天。执行会真实发送公开消息与私信,请先使用 `--check-action` 检查并按需修改。
|
||||
|
||||
## 项目结构
|
||||
|
||||
```text
|
||||
3rd/ Botcraft、GoogleTest Git 子模块
|
||||
include/ BilicraftClient、操作执行、调度和终端接口
|
||||
src/ 对应实现
|
||||
main.cpp 登录、主循环与退出处理
|
||||
actions/ .act 示例;user-defined/ 下的本地脚本不纳入版本管理
|
||||
patches/ 固定版本 Botcraft 的修复补丁
|
||||
cmake/ 补丁应用逻辑
|
||||
tests/ 离线测试
|
||||
```
|
||||
|
||||
CMake 项目和可执行文件名为 `bilicraft-bot`,C++ 命名空间为 `Bilicraft`,客户端类为 `BilicraftClient`。
|
||||
|
||||
`BilicraftClient` 继承 `Botcraft::TemplatedBehaviourClient<BilicraftClient>`,提供世界、实体、背包和物理管理器。游戏任务通过 `Yield()` 配合主线程处理终端输入、取消、断开与超时;使用 `SetActionYieldHandler` 的执行模式不能与上游 `StartBehaviour`、`BehaviourStep`、`SyncAction` 混用。自定义长任务也需定期让出执行权。
|
||||
|
||||
## 当前限制
|
||||
|
||||
- 每条游戏执行命令有 60 秒合作式超时,`wait` 不受该限制。不调用 `Yield()` 的阻塞代码无法及时取消。
|
||||
- Microsoft 授权是上游同步调用,授权期间的退出请求需等待调用返回;60 秒入服超时从授权返回后开始计算。
|
||||
- 尚未实现网络健康监控,无断开包的链路丢失不保证能主动检测;收到服务器断开包后退出,不自动重连。
|
||||
- 发送消息或点击成功仅表示已提交到 Botcraft/网络层;服务器插件可能拒绝或改变效果。操作会真实移动、丢弃或破坏物品,失败后不回滚。
|
||||
- Ctrl+C、SIGTERM 或 `quit` 正常退出返回 0;启动异常、服务器断开返回 1。EOF 排空退出时,若有脚本失败返回 1,否则返回 0。
|
||||
|
||||
## 许可证
|
||||
|
||||
bilicraft-bot 采用 **GNU General Public License v3.0(GPLv3)**,完整条款见 [LICENSE](LICENSE)。
|
||||
|
||||
第三方依赖保留各自的版权声明和许可证,详见 [Botcraft LICENSE](3rd/Botcraft/LICENSE)、[GoogleTest LICENSE](3rd/googletest/LICENSE) 及其传递依赖的许可证文件。
|
||||
@@ -0,0 +1,5 @@
|
||||
# action: demo
|
||||
# 示例只用于离线检查;执行会实际发送聊天并切换快捷栏。
|
||||
sw 1
|
||||
import greet
|
||||
sendmsg @CantyOnion 操作示例结束
|
||||
@@ -0,0 +1,2 @@
|
||||
# action: greet
|
||||
sendmsg 你好,这是一条操作文件消息
|
||||
@@ -0,0 +1,23 @@
|
||||
# Keep the pinned upstream revision reproducible while carrying targeted fixes.
|
||||
# Never reset/checkout the submodule: refuse conflicting local edits instead.
|
||||
find_package(Git REQUIRED)
|
||||
set(_botcraft "${CMAKE_CURRENT_SOURCE_DIR}/3rd/Botcraft")
|
||||
foreach(_patch_name Botcraft-inventory-sync.patch Botcraft-item-frame-spawn.patch)
|
||||
set(_patch "${CMAKE_CURRENT_SOURCE_DIR}/patches/${_patch_name}")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_patch}")
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" apply --reverse --check "${_patch}"
|
||||
WORKING_DIRECTORY "${_botcraft}" RESULT_VARIABLE _already_applied OUTPUT_QUIET ERROR_QUIET)
|
||||
if(NOT _already_applied EQUAL 0)
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" apply --check "${_patch}"
|
||||
WORKING_DIRECTORY "${_botcraft}" RESULT_VARIABLE _can_apply OUTPUT_QUIET ERROR_VARIABLE _error)
|
||||
if(NOT _can_apply EQUAL 0)
|
||||
message(FATAL_ERROR "Botcraft patch ${_patch_name} conflicts with the checkout; preserve local changes and inspect it manually.\n${_error}")
|
||||
endif()
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" apply "${_patch}"
|
||||
WORKING_DIRECTORY "${_botcraft}" RESULT_VARIABLE _applied ERROR_VARIABLE _error)
|
||||
if(NOT _applied EQUAL 0)
|
||||
message(FATAL_ERROR "Could not apply Botcraft patch ${_patch_name}: ${_error}")
|
||||
endif()
|
||||
message(STATUS "Applied Botcraft patch ${_patch_name}")
|
||||
endif()
|
||||
endforeach()
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "botcraft/AI/Status.hpp"
|
||||
#include "botcraft/Game/Enums.hpp"
|
||||
|
||||
namespace Botcraft
|
||||
{
|
||||
class Window;
|
||||
}
|
||||
|
||||
namespace ProtocolCraft
|
||||
{
|
||||
class ServerboundContainerClickPacket;
|
||||
class Slot;
|
||||
}
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
class BilicraftClient;
|
||||
struct ActionCommand;
|
||||
|
||||
// Call only from the cooperative action runner (or a Botcraft behaviour leaf).
|
||||
// std::exception failures gain source:line context; Botcraft's non-standard
|
||||
// interruption exceptions are intentionally allowed to unwind unchanged.
|
||||
Botcraft::Status ExecuteAction(BilicraftClient &client, const ActionCommand &command);
|
||||
|
||||
// The runner must call this at each Yield while executing an action. Botcraft
|
||||
// clears player inputs every physics tick, so a scoped shift needs refreshing.
|
||||
void MaintainActionInputs(BilicraftClient &client);
|
||||
|
||||
// Validated, zero-based protocol indices. GUI rows refer ONLY to the container
|
||||
// area, never to the player inventory appended below it.
|
||||
short ActionGuiSlot(Botcraft::InventoryType type, int row, int col);
|
||||
short ActionBackpackSlot(int row, int col);
|
||||
short ActionHotbarIndex(int slot);
|
||||
void ValidateActionPosition(int x, int y, int z);
|
||||
|
||||
enum class FrameAttackIntent { None, TakeItem, RemoveFrame };
|
||||
// Ordinary left click never intentionally attacks a known-empty frame. Creative
|
||||
// attacks break filled frames too, so item-only clicks must reject that mode.
|
||||
FrameAttackIntent PlanFrameAttack(bool destroy, bool hasItem, bool creative);
|
||||
void ValidateFrameAttack(FrameAttackIntent expected, bool destroy, bool hasItem, bool creative);
|
||||
|
||||
// Empty-cursor player-inventory number-key SWAP. No local prediction; the
|
||||
// deliberately stale state id requests authoritative server synchronization.
|
||||
std::shared_ptr<ProtocolCraft::ServerboundContainerClickPacket> MakeBackpackSwapPacket(int row, int col, int slot);
|
||||
|
||||
// Resolve a drop target to 1..9; requested slot 0 uses the current zero-based selection.
|
||||
// THROW (mode 4) targets a slot directly without changing the selected hotbar.
|
||||
short ActionDropSlot(int requestedSlot, int selectedHotbarIndex);
|
||||
std::shared_ptr<ProtocolCraft::ServerboundContainerClickPacket> MakeHotbarDropPacket(int slot, bool all);
|
||||
ProtocolCraft::Slot RemainingAfterDrop(const ProtocolCraft::Slot &before, bool all);
|
||||
// Unlike Window::GetSlot, missing/reset inventory data is an error, not an empty slot.
|
||||
ProtocolCraft::Slot ReadDropSlot(const Botcraft::Window &window, short slot);
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
enum class ActionKind
|
||||
{
|
||||
Goto,
|
||||
RightClick,
|
||||
LeftClick,
|
||||
GuiRightClick,
|
||||
GuiLeftClick,
|
||||
SelectHotbar,
|
||||
SwapBackpack,
|
||||
Drop,
|
||||
SendCommand,
|
||||
SendMessage,
|
||||
Wait
|
||||
};
|
||||
|
||||
enum class EntityFace
|
||||
{
|
||||
Any,
|
||||
Top,
|
||||
Bottom,
|
||||
South,
|
||||
North,
|
||||
West,
|
||||
East
|
||||
};
|
||||
|
||||
struct ActionCommand
|
||||
{
|
||||
ActionKind kind;
|
||||
int x = 0, y = 0, z = 0, row = 0, col = 0, slot = 0;
|
||||
bool shift = false, destroy = false;
|
||||
// Drop: slot == 0 means the current main-hand hotbar slot; all drops the stack.
|
||||
bool all = false;
|
||||
std::string text, recipient;
|
||||
std::filesystem::path source;
|
||||
std::size_t line = 0;
|
||||
// Wait: exact milliseconds, from zero (yield) through 365 days inclusive.
|
||||
std::chrono::milliseconds waitDuration{0};
|
||||
// Click entry: target an item frame; Any searches all six block faces.
|
||||
bool entity = false;
|
||||
EntityFace entityFace = EntityFace::Any;
|
||||
};
|
||||
|
||||
struct ActionProgram
|
||||
{
|
||||
std::string name;
|
||||
std::vector<ActionCommand> commands;
|
||||
};
|
||||
|
||||
// Load UTF-8 .act text and expand imports in place. Coordinates/slots are 1-based
|
||||
// where applicable; block coordinates remain signed integers. Errors throw
|
||||
// std::runtime_error with source:line context (including import-site context).
|
||||
// The entry file must have a .act extension. Action/import names omit .act and
|
||||
// must be simple names resolving to same-directory name.act files whose action
|
||||
// headers match. Cycles and symlink escapes are rejected. Limits: 32 active
|
||||
// files, 100000 expanded commands, 4096 file loads, 1 MiB/file and 16 MiB total.
|
||||
// Wait syntax: wait digits[.digits] [s|ms|min|h|d], default s. The duration
|
||||
// must be an exact whole number of milliseconds and may not exceed 365 days.
|
||||
// Clicks optionally accept entry [t|b|s|n|w|e] (or full face names), with
|
||||
// the face immediately after entry. Existing shift and left-click destroy flags
|
||||
// may appear before or after entry; omitted entry retains block-click behavior.
|
||||
ActionProgram LoadActionFile(const std::filesystem::path &path);
|
||||
|
||||
// Parse one console game instruction using the .act grammar, without file I/O.
|
||||
// Blank/comment lines return nullopt. Wait/import require `run file.act` instead.
|
||||
// CR, LF and NUL are rejected; errors throw with <console>:1 context.
|
||||
std::optional<ActionCommand> ParseInteractiveCommand(std::string_view text);
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include "ActionFile.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
// Single-threaded cooperative scheduler. Only the owner may execute commands;
|
||||
// enqueue/submit are safe from that owner's Yield callback, never other threads.
|
||||
class ActionScheduler
|
||||
{
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using TaskId = std::uint64_t;
|
||||
enum class State { Ready, Running, Blocked };
|
||||
struct TaskInfo
|
||||
{
|
||||
TaskId id;
|
||||
std::string name;
|
||||
State state;
|
||||
std::size_t nextCommand;
|
||||
std::size_t commandCount;
|
||||
Clock::time_point wakeAt;
|
||||
};
|
||||
struct Work
|
||||
{
|
||||
ActionCommand command;
|
||||
TaskId taskId; // 0 for an interactive command
|
||||
bool interactive;
|
||||
};
|
||||
|
||||
TaskId Enqueue(ActionProgram program, Clock::time_point now = Clock::now());
|
||||
void WakeReady(Clock::time_point now);
|
||||
void SubmitInteractive(ActionCommand command);
|
||||
// Call only when no command is outstanding. Wait is handled here, never
|
||||
// passed to the game executor. Timers don't preempt a running action.
|
||||
std::optional<Work> Next(Clock::time_point now);
|
||||
void Finish(bool success);
|
||||
bool InteractivePending() const;
|
||||
bool HasWork() const;
|
||||
std::optional<Clock::time_point> NextWake() const;
|
||||
std::vector<TaskInfo> Tasks() const;
|
||||
std::vector<std::string> DrainEvents();
|
||||
|
||||
private:
|
||||
struct Task
|
||||
{
|
||||
TaskId id;
|
||||
ActionProgram program;
|
||||
std::size_t pc = 0;
|
||||
State state = State::Ready;
|
||||
Clock::time_point wakeAt{};
|
||||
std::uint64_t readyOrder = 0;
|
||||
};
|
||||
void RemoveActive(bool success);
|
||||
std::map<TaskId, Task> tasks;
|
||||
std::optional<TaskId> active;
|
||||
std::optional<ActionCommand> interactive;
|
||||
bool inFlight = false;
|
||||
bool interactiveInFlight = false;
|
||||
TaskId nextId = 1;
|
||||
std::uint64_t nextOrder = 1;
|
||||
std::size_t storedCommands = 0;
|
||||
std::vector<std::string> events;
|
||||
};
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
inline constexpr std::string_view kGameVersion = BILICRAFT_BOT_GAME_VERSION;
|
||||
inline constexpr std::string_view kDefaultServer = "mc.bilicraft.com:25577";
|
||||
|
||||
struct AppConfig
|
||||
{
|
||||
std::string server{kDefaultServer};
|
||||
// Microsoft credential-cache key, NOT an offline player name or password.
|
||||
std::string account;
|
||||
std::string actionFile;
|
||||
bool checkAction = false;
|
||||
bool help = false;
|
||||
};
|
||||
|
||||
// Arguments exclude argv[0]. Invalid or incomplete options throw invalid_argument.
|
||||
AppConfig ParseArguments(std::span<const std::string_view> arguments);
|
||||
std::string Usage();
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
|
||||
#include "botcraft/AI/TemplatedBehaviourClient.hpp"
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
// CRTP keeps future behaviour-tree leaves typed as BilicraftClient, with access
|
||||
// to its custom fields as well as Botcraft's world/inventory/physics managers.
|
||||
class BilicraftClient : public Botcraft::TemplatedBehaviourClient<BilicraftClient>
|
||||
{
|
||||
public:
|
||||
~BilicraftClient() override;
|
||||
bool WasDisconnected() const;
|
||||
bool HasEnteredPlay() const;
|
||||
|
||||
// Synchronous .act execution: tasks yield to a main-thread cancellation/
|
||||
// pacing hook instead of starting the upstream behaviour worker. Never use
|
||||
// this mode concurrently with StartBehaviour/BehaviourStep/SyncAction.
|
||||
void SetActionYieldHandler(std::function<void()> handler);
|
||||
void Yield() override;
|
||||
|
||||
protected:
|
||||
using Botcraft::TemplatedBehaviourClient<BilicraftClient>::Handle;
|
||||
void Handle(ProtocolCraft::ClientboundLoginPacket &packet) override;
|
||||
void Handle(ProtocolCraft::ClientboundLoginDisconnectPacket &packet) override;
|
||||
void Handle(ProtocolCraft::ClientboundDisconnectConfigurationPacket &packet) override;
|
||||
void Handle(ProtocolCraft::ClientboundDisconnectPacket &packet) override;
|
||||
|
||||
private:
|
||||
// Main-thread-only hook; it is never called by network/physics handlers.
|
||||
std::function<void()> actionYieldHandler;
|
||||
// Do not use upstream's non-atomic should_be_closed as our cross-thread signal.
|
||||
std::atomic<bool> disconnected{false};
|
||||
std::atomic<bool> enteredPlay{false};
|
||||
};
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
#include "ActionFile.h"
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
enum class ConsoleKind { Empty, Action, Run, Tasks, Help, Quit };
|
||||
struct ConsoleCommand
|
||||
{
|
||||
ConsoleKind kind = ConsoleKind::Empty;
|
||||
std::string path;
|
||||
std::optional<ActionCommand> action;
|
||||
};
|
||||
ConsoleCommand ParseConsoleCommand(std::string_view line);
|
||||
std::string ConsoleHelp();
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "ActionFile.h"
|
||||
#include "botcraft/Game/Vector3.hpp"
|
||||
|
||||
namespace Botcraft
|
||||
{
|
||||
class EntityManager;
|
||||
class ItemFrameEntity;
|
||||
}
|
||||
namespace ProtocolCraft
|
||||
{
|
||||
class ServerboundInteractPacket;
|
||||
}
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
// Protocol 774: the command names the SUPPORT block; the frame's network
|
||||
// spawn position is an integer attachment cell (support + outward face normal),
|
||||
// but absolute movement/sync can replace it with the actual frame center.
|
||||
// Invalid commands throw. Malformed frame positions/directions do not match.
|
||||
bool MatchesItemFrame(const Botcraft::ItemFrameEntity &frame, const ActionCommand &command);
|
||||
|
||||
// Only ordinary/glow item frames qualify. Zero matches returns nullptr;
|
||||
// multiple matches (including on one explicit face) throw instead of guessing.
|
||||
// The manager lock is released before this returns; callers must revalidate
|
||||
// identity/position immediately before sending, particularly after yielding.
|
||||
std::shared_ptr<Botcraft::ItemFrameEntity> FindItemFrame(Botcraft::EntityManager &manager,
|
||||
const ActionCommand &command);
|
||||
|
||||
// Visual/collision center, NOT the spawn position. Throws for invalid state.
|
||||
// Suitable for LookAt and conservative eye-to-center reach checks.
|
||||
Botcraft::Vector3<double> ItemFrameCenter(const Botcraft::ItemFrameEntity &frame);
|
||||
|
||||
// Read-only, bounded diagnostic: loaded count and at most eight nearby frames
|
||||
// with raw position, direction and decoded support. Never selects a fallback.
|
||||
std::string DescribeItemFrameTargets(Botcraft::EntityManager &manager, const ActionCommand &command);
|
||||
|
||||
// Action 0 + main hand for ordinary right-click, Action 1 without a hand for
|
||||
// attack; never interact-at (Action 2). Secondary is the actual sneaking state.
|
||||
std::shared_ptr<ProtocolCraft::ServerboundInteractPacket> MakeEntityInteractionPacket(int entityId, bool attack,
|
||||
bool secondary);
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,70 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
// Pure in-memory, byte-at-a-time terminal editor. No terminal I/O or threads.
|
||||
// Only complete, valid UTF-8 codepoints are inserted; incomplete codepoints stay
|
||||
// buffered until complete or interrupted, and malformed input is discarded.
|
||||
// Cursor() is a byte offset, always on a codepoint boundary. History is local to
|
||||
// this instance, excludes blank/consecutive duplicate lines, and is never saved.
|
||||
class LineEditor
|
||||
{
|
||||
public:
|
||||
static constexpr std::size_t MaxLineBytes = 64 * 1024;
|
||||
static constexpr std::size_t MaxHistoryEntries = 200;
|
||||
|
||||
// CR or LF returns the line and resets the editor. One LF immediately after
|
||||
// CR is swallowed, even across calls. Stop reading as soon as a line returns.
|
||||
// Ctrl-D on an empty line latches EOF; subsequent Feed calls do nothing.
|
||||
// Exceeding MaxLineBytes throws std::length_error without changing the line;
|
||||
// the caller can continue editing (e.g. backspace) and try again.
|
||||
std::optional<std::string> Feed(char byte);
|
||||
const std::string &Text() const;
|
||||
std::size_t Cursor() const;
|
||||
bool IsEof() const;
|
||||
|
||||
private:
|
||||
enum class EscapeState
|
||||
{
|
||||
None,
|
||||
Start,
|
||||
Intermediate,
|
||||
Csi,
|
||||
Ss3,
|
||||
String,
|
||||
StringEscape
|
||||
};
|
||||
|
||||
void FeedEscape(unsigned char byte);
|
||||
void FinishControlSequence(char finalByte);
|
||||
void ResetEscape();
|
||||
void InsertByte(unsigned char byte);
|
||||
void InsertCodepoint(const std::string &codepoint);
|
||||
void HistoryUp();
|
||||
void HistoryDown();
|
||||
void DeleteAtCursor();
|
||||
std::size_t PreviousBoundary() const;
|
||||
std::size_t NextBoundary() const;
|
||||
std::string Submit();
|
||||
|
||||
std::string text;
|
||||
std::size_t cursor = 0;
|
||||
bool eof = false;
|
||||
bool swallowLf = false;
|
||||
std::vector<std::string> history;
|
||||
std::size_t historyIndex = 0;
|
||||
std::string draft;
|
||||
std::size_t draftCursor = 0;
|
||||
std::string utf8Pending;
|
||||
std::size_t utf8Expected = 0;
|
||||
EscapeState escapeState = EscapeState::None;
|
||||
std::string escapeParameters;
|
||||
std::size_t escapeLength = 0;
|
||||
bool escapeTooLong = false;
|
||||
};
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
// Owns terminal state, never the supplied descriptors. The caller must be the
|
||||
// sole input reader and keep all descriptors open until destruction. Stop logger
|
||||
// callbacks before destruction. Control/input methods belong to the main thread;
|
||||
// WriteLog is safe from other threads. Do not write directly to the terminal
|
||||
// while split mode is active: use Out(), Err(), or WriteLog().
|
||||
class TerminalConsole
|
||||
{
|
||||
public:
|
||||
explicit TerminalConsole(int inputFd = 0, int outputFd = 1, int errorFd = 2);
|
||||
~TerminalConsole() noexcept;
|
||||
TerminalConsole(const TerminalConsole &) = delete;
|
||||
TerminalConsole &operator=(const TerminalConsole &) = delete;
|
||||
|
||||
// Call after login. Idempotent; unsupported terminals retain plain line
|
||||
// input (including prompts), with no terminal control sequences generated.
|
||||
void Start();
|
||||
bool IsSplit() const;
|
||||
std::optional<std::string> PollLine();
|
||||
bool IsEof() const;
|
||||
void SetInputEnabled(bool enabled);
|
||||
void Tick();
|
||||
std::ostream &Out();
|
||||
std::ostream &Err();
|
||||
void WriteLog(std::string_view text, bool error = false) noexcept;
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl;
|
||||
};
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
// Incremental input with no wait for a user, a writer, or a complete line.
|
||||
// The caller must be the sole reader of fd (including its duplicated descriptors)
|
||||
// and must keep it open. This class never closes fd or changes its flags/mode.
|
||||
// Do not mix it with std::cin/getline: their buffering can read ahead.
|
||||
//
|
||||
// POSIX supports canonical terminals, pipes and ordinary files. Windows supports
|
||||
// redirected pipes and ordinary files; native consoles/other handle types fail
|
||||
// explicitly rather than falling back to a potentially blocking cooked read.
|
||||
class TerminalInput
|
||||
{
|
||||
public:
|
||||
static constexpr std::size_t MaxLineBytes = 64 * 1024;
|
||||
|
||||
TerminalInput();
|
||||
explicit TerminalInput(int fd);
|
||||
TerminalInput(const TerminalInput &) = delete;
|
||||
TerminalInput &operator=(const TerminalInput &) = delete;
|
||||
|
||||
// Consumes at most one line, stopping at its LF without reading the next
|
||||
// byte. nullopt means not ready, a partial line, or EOF (see IsEof()). Work
|
||||
// per call is bounded, so long lines may need several calls even from files.
|
||||
// A final nonempty line without LF is returned once, with IsEof() == true.
|
||||
// CR immediately before LF is removed; other CR bytes are preserved.
|
||||
// Up to MaxLineBytes bytes before LF are accepted (including any CR).
|
||||
// I/O/unsupported errors throw std::runtime_error once; overlong lines throw
|
||||
// std::length_error once. Both discard the partial line and latch EOF.
|
||||
std::optional<std::string> PollLine();
|
||||
bool IsEof() const;
|
||||
bool IsInteractive() const;
|
||||
|
||||
private:
|
||||
enum class ReadResult
|
||||
{
|
||||
NotReady,
|
||||
Byte,
|
||||
End
|
||||
};
|
||||
|
||||
ReadResult ReadByte(char &byte);
|
||||
[[noreturn]] void Fail(const std::string &message);
|
||||
std::string TakeLine(bool removeCr);
|
||||
|
||||
int fd;
|
||||
bool interactive;
|
||||
bool eof = false;
|
||||
std::string partial;
|
||||
};
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,218 @@
|
||||
#include "AppConfig.h"
|
||||
#include "ActionFile.h"
|
||||
#include "ActionExecutor.h"
|
||||
#include "ActionScheduler.h"
|
||||
#include "ConsoleCommand.h"
|
||||
#include "BilicraftClient.h"
|
||||
#include "TerminalConsole.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <cstdio>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "botcraft/Utilities/Logger.hpp"
|
||||
|
||||
namespace
|
||||
{
|
||||
volatile std::sig_atomic_t stopRequested = 0;
|
||||
void RequestStop(int) { stopRequested = 1; }
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
using namespace Bilicraft;
|
||||
using namespace std::chrono_literals;
|
||||
using Clock = ActionScheduler::Clock;
|
||||
try
|
||||
{
|
||||
std::vector<std::string_view> arguments;
|
||||
for (int i = 1; i < argc; ++i) arguments.emplace_back(argv[i]);
|
||||
const auto config = ParseArguments(arguments);
|
||||
if (config.help)
|
||||
{
|
||||
std::cout << Usage();
|
||||
return 0;
|
||||
}
|
||||
// Validate the entire initial import graph before authentication/effects.
|
||||
std::optional<ActionProgram> program;
|
||||
if (!config.actionFile.empty())
|
||||
{
|
||||
program = LoadActionFile(config.actionFile);
|
||||
if (config.checkAction)
|
||||
{
|
||||
std::cout << "Action '" << program->name << "': " << program->commands.size()
|
||||
<< " commands validated (including imports).\n";
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
std::signal(SIGINT, RequestStop);
|
||||
std::signal(SIGTERM, RequestStop);
|
||||
// Declared before the client: join network/physics logging before the
|
||||
// console restores the terminal. A weak callback cannot outlive it.
|
||||
auto console = std::make_shared<TerminalConsole>();
|
||||
Botcraft::Logger::GetInstance().SetLogFunc([weak = std::weak_ptr<TerminalConsole>(console)](const std::string &message) {
|
||||
if (const auto output = weak.lock())
|
||||
output->WriteLog(message);
|
||||
else
|
||||
{
|
||||
std::fwrite(message.data(), 1, message.size(), stdout);
|
||||
std::fflush(stdout);
|
||||
}
|
||||
});
|
||||
console->Out() << "bilicraft-bot | Minecraft Java " << kGameVersion << " | " << config.server << '\n';
|
||||
BilicraftClient client;
|
||||
if (stopRequested) return 0;
|
||||
client.ConnectMicrosoft(config.server, config.account);
|
||||
if (stopRequested) return 0;
|
||||
// Authentication is synchronous upstream. Only the subsequent login wait
|
||||
// and game execution can cooperate with cancellation.
|
||||
const auto loginDeadline = Clock::now() + 60s;
|
||||
while (!stopRequested && !client.WasDisconnected() && !client.HasEnteredPlay())
|
||||
{
|
||||
if (Clock::now() >= loginDeadline)
|
||||
throw std::runtime_error("Timed out waiting to enter the game (60 seconds)");
|
||||
std::this_thread::sleep_for(50ms);
|
||||
}
|
||||
if (stopRequested || client.WasDisconnected())
|
||||
{
|
||||
client.Disconnect();
|
||||
return stopRequested ? 0 : 1;
|
||||
}
|
||||
|
||||
ActionScheduler scheduler;
|
||||
if (program) scheduler.Enqueue(std::move(*program));
|
||||
console->Start();
|
||||
bool eofReported = false;
|
||||
bool actionFailed = false;
|
||||
std::optional<Clock::time_point> drainedSince;
|
||||
console->Out() << "Entered game. " << ConsoleHelp();
|
||||
const auto printEvents = [&] {
|
||||
for (const auto &event : scheduler.DrainEvents()) console->Out() << event << '\n';
|
||||
console->Out().flush();
|
||||
};
|
||||
const auto pumpConsole = [&] {
|
||||
scheduler.WakeReady(Clock::now());
|
||||
console->SetInputEnabled(!scheduler.InteractivePending() && !console->IsEof() && !stopRequested);
|
||||
console->Tick();
|
||||
if (scheduler.InteractivePending() || console->IsEof() || stopRequested) return;
|
||||
try
|
||||
{
|
||||
const auto line = console->PollLine();
|
||||
if (!line) return;
|
||||
const auto request = ParseConsoleCommand(*line);
|
||||
switch (request.kind)
|
||||
{
|
||||
case ConsoleKind::Empty: break;
|
||||
case ConsoleKind::Help: console->Out() << ConsoleHelp(); break;
|
||||
case ConsoleKind::Quit: stopRequested = 1; break;
|
||||
case ConsoleKind::Run:
|
||||
scheduler.Enqueue(LoadActionFile(request.path));
|
||||
break;
|
||||
case ConsoleKind::Tasks:
|
||||
{
|
||||
const auto now = Clock::now();
|
||||
const auto tasks = scheduler.Tasks();
|
||||
if (tasks.empty()) console->Out() << "No queued actions.\n";
|
||||
for (const auto &task : tasks)
|
||||
{
|
||||
console->Out() << '#' << task.id << " '" << task.name << "' "
|
||||
<< (task.state == ActionScheduler::State::Blocked ? "blocked" :
|
||||
task.state == ActionScheduler::State::Running ? "running" : "ready")
|
||||
<< " command " << task.nextCommand << '/' << task.commandCount;
|
||||
if (task.state == ActionScheduler::State::Blocked)
|
||||
console->Out() << " remaining=" << std::max<std::int64_t>(0,
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(task.wakeAt - now).count())
|
||||
<< "ms";
|
||||
console->Out() << '\n';
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ConsoleKind::Action:
|
||||
scheduler.SubmitInteractive(*request.action);
|
||||
console->SetInputEnabled(false);
|
||||
console->Out() << "Interactive command pending (runs at the next action boundary).\n";
|
||||
break;
|
||||
}
|
||||
printEvents();
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
console->Err() << "Console: " << error.what() << '\n';
|
||||
}
|
||||
};
|
||||
printEvents();
|
||||
while (!stopRequested && !client.WasDisconnected())
|
||||
{
|
||||
pumpConsole();
|
||||
if (stopRequested) break;
|
||||
const auto work = scheduler.Next(Clock::now());
|
||||
printEvents();
|
||||
if (work)
|
||||
{
|
||||
drainedSince.reset();
|
||||
const auto commandDeadline = Clock::now() + 60s;
|
||||
client.SetActionYieldHandler([&client, &pumpConsole, commandDeadline] {
|
||||
pumpConsole();
|
||||
if (stopRequested) throw std::runtime_error("Action cancelled");
|
||||
if (client.WasDisconnected()) throw std::runtime_error("Server disconnected during action");
|
||||
if (Clock::now() >= commandDeadline)
|
||||
throw std::runtime_error("Action command timed out (60 seconds)");
|
||||
std::this_thread::sleep_for(10ms);
|
||||
});
|
||||
try
|
||||
{
|
||||
client.Yield();
|
||||
if (ExecuteAction(client, work->command) != Botcraft::Status::Success)
|
||||
throw std::runtime_error(work->command.source.string() + ":" +
|
||||
std::to_string(work->command.line) + ": action command failed");
|
||||
scheduler.Finish(true);
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
console->Err() << "Execution failed: " << error.what() << '\n';
|
||||
scheduler.Finish(false);
|
||||
if (!work->interactive) actionFailed = true;
|
||||
}
|
||||
client.SetActionYieldHandler({});
|
||||
printEvents();
|
||||
continue;
|
||||
}
|
||||
if (console->IsEof() && !eofReported)
|
||||
{
|
||||
console->Out() << "Console input closed; draining queued actions before disconnect.\n";
|
||||
eofReported = true;
|
||||
}
|
||||
if (console->IsEof() && !scheduler.HasWork())
|
||||
{
|
||||
// Best-effort grace for upstream's asynchronous send queue; it
|
||||
// provides no flush API. Do not disconnect on the last Send().
|
||||
if (!drainedSince) drainedSince = Clock::now();
|
||||
if (Clock::now() - *drainedSince >= 500ms) break;
|
||||
}
|
||||
auto sleep = 50ms;
|
||||
if (const auto wake = scheduler.NextWake())
|
||||
sleep = std::clamp(std::chrono::duration_cast<std::chrono::milliseconds>(*wake - Clock::now()),
|
||||
0ms, sleep);
|
||||
std::this_thread::sleep_for(sleep);
|
||||
}
|
||||
const bool disconnected = client.WasDisconnected();
|
||||
client.SetActionYieldHandler({});
|
||||
client.Disconnect();
|
||||
return stopRequested ? 0 : (disconnected || actionFailed ? 1 : 0);
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
std::cerr << "bilicraft-bot failed: " << error.what() << '\n';
|
||||
return stopRequested ? 0 : 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
diff --git a/botcraft/src/Game/Inventory/InventoryManager.cpp b/botcraft/src/Game/Inventory/InventoryManager.cpp
|
||||
index b35f052b..fdc10155 100644
|
||||
--- a/botcraft/src/Game/Inventory/InventoryManager.cpp
|
||||
+++ b/botcraft/src/Game/Inventory/InventoryManager.cpp
|
||||
@@ -8,6 +8,19 @@ using namespace ProtocolCraft;
|
||||
|
||||
namespace Botcraft
|
||||
{
|
||||
+ namespace
|
||||
+ {
|
||||
+ // Player Inventory indices differ from inventory-menu/window indices.
|
||||
+ short PlayerInventoryToMenuSlot(const int index)
|
||||
+ {
|
||||
+ if (index >= 0 && index < 9) return static_cast<short>(36 + index);
|
||||
+ if (index >= 9 && index < 36) return static_cast<short>(index);
|
||||
+ if (index >= 36 && index < 40) return static_cast<short>(44 - index);
|
||||
+ if (index == 40) return Window::INVENTORY_OFFHAND_INDEX;
|
||||
+ return -1;
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
InventoryManager::InventoryManager(const std::shared_ptr<NetworkManager>& network_manager) : network_manager(network_manager)
|
||||
{
|
||||
std::scoped_lock<std::shared_mutex> lock(inventory_manager_mutex);
|
||||
@@ -556,13 +569,10 @@ namespace Botcraft
|
||||
// Slot index is starting in the hotbar, THEN in the main storage in this case :)
|
||||
else if (packet.GetContainerId() == -2)
|
||||
{
|
||||
- if (packet.GetSlot() < Window::INVENTORY_OFFHAND_INDEX - Window::INVENTORY_HOTBAR_START)
|
||||
- {
|
||||
- SetSlot(Window::PLAYER_INVENTORY_INDEX, Window::INVENTORY_HOTBAR_START + packet.GetSlot(), packet.GetItemStack());
|
||||
- }
|
||||
- else
|
||||
+ const short slot = PlayerInventoryToMenuSlot(packet.GetSlot());
|
||||
+ if (slot >= 0)
|
||||
{
|
||||
- SetSlot(Window::PLAYER_INVENTORY_INDEX, packet.GetSlot() + Window::INVENTORY_OFFHAND_INDEX - Window::INVENTORY_HOTBAR_START, packet.GetItemStack());
|
||||
+ SetSlot(Window::PLAYER_INVENTORY_INDEX, slot, packet.GetItemStack());
|
||||
}
|
||||
}
|
||||
else if (packet.GetContainerId() >= 0)
|
||||
@@ -586,6 +596,10 @@ namespace Botcraft
|
||||
window->SetContent(packet.GetItems());
|
||||
}
|
||||
|
||||
+#if PROTOCOL_VERSION > 755
|
||||
+ SetCursor(packet.GetCarriedItem());
|
||||
+#endif
|
||||
+
|
||||
#if PROTOCOL_VERSION > 755 /* > 1.17 */
|
||||
if (packet.GetContainerId() >= 0)
|
||||
{
|
||||
@@ -694,13 +708,16 @@ namespace Botcraft
|
||||
#if PROTOCOL_VERSION > 767 /* > 1.21.1 */
|
||||
void InventoryManager::Handle(ClientboundSetCursorItemPacket& packet)
|
||||
{
|
||||
- // Not sure about this one, I can't figure out when it's sent by the server
|
||||
- SetSlot(Window::PLAYER_INVENTORY_INDEX, Window::INVENTORY_HOTBAR_START + index_hotbar_selected, packet.GetContents());
|
||||
+ SetCursor(packet.GetContents());
|
||||
}
|
||||
|
||||
void InventoryManager::Handle(ProtocolCraft::ClientboundSetPlayerInventoryPacket& packet)
|
||||
{
|
||||
- SetSlot(Window::PLAYER_INVENTORY_INDEX, static_cast<short>(packet.GetSlot()), packet.GetContents());
|
||||
+ const short slot = PlayerInventoryToMenuSlot(packet.GetSlot());
|
||||
+ if (slot >= 0)
|
||||
+ {
|
||||
+ SetSlot(Window::PLAYER_INVENTORY_INDEX, slot, packet.GetContents());
|
||||
+ }
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
diff --git a/botcraft/src/Game/Entities/EntityManager.cpp b/botcraft/src/Game/Entities/EntityManager.cpp
|
||||
index 3925686d..cc401e99 100644
|
||||
--- a/botcraft/src/Game/Entities/EntityManager.cpp
|
||||
+++ b/botcraft/src/Game/Entities/EntityManager.cpp
|
||||
@@ -1,6 +1,9 @@
|
||||
#include "botcraft/Game/Entities/EntityManager.hpp"
|
||||
#include "botcraft/Game/Entities/entities/Entity.hpp"
|
||||
#include "botcraft/Game/Entities/entities/UnknownEntity.hpp"
|
||||
+#if PROTOCOL_VERSION > 770 /* > 1.21.5 */
|
||||
+#include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp"
|
||||
+#endif
|
||||
#include "botcraft/Game/Entities/LocalPlayer.hpp"
|
||||
#include "botcraft/Network/NetworkManager.hpp"
|
||||
|
||||
@@ -238,6 +241,23 @@ namespace Botcraft
|
||||
entity->SetSpeed(Vector3<double>(packet.GetMovement()));
|
||||
#endif
|
||||
|
||||
+#if PROTOCOL_VERSION > 770 /* > 1.21.5 */
|
||||
+ if (entity->GetType() == EntityType::ItemFrame || entity->GetType() == EntityType::GlowItemFrame)
|
||||
+ {
|
||||
+ // Official 1.21.11 client: ItemFrame.getAddEntityPacket supplies
|
||||
+ // getDirection().get3DDataValue() and getPos() to AddEntityPacket.
|
||||
+ // Its (Entity, int, BlockPos) constructor sends integer anchor XYZ;
|
||||
+ // recreateFromPacket sets direction from Data, not from yaw/pitch.
|
||||
+ // Keep XYZ unchanged and initialize before publishing the entity:
|
||||
+ // metadata may arrive later (or omit the default South direction).
|
||||
+ const int direction = packet.GetData();
|
||||
+ // Do not wrap malformed values into a valid face or retain South:
|
||||
+ // -1 is deliberately invalid so targeting helpers can reject it.
|
||||
+ std::static_pointer_cast<ItemFrameEntity>(entity)->SetDataDirection(
|
||||
+ direction >= 0 && direction <= 5 ? direction : -1);
|
||||
+ }
|
||||
+#endif
|
||||
+
|
||||
std::scoped_lock<std::shared_mutex> lock(entity_manager_mutex);
|
||||
entities[packet.GetEntityId()] = entity;
|
||||
}
|
||||
diff --git a/botcraft/src/Game/Entities/entities/decoration/HangingEntity.cpp b/botcraft/src/Game/Entities/entities/decoration/HangingEntity.cpp
|
||||
index 8730b02b..0b9f13d2 100644
|
||||
--- a/botcraft/src/Game/Entities/entities/decoration/HangingEntity.cpp
|
||||
+++ b/botcraft/src/Game/Entities/entities/decoration/HangingEntity.cpp
|
||||
@@ -53,7 +53,18 @@ namespace Botcraft
|
||||
else if (index - hierarchy_metadata_count < metadata_count)
|
||||
{
|
||||
std::scoped_lock<std::shared_mutex> lock(entity_mutex);
|
||||
- metadata[metadata_names[index - hierarchy_metadata_count]] = value;
|
||||
+ // DATA_DIRECTION uses the DIRECTION serializer (not INT) in the
|
||||
+ // official 1.21.11 client. Entity::LoadMetadataFromRawArray stores
|
||||
+ // that as Direction; normalize it to our existing int getter/setter
|
||||
+ // representation without wrapping invalid values into valid faces.
|
||||
+ if (const auto* direction = std::any_cast<Direction>(&value))
|
||||
+ {
|
||||
+ metadata[metadata_names[index - hierarchy_metadata_count]] = static_cast<int>(*direction);
|
||||
+ }
|
||||
+ else
|
||||
+ {
|
||||
+ metadata[metadata_names[index - hierarchy_metadata_count]] = value;
|
||||
+ }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,622 @@
|
||||
#include "ActionExecutor.h"
|
||||
|
||||
#include "ActionFile.h"
|
||||
#include "BilicraftClient.h"
|
||||
#include "EntityInteraction.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "botcraft/AI/Tasks/DigTask.hpp"
|
||||
#include "botcraft/AI/Tasks/InventoryTasks.hpp"
|
||||
#include "botcraft/AI/Tasks/PathfindingTask.hpp"
|
||||
#include "botcraft/Game/Entities/LocalPlayer.hpp"
|
||||
#include "botcraft/Game/Entities/EntityManager.hpp"
|
||||
#include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp"
|
||||
#include "botcraft/Game/Inventory/InventoryManager.hpp"
|
||||
#include "botcraft/Game/Inventory/Window.hpp"
|
||||
#include "botcraft/Game/World/Blockstate.hpp"
|
||||
#include "botcraft/Game/World/World.hpp"
|
||||
#include "botcraft/Network/NetworkManager.hpp"
|
||||
#include "botcraft/Utilities/Logger.hpp"
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Botcraft::Status;
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
void Require(bool condition, const std::string &message)
|
||||
{
|
||||
if (!condition)
|
||||
throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
void CheckConnection(BilicraftClient &client)
|
||||
{
|
||||
Require(!client.WasDisconnected(), "disconnected while executing action");
|
||||
Require(client.HasEnteredPlay() && client.GetNetworkManager() &&
|
||||
client.GetNetworkManager()->GetConnectionState() == ProtocolCraft::ConnectionState::Play,
|
||||
"client is not in Play state");
|
||||
}
|
||||
|
||||
template <typename Predicate>
|
||||
void Await(BilicraftClient &client, Predicate ready, std::chrono::milliseconds timeout, const char *description)
|
||||
{
|
||||
const auto deadline = Clock::now() + timeout;
|
||||
while (!ready())
|
||||
{
|
||||
CheckConnection(client);
|
||||
Require(Clock::now() < deadline, std::string("timeout waiting for ") + description);
|
||||
client.Yield();
|
||||
}
|
||||
CheckConnection(client);
|
||||
}
|
||||
|
||||
void WaitForManagers(BilicraftClient &client)
|
||||
{
|
||||
Await(client,
|
||||
[&] {
|
||||
if (!client.GetWorld() || !client.GetLocalPlayer() || !client.GetPhysicsManager() ||
|
||||
!client.GetInventoryManager() || !client.GetInventoryManager()->GetPlayerInventory())
|
||||
return false;
|
||||
// Botcraft initializes local Y to NaN until PlayerPosition is
|
||||
// processed under the player's mutex. Non-null managers alone
|
||||
// are not sufficient to begin pathfinding or block interaction.
|
||||
const auto position = client.GetLocalPlayer()->GetPosition();
|
||||
return std::isfinite(position.x) && std::isfinite(position.y) && std::isfinite(position.z);
|
||||
},
|
||||
10s, "world/player/physics/inventory managers and spawn position");
|
||||
}
|
||||
|
||||
struct SneakContext
|
||||
{
|
||||
BilicraftClient *client;
|
||||
std::shared_ptr<Botcraft::LocalPlayer> player;
|
||||
};
|
||||
thread_local SneakContext *activeSneak = nullptr;
|
||||
|
||||
void SendSneak(const std::shared_ptr<Botcraft::NetworkManager> &network, bool sneak)
|
||||
{
|
||||
// Since 1.21.6 shift is sent via PlayerInput, not PlayerCommand. Send
|
||||
// explicitly as well as setting the input so the immediately following
|
||||
// UseItemOn cannot overtake the physics tick that presses shift. Actions
|
||||
// are sequential and stationary here; all movement keys remain released.
|
||||
auto packet = std::make_shared<ProtocolCraft::ServerboundPlayerInputPacket>();
|
||||
packet->SetShift(sneak);
|
||||
network->Send(packet);
|
||||
}
|
||||
|
||||
class ScopedSneak
|
||||
{
|
||||
public:
|
||||
ScopedSneak(BilicraftClient &client, bool enabled)
|
||||
: context{&client, client.GetLocalPlayer()}, network(client.GetNetworkManager()), enabled(enabled)
|
||||
{
|
||||
Require(!enabled || activeSneak == nullptr, "nested shifted actions are unsupported");
|
||||
if (!enabled)
|
||||
return;
|
||||
// .act owns the inputs exclusively and has no persistent sneak mode.
|
||||
// Do not snapshot delayed server metadata: it can still say 'sneaking'
|
||||
// from the previous command and accidentally latch shift after this one.
|
||||
// Publish the thread-local context only after initialization succeeds;
|
||||
// constructor failure must leave no dangling pointer.
|
||||
try
|
||||
{
|
||||
context.player->SetInputsSneak(true);
|
||||
SendSneak(network, true);
|
||||
activeSneak = &context;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
Restore();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
~ScopedSneak() noexcept
|
||||
{
|
||||
if (enabled)
|
||||
{
|
||||
activeSneak = nullptr;
|
||||
Restore();
|
||||
}
|
||||
}
|
||||
|
||||
ScopedSneak(const ScopedSneak &) = delete;
|
||||
ScopedSneak &operator=(const ScopedSneak &) = delete;
|
||||
|
||||
private:
|
||||
void Restore() noexcept
|
||||
{
|
||||
// Never yield in an unwinding destructor. Captured shared_ptrs remain
|
||||
// valid even if connection teardown has begun.
|
||||
try
|
||||
{
|
||||
context.player->SetInputsSneak(false);
|
||||
if (network && network->GetConnectionState() == ProtocolCraft::ConnectionState::Play)
|
||||
SendSneak(network, false);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
// Best effort only: a dead connection cannot accept a release.
|
||||
}
|
||||
}
|
||||
|
||||
SneakContext context;
|
||||
std::shared_ptr<Botcraft::NetworkManager> network;
|
||||
bool enabled;
|
||||
};
|
||||
|
||||
Botcraft::Vector3<double> BlockCenter(const ActionCommand &command)
|
||||
{
|
||||
return Botcraft::Vector3<double>(command.x + 0.5, command.y + 0.5, command.z + 0.5);
|
||||
}
|
||||
|
||||
void CheckTarget(BilicraftClient &client, const ActionCommand &command)
|
||||
{
|
||||
const Botcraft::Position pos(command.x, command.y, command.z);
|
||||
Await(client, [&] { return client.GetWorld()->GetBlock(pos) != nullptr; }, 5s, "target chunk to load");
|
||||
const auto *block = client.GetWorld()->GetBlock(pos);
|
||||
Require(block && !block->IsAir(), "target is air or is no longer loaded");
|
||||
const auto player = client.GetLocalPlayer();
|
||||
const auto eyes = player->GetPosition() + Botcraft::Vector3<double>(0.0, player->GetEyeHeight(), 0.0);
|
||||
const double range = player->GetAttributePlayerBlockInteractionRangeValue();
|
||||
// Conservative center test: no hidden automatic navigation, including at
|
||||
// reach boundaries. This does not claim to implement server line of sight.
|
||||
Require(range > 0 && eyes.SqrDist(BlockCenter(command)) < range * range,
|
||||
"target is outside block interaction reach; use goto explicitly");
|
||||
}
|
||||
|
||||
void Swing(BilicraftClient &client)
|
||||
{
|
||||
auto packet = std::make_shared<ProtocolCraft::ServerboundSwingPacket>();
|
||||
packet->SetHand(static_cast<int>(Botcraft::Hand::Main));
|
||||
client.GetNetworkManager()->Send(packet);
|
||||
}
|
||||
|
||||
Status ClickBlock(BilicraftClient &client, const ActionCommand &command)
|
||||
{
|
||||
CheckTarget(client, command);
|
||||
if (Botcraft::LookAt(client, BlockCenter(command), true, true) != Status::Success)
|
||||
return Status::Failure;
|
||||
CheckTarget(client, command); // The world/player may have changed during Yield.
|
||||
ScopedSneak sneak(client, command.shift);
|
||||
const Botcraft::Position pos(command.x, command.y, command.z);
|
||||
if (command.kind == ActionKind::LeftClick)
|
||||
{
|
||||
if (command.destroy)
|
||||
return Botcraft::Dig(client, pos, true, Botcraft::PlayerDiggingFace::Up, false);
|
||||
// Never send StartDigging: creative and instant-break blocks could be
|
||||
// destroyed by that packet alone, even if immediately cancelled.
|
||||
Swing(client);
|
||||
return Status::Success;
|
||||
}
|
||||
|
||||
// InteractWithBlock unconditionally pathfinds when its own range check
|
||||
// fails. Use its verified packet layout directly to guarantee no movement.
|
||||
auto packet = std::make_shared<ProtocolCraft::ServerboundUseItemOnPacket>();
|
||||
packet->SetLocation(pos.ToNetworkPosition());
|
||||
packet->SetDirection(static_cast<int>(Botcraft::PlayerDiggingFace::Up));
|
||||
packet->SetCursorPositionX(0.5f);
|
||||
packet->SetCursorPositionY(1.0f);
|
||||
packet->SetCursorPositionZ(0.5f);
|
||||
packet->SetInside(false);
|
||||
packet->SetWorldBorderHit(false);
|
||||
packet->SetHand(static_cast<int>(Botcraft::Hand::Main));
|
||||
packet->SetSequence(client.GetWorld()->GetNextWorldInteractionSequenceId());
|
||||
client.GetNetworkManager()->Send(packet);
|
||||
Swing(client);
|
||||
return Status::Success;
|
||||
}
|
||||
|
||||
Status ClickItemFrame(BilicraftClient &client, const ActionCommand &command)
|
||||
{
|
||||
Await(client, [&] { return client.GetEntityManager() != nullptr; }, 5s, "entity manager");
|
||||
const auto manager = client.GetEntityManager();
|
||||
std::shared_ptr<Botcraft::ItemFrameEntity> frame;
|
||||
try
|
||||
{
|
||||
Await(client, [&] { frame = FindItemFrame(*manager, command); return frame != nullptr; },
|
||||
5s, "a unique item frame on the requested block face(s)");
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
throw std::runtime_error(std::string(error.what()) + "; " + DescribeItemFrameTargets(*manager, command));
|
||||
}
|
||||
const auto id = frame->GetEntityID();
|
||||
const auto uuid = frame->GetUUID();
|
||||
const auto sameFrame = [&] {
|
||||
return manager->GetEntity(id) == frame && frame->GetUUID() == uuid;
|
||||
};
|
||||
const auto checkTarget = [&] {
|
||||
CheckConnection(client);
|
||||
Require(client.GetEntityManager() == manager, "entity manager changed during frame interaction");
|
||||
Require(sameFrame(), "item frame disappeared or was replaced (not retried)");
|
||||
Require(MatchesItemFrame(*frame, command), "item frame moved or changed its attached face");
|
||||
// Recheck uniqueness after LookAt/Yield, not just when first selected.
|
||||
Require(FindItemFrame(*manager, command) == frame, "item frame selection changed");
|
||||
const auto player = client.GetLocalPlayer();
|
||||
const auto eyes = player->GetPosition() + Botcraft::Vector3<double>(0, player->GetEyeHeight(), 0);
|
||||
const double range = player->GetAttributeEntityInteractionRangeValue();
|
||||
const auto center = ItemFrameCenter(*frame);
|
||||
Require(std::isfinite(range) && range > 0 && eyes.SqrDist(center) < range * range,
|
||||
"item frame is outside entity interaction reach; use goto explicitly");
|
||||
};
|
||||
checkTarget();
|
||||
if (Botcraft::LookAt(client, ItemFrameCenter(*frame), true, true) != Status::Success)
|
||||
return Status::Failure;
|
||||
checkTarget();
|
||||
ScopedSneak sneak(client, command.shift);
|
||||
if (command.kind == ActionKind::RightClick)
|
||||
{
|
||||
client.GetNetworkManager()->Send(MakeEntityInteractionPacket(id, false, command.shift));
|
||||
Swing(client);
|
||||
return Status::Success; // Like block right click: sent once, no generic server acknowledgement.
|
||||
}
|
||||
|
||||
const auto plan = [&] {
|
||||
const auto player = client.GetLocalPlayer();
|
||||
return PlanFrameAttack(command.destroy, !frame->GetDataItem().IsEmptySlot(),
|
||||
player->GetInstabuild() || player->GetGameMode() == Botcraft::GameType::Creative);
|
||||
};
|
||||
const auto intent = plan();
|
||||
if (intent == FrameAttackIntent::None)
|
||||
{
|
||||
Swing(client); // Known-empty frame: keep it, and never send Attack.
|
||||
return Status::Success;
|
||||
}
|
||||
const auto attack = [&](FrameAttackIntent expected) {
|
||||
checkTarget();
|
||||
const auto player = client.GetLocalPlayer();
|
||||
ValidateFrameAttack(expected, command.destroy, !frame->GetDataItem().IsEmptySlot(),
|
||||
player->GetInstabuild() || player->GetGameMode() == Botcraft::GameType::Creative);
|
||||
client.GetNetworkManager()->Send(MakeEntityInteractionPacket(id, true, command.shift));
|
||||
Swing(client);
|
||||
};
|
||||
if (intent == FrameAttackIntent::TakeItem)
|
||||
{
|
||||
// Abort a changed plan before sending, rather than treating a removal
|
||||
// attack as a successful take-item phase and sending a duplicate attack.
|
||||
attack(FrameAttackIntent::TakeItem);
|
||||
Await(client, [&] {
|
||||
Require(client.GetEntityManager() == manager, "entity manager changed while taking frame item");
|
||||
if (!sameFrame())
|
||||
{
|
||||
Require(command.destroy, "item frame was removed/replaced while taking its item (not retried)");
|
||||
return true;
|
||||
}
|
||||
return frame->GetDataItem().IsEmptySlot();
|
||||
}, 5s, "frame item removal (not retried)");
|
||||
if (!command.destroy || !sameFrame()) return Status::Success;
|
||||
// A second attack is a distinct, explicitly requested removal phase,
|
||||
// not a retry. Never attack a newly inserted item or a replacement frame.
|
||||
checkTarget();
|
||||
Require(frame->GetDataItem().IsEmptySlot(), "frame was refilled before removal; not attacking again");
|
||||
}
|
||||
attack(FrameAttackIntent::RemoveFrame);
|
||||
Await(client, [&] {
|
||||
Require(client.GetEntityManager() == manager, "entity manager changed while removing frame");
|
||||
return !sameFrame();
|
||||
}, 5s, "item frame removal (not retried)");
|
||||
return Status::Success;
|
||||
}
|
||||
|
||||
Status ClickGui(BilicraftClient &client, const ActionCommand &command)
|
||||
{
|
||||
const auto inventory = client.GetInventoryManager();
|
||||
Await(client, [&] { return inventory->GetFirstOpenedWindowId() > 0; }, 5s, "an open container GUI");
|
||||
const short id = inventory->GetFirstOpenedWindowId();
|
||||
const auto window = inventory->GetWindow(id);
|
||||
Require(window != nullptr, "container closed before GUI click");
|
||||
const short slot = ActionGuiSlot(window->GetType(), command.row, command.col);
|
||||
Await(client, [&] { return window->GetSlots().contains(slot); }, 5s, "container contents");
|
||||
Require(inventory->GetFirstOpenedWindowId() == id && inventory->GetWindow(id) == window,
|
||||
"container changed before GUI click");
|
||||
return Botcraft::ClickSlotInContainer(client, id, slot, 0, command.kind == ActionKind::GuiRightClick ? 1 : 0);
|
||||
}
|
||||
|
||||
std::vector<unsigned char> SlotBytes(const ProtocolCraft::Slot &slot)
|
||||
{
|
||||
std::vector<unsigned char> bytes;
|
||||
slot.Write(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
std::string SlotDescription(const ProtocolCraft::Slot &slot)
|
||||
{
|
||||
return slot.IsEmptySlot() ? "empty" : "item=" + std::to_string(slot.GetItemId()) +
|
||||
",count=" + std::to_string(slot.GetItemCount());
|
||||
}
|
||||
|
||||
std::string WindowSlotDescription(const Botcraft::Window &window, short index)
|
||||
{
|
||||
const auto slots = window.GetSlots();
|
||||
const auto found = slots.find(index);
|
||||
return std::to_string(index) + "=" + (found == slots.end() ? "missing" : SlotDescription(found->second));
|
||||
}
|
||||
|
||||
Status SwapBackpack(BilicraftClient &client, const ActionCommand &command)
|
||||
{
|
||||
const short from = ActionBackpackSlot(command.row, command.col);
|
||||
const short hotbar = ActionHotbarIndex(command.slot);
|
||||
const short to = Botcraft::Window::INVENTORY_HOTBAR_START + hotbar;
|
||||
const auto inventory = client.GetInventoryManager();
|
||||
Require(inventory->GetFirstOpenedWindowId() < 0, "swb requires all container GUIs to be closed");
|
||||
Require(inventory->GetCursor().IsEmptySlot(), "swb requires an empty cursor");
|
||||
const auto window = inventory->GetPlayerInventory();
|
||||
Await(client,
|
||||
[&] {
|
||||
const auto slots = window->GetSlots();
|
||||
return slots.contains(from) && slots.contains(to);
|
||||
},
|
||||
5s, "player inventory contents");
|
||||
Require(inventory->GetFirstOpenedWindowId() < 0, "a GUI opened while waiting for player inventory");
|
||||
Require(inventory->GetCursor().IsEmptySlot(), "cursor changed while waiting for player inventory");
|
||||
const auto before = window->GetSlots();
|
||||
Require(before.contains(from) && before.contains(to), "inventory reset before swb");
|
||||
const auto first = SlotBytes(before.at(from));
|
||||
const auto second = SlotBytes(before.at(to));
|
||||
if (first == second)
|
||||
return Status::Success;
|
||||
|
||||
// Upstream's three-click SwapItemsInContainer merges equal item stacks,
|
||||
// and its InventoryManager rejects click type 2. Send a real number-key
|
||||
// SWAP instead, with no optimistic local mutation. An intentionally stale
|
||||
// state id requests a full authoritative resync after the server action.
|
||||
client.GetNetworkManager()->Send(MakeBackpackSwapPacket(command.row, command.col, command.slot));
|
||||
try
|
||||
{
|
||||
Await(client,
|
||||
[&] {
|
||||
Require(inventory->GetFirstOpenedWindowId() < 0, "a GUI opened during swb");
|
||||
Require(inventory->GetCursor().IsEmptySlot(), "cursor changed during swb");
|
||||
Require(inventory->GetPlayerInventory() == window, "inventory replaced during swb");
|
||||
const auto current = window->GetSlots();
|
||||
Require(current.contains(from) && current.contains(to), "inventory reset during swb");
|
||||
return SlotBytes(current.at(from)) == second && SlotBytes(current.at(to)) == first;
|
||||
},
|
||||
5s, "server confirmation of backpack/hotbar swap (not retried)");
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
throw std::runtime_error(std::string(error.what()) + "; before: " + SlotDescription(before.at(from)) +
|
||||
" <-> " + SlotDescription(before.at(to)) + "; now: " +
|
||||
WindowSlotDescription(*window, from) + ", " + WindowSlotDescription(*window, to));
|
||||
}
|
||||
return Status::Success;
|
||||
}
|
||||
|
||||
Status DropHotbar(BilicraftClient &client, const ActionCommand &command)
|
||||
{
|
||||
const auto inventory = client.GetInventoryManager();
|
||||
const short hotbarSlot = ActionDropSlot(command.slot, inventory->GetIndexHotbarSelected());
|
||||
const short slot = Botcraft::Window::INVENTORY_HOTBAR_START + ActionHotbarIndex(hotbarSlot);
|
||||
const auto window = inventory->GetPlayerInventory();
|
||||
const auto checkInventory = [&] {
|
||||
Require(inventory->GetFirstOpenedWindowId() < 0, "drop requires all container GUIs to be closed");
|
||||
Require(inventory->GetCursor().IsEmptySlot(), "drop requires an empty cursor");
|
||||
Require(inventory->GetPlayerInventory() == window, "player inventory changed during drop");
|
||||
};
|
||||
checkInventory();
|
||||
Await(client, [&] { return window->GetSlots().contains(slot); }, 5s, "hotbar contents before drop");
|
||||
checkInventory();
|
||||
const auto before = ReadDropSlot(*window, slot);
|
||||
if (before.IsEmptySlot())
|
||||
return Status::Success; // Empty slots are harmless no-ops; do not send THROW.
|
||||
const auto expected = RemainingAfterDrop(before, command.all);
|
||||
const auto expectedBytes = SlotBytes(expected);
|
||||
|
||||
// A single mode-4 THROW avoids picking the stack onto the cursor, repeated
|
||||
// outside clicks, or temporarily selecting a different item. Like swb, use
|
||||
// server resync rather than optimistic local mutations. Never retry a drop:
|
||||
// a lost/delayed update must not cause extra items to be discarded.
|
||||
client.GetNetworkManager()->Send(MakeHotbarDropPacket(hotbarSlot, command.all));
|
||||
try
|
||||
{
|
||||
Await(client,
|
||||
[&] {
|
||||
checkInventory();
|
||||
const auto actual = ReadDropSlot(*window, slot);
|
||||
return expected.IsEmptySlot() ? actual.IsEmptySlot() : SlotBytes(actual) == expectedBytes;
|
||||
},
|
||||
5s, "server confirmation of drop (not retried)");
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
throw std::runtime_error(std::string(error.what()) + "; before: " + SlotDescription(before) +
|
||||
"; expected: " + SlotDescription(expected) + "; now: " +
|
||||
WindowSlotDescription(*window, slot));
|
||||
}
|
||||
return Status::Success;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void ValidateActionPosition(int x, int y, int z)
|
||||
{
|
||||
// NetworkPosition packs signed 26/12/26-bit coordinates. Restrict X/Z to
|
||||
// the vanilla world boundary too, preventing pathfinding arithmetic on
|
||||
// arbitrary int-range user input. Dimension-specific Y limits vary.
|
||||
Require(x >= -29999984 && x <= 29999984 && z >= -29999984 && z <= 29999984 &&
|
||||
y >= -2048 && y <= 2047,
|
||||
"coordinates exceed supported Minecraft world/protocol bounds");
|
||||
}
|
||||
|
||||
FrameAttackIntent PlanFrameAttack(bool destroy, bool hasItem, bool creative)
|
||||
{
|
||||
if (!destroy && !hasItem) return FrameAttackIntent::None;
|
||||
Require(destroy || !creative, "item-only frame left click is unsafe in creative/instabuild mode; use destory explicitly to remove the frame");
|
||||
return hasItem ? FrameAttackIntent::TakeItem : FrameAttackIntent::RemoveFrame;
|
||||
}
|
||||
|
||||
void ValidateFrameAttack(FrameAttackIntent expected, bool destroy, bool hasItem, bool creative)
|
||||
{
|
||||
Require(expected != FrameAttackIntent::None && PlanFrameAttack(destroy, hasItem, creative) == expected,
|
||||
"frame contents or game mode changed before attack; not sending/retrying");
|
||||
}
|
||||
|
||||
short ActionGuiSlot(Botcraft::InventoryType type, int row, int col)
|
||||
{
|
||||
int rows = 0;
|
||||
switch (type)
|
||||
{
|
||||
case Botcraft::InventoryType::Generic9x1: rows = 1; break;
|
||||
case Botcraft::InventoryType::Generic9x2: rows = 2; break;
|
||||
case Botcraft::InventoryType::Generic9x3: rows = 3; break;
|
||||
case Botcraft::InventoryType::Generic9x4: rows = 4; break;
|
||||
case Botcraft::InventoryType::Generic9x5: rows = 5; break;
|
||||
case Botcraft::InventoryType::Generic9x6: rows = 6; break;
|
||||
case Botcraft::InventoryType::ShulkerBox: rows = 3; break;
|
||||
default: throw std::runtime_error("GUI type is unsupported: only generic 9-column containers and shulker boxes are supported");
|
||||
}
|
||||
Require(row >= 1 && row <= rows && col >= 1 && col <= 9, "GUI row/column is outside the container area");
|
||||
return static_cast<short>((row - 1) * 9 + col - 1);
|
||||
}
|
||||
|
||||
short ActionBackpackSlot(int row, int col)
|
||||
{
|
||||
Require(row >= 1 && row <= 3 && col >= 1 && col <= 9, "backpack requires row 1..3 and column 1..9");
|
||||
return static_cast<short>(Botcraft::Window::INVENTORY_STORAGE_START + (row - 1) * 9 + col - 1);
|
||||
}
|
||||
|
||||
short ActionHotbarIndex(int slot)
|
||||
{
|
||||
Require(slot >= 1 && slot <= 9, "hotbar slot must be in 1..9");
|
||||
return static_cast<short>(slot - 1);
|
||||
}
|
||||
|
||||
std::shared_ptr<ProtocolCraft::ServerboundContainerClickPacket> MakeBackpackSwapPacket(int row, int col, int slot)
|
||||
{
|
||||
const short from = ActionBackpackSlot(row, col);
|
||||
const short hotbar = ActionHotbarIndex(slot);
|
||||
auto packet = std::make_shared<ProtocolCraft::ServerboundContainerClickPacket>();
|
||||
packet->SetContainerId(Botcraft::Window::PLAYER_INVENTORY_INDEX);
|
||||
packet->SetStateId(-1);
|
||||
packet->SetSlotNum(from);
|
||||
packet->SetButtonNum(static_cast<char>(hotbar));
|
||||
packet->SetClickType(2);
|
||||
packet->SetChangedSlots({});
|
||||
packet->SetCarriedItem(ProtocolCraft::HashedSlot(ProtocolCraft::Slot()));
|
||||
return packet;
|
||||
}
|
||||
|
||||
short ActionDropSlot(int requestedSlot, int selectedHotbarIndex)
|
||||
{
|
||||
if (requestedSlot == 0)
|
||||
{
|
||||
Require(selectedHotbarIndex >= 0 && selectedHotbarIndex < 9, "invalid current hotbar selection for drop");
|
||||
return static_cast<short>(selectedHotbarIndex + 1);
|
||||
}
|
||||
return static_cast<short>(ActionHotbarIndex(requestedSlot) + 1);
|
||||
}
|
||||
|
||||
std::shared_ptr<ProtocolCraft::ServerboundContainerClickPacket> MakeHotbarDropPacket(int slot, bool all)
|
||||
{
|
||||
const short hotbar = ActionHotbarIndex(slot);
|
||||
auto packet = std::make_shared<ProtocolCraft::ServerboundContainerClickPacket>();
|
||||
packet->SetContainerId(Botcraft::Window::PLAYER_INVENTORY_INDEX);
|
||||
packet->SetStateId(-1); // Request an authoritative resync, as with swb.
|
||||
packet->SetSlotNum(Botcraft::Window::INVENTORY_HOTBAR_START + hotbar);
|
||||
packet->SetButtonNum(all ? 1 : 0); // THROW: 0 = one item, 1 = entire stack.
|
||||
packet->SetClickType(4);
|
||||
packet->SetChangedSlots({});
|
||||
packet->SetCarriedItem(ProtocolCraft::HashedSlot(ProtocolCraft::Slot()));
|
||||
return packet;
|
||||
}
|
||||
|
||||
ProtocolCraft::Slot RemainingAfterDrop(const ProtocolCraft::Slot &before, bool all)
|
||||
{
|
||||
if (before.IsEmptySlot() || all || before.GetItemCount() == 1)
|
||||
return ProtocolCraft::Slot();
|
||||
auto remaining = before;
|
||||
remaining.SetItemCount(before.GetItemCount() - 1);
|
||||
return remaining;
|
||||
}
|
||||
|
||||
ProtocolCraft::Slot ReadDropSlot(const Botcraft::Window &window, short slot)
|
||||
{
|
||||
// Window::Init can clear slots without replacing the window object (e.g.
|
||||
// plugin-driven inventory resets). GetSlot would silently return an empty
|
||||
// slot, falsely confirming a whole-stack drop. Read one coherent snapshot.
|
||||
const auto slots = window.GetSlots();
|
||||
const auto found = slots.find(slot);
|
||||
Require(found != slots.end(), "hotbar contents disappeared/reset during drop");
|
||||
return found->second;
|
||||
}
|
||||
|
||||
void MaintainActionInputs(BilicraftClient &client)
|
||||
{
|
||||
if (activeSneak && activeSneak->client == &client)
|
||||
activeSneak->player->SetInputsSneak(true);
|
||||
}
|
||||
|
||||
Status ExecuteAction(BilicraftClient &client, const ActionCommand &command)
|
||||
{
|
||||
const std::string location = command.source.string() + ":" + std::to_string(command.line);
|
||||
try
|
||||
{
|
||||
Require(command.kind != ActionKind::Wait, "wait must be handled by the action scheduler");
|
||||
if (command.kind == ActionKind::Goto || command.kind == ActionKind::RightClick || command.kind == ActionKind::LeftClick)
|
||||
ValidateActionPosition(command.x, command.y, command.z);
|
||||
CheckConnection(client);
|
||||
Status result = Status::Failure;
|
||||
if (command.kind == ActionKind::SendCommand)
|
||||
{
|
||||
const std::string text = !command.text.empty() && command.text.front() == '/' ? command.text.substr(1) : command.text;
|
||||
Require(!text.empty(), "empty chat command");
|
||||
client.SendChatCommand(text);
|
||||
result = Status::Success;
|
||||
}
|
||||
else if (command.kind == ActionKind::SendMessage)
|
||||
{
|
||||
Require(!command.text.empty(), "empty chat message");
|
||||
if (command.recipient.empty())
|
||||
client.SendChatMessage(command.text);
|
||||
else
|
||||
client.SendChatCommand("msg " + command.recipient + " " + command.text);
|
||||
result = Status::Success;
|
||||
}
|
||||
else
|
||||
{
|
||||
WaitForManagers(client);
|
||||
switch (command.kind)
|
||||
{
|
||||
case ActionKind::Goto:
|
||||
result = Botcraft::GoTo(client, Botcraft::Position(command.x, command.y, command.z));
|
||||
break;
|
||||
case ActionKind::RightClick:
|
||||
case ActionKind::LeftClick:
|
||||
result = command.entity ? ClickItemFrame(client, command) : ClickBlock(client, command);
|
||||
break;
|
||||
case ActionKind::GuiRightClick:
|
||||
case ActionKind::GuiLeftClick:
|
||||
result = ClickGui(client, command);
|
||||
break;
|
||||
case ActionKind::SelectHotbar:
|
||||
result = Botcraft::SelectHotbarSlot(client, ActionHotbarIndex(command.slot));
|
||||
break;
|
||||
case ActionKind::SwapBackpack:
|
||||
result = SwapBackpack(client, command);
|
||||
break;
|
||||
case ActionKind::Drop:
|
||||
result = DropHotbar(client, command);
|
||||
break;
|
||||
default: throw std::runtime_error("unknown action kind");
|
||||
}
|
||||
}
|
||||
if (result != Status::Success)
|
||||
LOG_ERROR(location << ": action failed");
|
||||
return result;
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
throw std::runtime_error(location + ": " + error.what());
|
||||
}
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,424 @@
|
||||
#include "ActionFile.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::size_t kMaxDepth = 32;
|
||||
constexpr std::size_t kMaxCommands = 100000;
|
||||
constexpr std::size_t kMaxLoads = 4096;
|
||||
constexpr std::size_t kMaxFileBytes = 1024 * 1024;
|
||||
constexpr std::size_t kMaxTotalBytes = 16 * kMaxFileBytes;
|
||||
|
||||
bool IsSpace(char c)
|
||||
{
|
||||
return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f';
|
||||
}
|
||||
|
||||
std::string_view Trim(std::string_view text)
|
||||
{
|
||||
while (!text.empty() && IsSpace(text.front()))
|
||||
text.remove_prefix(1);
|
||||
while (!text.empty() && IsSpace(text.back()))
|
||||
text.remove_suffix(1);
|
||||
return text;
|
||||
}
|
||||
|
||||
std::string_view TakeToken(std::string_view &text)
|
||||
{
|
||||
text = Trim(text);
|
||||
const auto end = text.find_first_of(" \t\r\n\v\f");
|
||||
const auto token = text.substr(0, end);
|
||||
text.remove_prefix(end == std::string_view::npos ? text.size() : end);
|
||||
return token;
|
||||
}
|
||||
|
||||
[[noreturn]] void Fail(const std::filesystem::path &source, std::size_t line, const std::string &message)
|
||||
{
|
||||
throw std::runtime_error(source.string() + ":" + std::to_string(line) + ": " + message);
|
||||
}
|
||||
|
||||
bool IsSimpleName(std::string_view name)
|
||||
{
|
||||
if (name.empty() || name == "." || name == ".." || name.back() == '.' || name.ends_with(".act"))
|
||||
return false;
|
||||
// Also reject Windows separators/drive syntax when parsing on POSIX.
|
||||
for (const unsigned char c : name)
|
||||
if (c <= 32 || c == 127 || std::string_view("/\\:<>\"|?*").find(c) != std::string_view::npos)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
int Integer(std::string_view token, const ActionCommand &command)
|
||||
{
|
||||
int value = 0;
|
||||
// from_chars intentionally does not accept '+', but signed decimal does.
|
||||
if (!token.empty() && token.front() == '+')
|
||||
{
|
||||
token.remove_prefix(1);
|
||||
if (token.empty() || token.front() == '-' || token.front() == '+')
|
||||
Fail(command.source, command.line, "expected a decimal integer");
|
||||
}
|
||||
const auto result = std::from_chars(token.data(), token.data() + token.size(), value);
|
||||
if (token.empty() || result.ec != std::errc{} || result.ptr != token.data() + token.size())
|
||||
Fail(command.source, command.line, "expected a decimal integer: '" + std::string(token) + "'");
|
||||
return value;
|
||||
}
|
||||
|
||||
std::chrono::milliseconds ParseWaitDuration(std::string_view number, std::string_view unit,
|
||||
const ActionCommand &command)
|
||||
{
|
||||
std::int64_t multiplier = 0;
|
||||
if (unit.empty() || unit == "s")
|
||||
multiplier = 1000;
|
||||
else if (unit == "ms")
|
||||
multiplier = 1;
|
||||
else if (unit == "min")
|
||||
multiplier = 60000;
|
||||
else if (unit == "h")
|
||||
multiplier = 3600000;
|
||||
else if (unit == "d")
|
||||
multiplier = 86400000;
|
||||
else
|
||||
Fail(command.source, command.line, "unknown wait unit (expected s, ms, min, h or d)");
|
||||
|
||||
// Plain unsigned decimal: digits, optionally followed by '.' and digits.
|
||||
// Validate before arithmetic; in particular no signs, exponent, NaN or Inf.
|
||||
const auto dot = number.find('.');
|
||||
const auto whole = number.substr(0, dot);
|
||||
const auto fraction = dot == std::string_view::npos ? std::string_view{} : number.substr(dot + 1);
|
||||
const auto digits = [](std::string_view text) {
|
||||
return std::all_of(text.begin(), text.end(), [](char c) { return c >= '0' && c <= '9'; });
|
||||
};
|
||||
if (whole.empty() || !digits(whole) || (dot != std::string_view::npos && fraction.empty()) || !digits(fraction))
|
||||
Fail(command.source, command.line, "wait requires a nonnegative plain decimal number (digits[.digits])");
|
||||
|
||||
// Bound before multiplication, including arbitrarily long numeric tokens.
|
||||
// A short fixed cap also keeps scheduling far below steady_clock's range.
|
||||
constexpr std::int64_t max_milliseconds = 365LL * 24 * 60 * 60 * 1000;
|
||||
const auto limit = max_milliseconds / multiplier;
|
||||
std::int64_t integral = 0;
|
||||
for (const char c : whole)
|
||||
{
|
||||
const int digit = c - '0';
|
||||
if (integral > (limit - digit) / 10)
|
||||
Fail(command.source, command.line, "wait duration exceeds the 365 days limit");
|
||||
integral = integral * 10 + digit;
|
||||
}
|
||||
|
||||
// Decimal multiplication from right to left. Each discarded fractional
|
||||
// digit must be zero, so we never round or use floating-point arithmetic.
|
||||
// The carry is always < multiplier, regardless of the token's length.
|
||||
std::int64_t fractional_milliseconds = 0;
|
||||
for (auto it = fraction.rbegin(); it != fraction.rend(); ++it)
|
||||
{
|
||||
const auto product = (*it - '0') * multiplier + fractional_milliseconds;
|
||||
if (product % 10 != 0)
|
||||
Fail(command.source, command.line, "wait duration must be an exact whole number of milliseconds");
|
||||
fractional_milliseconds = product / 10;
|
||||
}
|
||||
const auto milliseconds = integral * multiplier + fractional_milliseconds;
|
||||
if (milliseconds > max_milliseconds)
|
||||
Fail(command.source, command.line, "wait duration exceeds the 365 days limit");
|
||||
return std::chrono::milliseconds{milliseconds};
|
||||
}
|
||||
|
||||
std::optional<EntityFace> ParseEntityFace(std::string_view token)
|
||||
{
|
||||
if (token == "t" || token == "top")
|
||||
return EntityFace::Top;
|
||||
if (token == "b" || token == "bottom")
|
||||
return EntityFace::Bottom;
|
||||
if (token == "s" || token == "south")
|
||||
return EntityFace::South;
|
||||
if (token == "n" || token == "north")
|
||||
return EntityFace::North;
|
||||
if (token == "w" || token == "west")
|
||||
return EntityFace::West;
|
||||
if (token == "e" || token == "east")
|
||||
return EntityFace::East;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
ActionCommand ParseCommand(std::string_view verb, std::string_view line, const std::filesystem::path &source,
|
||||
std::size_t line_number)
|
||||
{
|
||||
ActionCommand command{};
|
||||
command.source = source;
|
||||
command.line = line_number;
|
||||
if (verb == "sendcmd" || verb == "sendmsg")
|
||||
{
|
||||
command.kind = verb == "sendcmd" ? ActionKind::SendCommand : ActionKind::SendMessage;
|
||||
line = Trim(line);
|
||||
if (verb == "sendmsg" && line.starts_with('@'))
|
||||
{
|
||||
const auto recipient = TakeToken(line).substr(1);
|
||||
if (recipient.empty())
|
||||
Fail(source, line_number, "sendmsg recipient must not be empty");
|
||||
command.recipient = recipient;
|
||||
}
|
||||
command.text = Trim(line);
|
||||
if (command.text.empty())
|
||||
Fail(source, line_number, "message or command text must not be empty");
|
||||
if (verb == "sendcmd" && command.text.starts_with('/') &&
|
||||
Trim(std::string_view(command.text).substr(1)).empty())
|
||||
Fail(source, line_number, "command text after '/' must not be empty");
|
||||
}
|
||||
else
|
||||
{
|
||||
std::vector<std::string_view> args;
|
||||
while (!Trim(line).empty())
|
||||
args.push_back(TakeToken(line));
|
||||
const auto count_is = [&](std::size_t count) {
|
||||
if (args.size() != count)
|
||||
Fail(source, line_number, std::string(verb) + " requires " + std::to_string(count) + " arguments");
|
||||
};
|
||||
if (verb == "wait")
|
||||
{
|
||||
if (args.empty() || args.size() > 2)
|
||||
Fail(source, line_number, "wait requires a duration and optional unit: wait times [s|ms|min|h|d]");
|
||||
command.kind = ActionKind::Wait;
|
||||
command.waitDuration = ParseWaitDuration(args[0], args.size() == 2 ? args[1] : std::string_view{}, command);
|
||||
}
|
||||
else if (verb == "goto" || verb == "rclick" || verb == "lclick")
|
||||
{
|
||||
const auto max_args = verb == "goto" ? 3U : verb == "rclick" ? 6U : 7U;
|
||||
if (args.size() < 3 || args.size() > max_args)
|
||||
Fail(source, line_number, "invalid coordinate/flag argument count for " + std::string(verb));
|
||||
command.kind = verb == "goto" ? ActionKind::Goto
|
||||
: verb == "rclick" ? ActionKind::RightClick
|
||||
: ActionKind::LeftClick;
|
||||
command.x = Integer(args[0], command);
|
||||
command.y = Integer(args[1], command);
|
||||
command.z = Integer(args[2], command);
|
||||
for (std::size_t i = 3; i < args.size(); ++i)
|
||||
{
|
||||
if (verb != "goto" && args[i] == "entry" && !command.entity)
|
||||
{
|
||||
command.entity = true;
|
||||
// Only an immediately adjacent face belongs to entry.
|
||||
// Otherwise leave the next token for normal flag parsing.
|
||||
if (i + 1 < args.size())
|
||||
{
|
||||
if (const auto face = ParseEntityFace(args[i + 1]))
|
||||
{
|
||||
command.entityFace = *face;
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (args[i] == "shift" && !command.shift)
|
||||
command.shift = true;
|
||||
else if (verb == "lclick" && (args[i] == "destory" || args[i] == "destroy") && !command.destroy)
|
||||
command.destroy = true;
|
||||
else
|
||||
Fail(source, line_number, "unknown or duplicate flag: " + std::string(args[i]));
|
||||
}
|
||||
}
|
||||
else if (verb == "grclick" || verb == "glclick" || verb == "swb")
|
||||
{
|
||||
count_is(verb == "swb" ? 3 : 2);
|
||||
command.kind = verb == "grclick" ? ActionKind::GuiRightClick
|
||||
: verb == "glclick" ? ActionKind::GuiLeftClick
|
||||
: ActionKind::SwapBackpack;
|
||||
command.row = Integer(args[0], command);
|
||||
command.col = Integer(args[1], command);
|
||||
if (command.row < 1 || command.col < 1 || command.col > 9 || (verb == "swb" && command.row > 3))
|
||||
Fail(source, line_number,
|
||||
"row/column out of range (rows start at 1; columns 1..9; backpack rows 1..3)");
|
||||
if (verb == "swb")
|
||||
command.slot = Integer(args[2], command);
|
||||
}
|
||||
else if (verb == "drop")
|
||||
{
|
||||
command.kind = ActionKind::Drop;
|
||||
if (args.size() > 2)
|
||||
Fail(source, line_number, "drop accepts an optional hotbar slot and optional all flag");
|
||||
for (const auto argument : args)
|
||||
{
|
||||
if (argument == "all")
|
||||
{
|
||||
if (command.all)
|
||||
Fail(source, line_number, "duplicate drop flag: all");
|
||||
command.all = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (command.slot != 0)
|
||||
Fail(source, line_number, "duplicate drop hotbar slot");
|
||||
command.slot = Integer(argument, command);
|
||||
if (command.slot < 1 || command.slot > 9)
|
||||
Fail(source, line_number, "drop hotbar slot must be in 1..9");
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (verb == "sw")
|
||||
{
|
||||
count_is(1);
|
||||
command.kind = ActionKind::SelectHotbar;
|
||||
command.slot = Integer(args[0], command);
|
||||
}
|
||||
else
|
||||
Fail(source, line_number, "unknown instruction: " + std::string(verb));
|
||||
if ((verb == "sw" || verb == "swb") && (command.slot < 1 || command.slot > 9))
|
||||
Fail(source, line_number, "hotbar slot must be in 1..9");
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
struct Loader
|
||||
{
|
||||
ActionProgram program;
|
||||
std::vector<std::filesystem::path> active;
|
||||
std::size_t loads = 0;
|
||||
std::size_t total_bytes = 0;
|
||||
|
||||
void Load(const std::filesystem::path &path, std::string_view expected_name = {})
|
||||
{
|
||||
std::error_code ec;
|
||||
const auto source = std::filesystem::canonical(path, ec);
|
||||
if (ec)
|
||||
Fail(path, 1, "cannot resolve action file: " + ec.message());
|
||||
if (!std::filesystem::is_regular_file(source, ec) || ec)
|
||||
Fail(source, 1, "action file is not a regular file");
|
||||
if (active.size() >= kMaxDepth)
|
||||
Fail(source, 1, "import depth limit exceeded (32)");
|
||||
if (std::find(active.begin(), active.end(), source) != active.end())
|
||||
Fail(source, 1, "cyclic import");
|
||||
if (++loads > kMaxLoads)
|
||||
Fail(source, 1, "file load limit exceeded (4096)");
|
||||
|
||||
std::ifstream input(source, std::ios::binary);
|
||||
if (!input)
|
||||
Fail(source, 1, "cannot open action file");
|
||||
// A bounded read also protects against files that grow after stat().
|
||||
std::string contents(kMaxFileBytes + 1, '\0');
|
||||
input.read(contents.data(), static_cast<std::streamsize>(contents.size()));
|
||||
const auto count = static_cast<std::size_t>(input.gcount());
|
||||
if (input.bad() || (input.fail() && !input.eof()))
|
||||
Fail(source, 1, "cannot read action file");
|
||||
if (count > kMaxFileBytes)
|
||||
Fail(source, 1, "action file size limit exceeded (1 MiB)");
|
||||
contents.resize(count);
|
||||
total_bytes += count;
|
||||
if (total_bytes > kMaxTotalBytes)
|
||||
Fail(source, 1, "total action input limit exceeded (16 MiB)");
|
||||
|
||||
active.push_back(source);
|
||||
struct PopActive
|
||||
{
|
||||
std::vector<std::filesystem::path> &paths;
|
||||
~PopActive()
|
||||
{
|
||||
paths.pop_back();
|
||||
}
|
||||
} pop{active};
|
||||
std::string_view remaining(contents);
|
||||
if (remaining.starts_with("\xEF\xBB\xBF"))
|
||||
remaining.remove_prefix(3);
|
||||
bool header_seen = false;
|
||||
std::size_t line_number = 0;
|
||||
while (!remaining.empty())
|
||||
{
|
||||
++line_number;
|
||||
const auto newline = remaining.find('\n');
|
||||
auto line = Trim(remaining.substr(0, newline));
|
||||
remaining.remove_prefix(newline == std::string_view::npos ? remaining.size() : newline + 1);
|
||||
if (line.find('\0') != std::string_view::npos)
|
||||
Fail(source, line_number, "NUL bytes are not allowed");
|
||||
if (line.starts_with('#'))
|
||||
{
|
||||
auto comment = Trim(line.substr(1));
|
||||
if (comment.starts_with("action:"))
|
||||
{
|
||||
if (header_seen)
|
||||
Fail(source, line_number, "duplicate action header");
|
||||
const auto name = Trim(comment.substr(7, comment.find('#', 7) == std::string_view::npos
|
||||
? std::string_view::npos
|
||||
: comment.find('#', 7) - 7));
|
||||
if (!IsSimpleName(name))
|
||||
Fail(source, line_number,
|
||||
"action name must be a nonempty simple filename without a path or .act suffix");
|
||||
if (!expected_name.empty() && name != expected_name)
|
||||
Fail(source, line_number,
|
||||
"action header name '" + std::string(name) + "' does not match imported name '" +
|
||||
std::string(expected_name) + "'");
|
||||
if (active.size() == 1)
|
||||
program.name = name;
|
||||
header_seen = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
line = Trim(line.substr(0, line.find('#')));
|
||||
if (line.empty())
|
||||
continue;
|
||||
if (!header_seen)
|
||||
Fail(source, line_number, "missing action header before first instruction");
|
||||
const auto verb = TakeToken(line);
|
||||
if (verb == "import")
|
||||
{
|
||||
const auto name = TakeToken(line);
|
||||
if (!IsSimpleName(name) || !Trim(line).empty())
|
||||
Fail(source, line_number, "import requires exactly one simple action name");
|
||||
const auto imported = source.parent_path() / (std::string(name) + ".act");
|
||||
const auto resolved = std::filesystem::canonical(imported, ec);
|
||||
if (ec)
|
||||
Fail(source, line_number, "cannot import '" + std::string(name) + "': " + ec.message());
|
||||
if (resolved.parent_path() != source.parent_path())
|
||||
Fail(source, line_number, "import escapes its action directory");
|
||||
try
|
||||
{
|
||||
Load(resolved, name);
|
||||
}
|
||||
catch (const std::runtime_error &error)
|
||||
{
|
||||
Fail(source, line_number, "import '" + std::string(name) + "': " + error.what());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
auto command = ParseCommand(verb, line, source, line_number);
|
||||
if (program.commands.size() >= kMaxCommands)
|
||||
Fail(source, line_number, "expanded command limit exceeded (100000)");
|
||||
program.commands.push_back(std::move(command));
|
||||
}
|
||||
if (!header_seen)
|
||||
Fail(source, line_number == 0 ? 1 : line_number, "missing action header");
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
ActionProgram LoadActionFile(const std::filesystem::path &path)
|
||||
{
|
||||
if (path.extension() != ".act")
|
||||
Fail(path, 1, "action file must have the .act extension");
|
||||
Loader loader;
|
||||
loader.Load(path);
|
||||
return std::move(loader.program);
|
||||
}
|
||||
|
||||
std::optional<ActionCommand> ParseInteractiveCommand(std::string_view text)
|
||||
{
|
||||
const std::filesystem::path source{"<console>"};
|
||||
// Validate the entire input, even comments and text that would be trimmed.
|
||||
if (text.find('\0') != std::string_view::npos)
|
||||
Fail(source, 1, "NUL bytes are not allowed");
|
||||
if (text.find_first_of("\r\n") != std::string_view::npos)
|
||||
Fail(source, 1, "console input must contain exactly one line (no CR or LF)");
|
||||
text = Trim(text.substr(0, text.find('#')));
|
||||
if (text.empty())
|
||||
return std::nullopt;
|
||||
const auto verb = TakeToken(text);
|
||||
if (verb == "wait" || verb == "import")
|
||||
Fail(source, 1, std::string(verb) + " is only available in action files; use run file.act");
|
||||
return ParseCommand(verb, text, source, 1);
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,157 @@
|
||||
#include "ActionScheduler.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
ActionScheduler::TaskId ActionScheduler::Enqueue(ActionProgram program, Clock::time_point now)
|
||||
{
|
||||
if (tasks.size() >= 128 || program.commands.size() > 1000000 - storedCommands)
|
||||
throw std::runtime_error("action queue limit exceeded (128 tasks / 1000000 commands)");
|
||||
for (const auto &command : program.commands)
|
||||
if (command.kind == ActionKind::Wait &&
|
||||
(command.waitDuration.count() < 0 || command.waitDuration > std::chrono::hours(24 * 365)))
|
||||
throw std::runtime_error("wait duration must be between zero and 365 days");
|
||||
// An already-expired wait became ready BEFORE this newly submitted task,
|
||||
// even when another action was executing throughout that time.
|
||||
WakeReady(now);
|
||||
const auto id = nextId++;
|
||||
storedCommands += program.commands.size();
|
||||
tasks.emplace(id, Task{id, std::move(program), 0, State::Ready, {}, nextOrder++});
|
||||
events.push_back("Action #" + std::to_string(id) + " '" + tasks.at(id).program.name + "': queued");
|
||||
return id;
|
||||
}
|
||||
|
||||
void ActionScheduler::SubmitInteractive(ActionCommand command)
|
||||
{
|
||||
if (interactive)
|
||||
throw std::runtime_error("previous interactive command has not completed");
|
||||
if (command.kind == ActionKind::Wait)
|
||||
throw std::runtime_error("wait is not allowed in the interactive console; use run file.act");
|
||||
interactive = std::move(command);
|
||||
}
|
||||
|
||||
void ActionScheduler::WakeReady(Clock::time_point now)
|
||||
{
|
||||
std::vector<Task *> awakened;
|
||||
for (auto &[id, task] : tasks)
|
||||
if (task.state == State::Blocked && task.wakeAt <= now)
|
||||
awakened.push_back(&task);
|
||||
std::sort(awakened.begin(), awakened.end(), [](const Task *a, const Task *b) {
|
||||
return a->wakeAt == b->wakeAt ? a->id < b->id : a->wakeAt < b->wakeAt;
|
||||
});
|
||||
for (auto *task : awakened)
|
||||
{
|
||||
task->state = State::Ready;
|
||||
task->readyOrder = nextOrder++;
|
||||
events.push_back("Action #" + std::to_string(task->id) + ": ready after wait");
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<ActionScheduler::Work> ActionScheduler::Next(Clock::time_point now)
|
||||
{
|
||||
if (inFlight)
|
||||
throw std::logic_error("finish the outstanding command before scheduling another");
|
||||
WakeReady(now);
|
||||
for (;;)
|
||||
{
|
||||
if (!active)
|
||||
{
|
||||
if (interactive)
|
||||
{
|
||||
inFlight = interactiveInFlight = true;
|
||||
return Work{*interactive, 0, true};
|
||||
}
|
||||
Task *newest = nullptr;
|
||||
for (auto &[id, task] : tasks)
|
||||
if (task.state == State::Ready && (!newest || task.readyOrder > newest->readyOrder))
|
||||
newest = &task;
|
||||
if (!newest)
|
||||
return std::nullopt;
|
||||
active = newest->id;
|
||||
newest->state = State::Running;
|
||||
events.push_back("Action #" + std::to_string(*active) + " '" + newest->program.name + "': running");
|
||||
}
|
||||
auto &task = tasks.at(*active);
|
||||
if (task.pc == task.program.commands.size())
|
||||
{
|
||||
RemoveActive(true);
|
||||
continue;
|
||||
}
|
||||
const auto &command = task.program.commands[task.pc];
|
||||
if (command.kind == ActionKind::Wait)
|
||||
{
|
||||
if (now > Clock::time_point::max() - command.waitDuration)
|
||||
throw std::overflow_error("wait deadline exceeds steady clock range");
|
||||
++task.pc;
|
||||
task.state = State::Blocked;
|
||||
task.wakeAt = now + command.waitDuration;
|
||||
events.push_back("Action #" + std::to_string(task.id) + ": blocked for " +
|
||||
std::to_string(command.waitDuration.count()) + " ms");
|
||||
active.reset();
|
||||
// Even wait 0 yields once. It is promoted on the next Next() call.
|
||||
continue;
|
||||
}
|
||||
inFlight = true;
|
||||
interactiveInFlight = false;
|
||||
return Work{command, task.id, false};
|
||||
}
|
||||
}
|
||||
|
||||
void ActionScheduler::RemoveActive(bool success)
|
||||
{
|
||||
auto &task = tasks.at(*active);
|
||||
events.push_back("Action #" + std::to_string(task.id) + " '" + task.program.name +
|
||||
(success ? "': completed" : "': failed (remaining commands discarded)"));
|
||||
storedCommands -= task.program.commands.size();
|
||||
tasks.erase(*active);
|
||||
active.reset();
|
||||
}
|
||||
|
||||
void ActionScheduler::Finish(bool success)
|
||||
{
|
||||
if (!inFlight)
|
||||
throw std::logic_error("no outstanding command to finish");
|
||||
if (interactiveInFlight)
|
||||
{
|
||||
interactive.reset();
|
||||
events.push_back(success ? "Interactive command completed" : "Interactive command failed");
|
||||
}
|
||||
else
|
||||
{
|
||||
auto &task = tasks.at(*active);
|
||||
if (success)
|
||||
++task.pc;
|
||||
if (!success || task.pc == task.program.commands.size())
|
||||
RemoveActive(success);
|
||||
}
|
||||
inFlight = interactiveInFlight = false;
|
||||
}
|
||||
|
||||
bool ActionScheduler::InteractivePending() const { return interactive.has_value(); }
|
||||
bool ActionScheduler::HasWork() const { return !tasks.empty() || interactive.has_value(); }
|
||||
|
||||
std::optional<ActionScheduler::Clock::time_point> ActionScheduler::NextWake() const
|
||||
{
|
||||
std::optional<Clock::time_point> wake;
|
||||
for (const auto &[id, task] : tasks)
|
||||
if (task.state == State::Blocked && (!wake || task.wakeAt < *wake))
|
||||
wake = task.wakeAt;
|
||||
return wake;
|
||||
}
|
||||
|
||||
std::vector<ActionScheduler::TaskInfo> ActionScheduler::Tasks() const
|
||||
{
|
||||
std::vector<TaskInfo> result;
|
||||
for (const auto &[id, task] : tasks)
|
||||
result.push_back({id, task.program.name, task.state, task.pc, task.program.commands.size(), task.wakeAt});
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<std::string> ActionScheduler::DrainEvents()
|
||||
{
|
||||
return std::exchange(events, {});
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,52 @@
|
||||
#include "AppConfig.h"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
AppConfig ParseArguments(std::span<const std::string_view> arguments)
|
||||
{
|
||||
AppConfig config;
|
||||
for (std::size_t i = 0; i < arguments.size(); ++i)
|
||||
{
|
||||
const auto argument = arguments[i];
|
||||
if (argument == "--help" || argument == "-h")
|
||||
{
|
||||
config.help = true;
|
||||
continue;
|
||||
}
|
||||
if (argument != "--server" && argument != "--account" && argument != "--action" &&
|
||||
argument != "--check-action")
|
||||
throw std::invalid_argument("Unknown option: " + std::string(argument));
|
||||
if (i + 1 == arguments.size() || arguments[i + 1].empty() || arguments[i + 1].starts_with('-'))
|
||||
throw std::invalid_argument("Missing value for " + std::string(argument));
|
||||
const auto value = arguments[++i];
|
||||
if (argument == "--server")
|
||||
config.server = value;
|
||||
else if (argument == "--account")
|
||||
config.account = value;
|
||||
else
|
||||
{
|
||||
if (!config.actionFile.empty())
|
||||
throw std::invalid_argument("Specify only one of --action or --check-action, once");
|
||||
config.actionFile = value;
|
||||
config.checkAction = argument == "--check-action";
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
std::string Usage()
|
||||
{
|
||||
return "Usage: bilicraft-bot [--server host:port] [--account cache-key]\n"
|
||||
" [--action file.act | --check-action file.act] [--help]\n"
|
||||
"Minecraft Java " + std::string(kGameVersion) + "\n"
|
||||
" --server Server address (default: " + std::string(kDefaultServer) + ")\n"
|
||||
" --account Microsoft credential-cache key (default: empty key)\n"
|
||||
" --action Queue an initial .act task after login and start the console\n"
|
||||
" --check-action Validate a .act file and imports offline, then exit\n"
|
||||
" --help Show help without connecting or authenticating\n"
|
||||
"Console: run file.act, tasks, help, quit, or a single game command (no wait).\n"
|
||||
"Microsoft authentication is required. Ctrl+C requests shutdown.\n";
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,65 @@
|
||||
#include "BilicraftClient.h"
|
||||
#include "ActionExecutor.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
static_assert(PROTOCOL_VERSION == 774, "This project targets Minecraft Java 1.21.11");
|
||||
|
||||
BilicraftClient::~BilicraftClient()
|
||||
{
|
||||
// Join packet processing before destroying our derived-class state.
|
||||
Disconnect();
|
||||
}
|
||||
|
||||
void BilicraftClient::SetActionYieldHandler(std::function<void()> handler)
|
||||
{
|
||||
actionYieldHandler = std::move(handler);
|
||||
}
|
||||
|
||||
void BilicraftClient::Yield()
|
||||
{
|
||||
if (actionYieldHandler)
|
||||
{
|
||||
MaintainActionInputs(*this);
|
||||
actionYieldHandler();
|
||||
}
|
||||
else
|
||||
Botcraft::TemplatedBehaviourClient<BilicraftClient>::Yield();
|
||||
}
|
||||
|
||||
bool BilicraftClient::WasDisconnected() const
|
||||
{
|
||||
return disconnected.load();
|
||||
}
|
||||
|
||||
bool BilicraftClient::HasEnteredPlay() const
|
||||
{
|
||||
return enteredPlay.load();
|
||||
}
|
||||
|
||||
void BilicraftClient::Handle(ProtocolCraft::ClientboundLoginPacket &packet)
|
||||
{
|
||||
Botcraft::TemplatedBehaviourClient<BilicraftClient>::Handle(packet);
|
||||
enteredPlay.store(true);
|
||||
}
|
||||
|
||||
void BilicraftClient::Handle(ProtocolCraft::ClientboundLoginDisconnectPacket &packet)
|
||||
{
|
||||
Botcraft::TemplatedBehaviourClient<BilicraftClient>::Handle(packet);
|
||||
disconnected.store(true);
|
||||
}
|
||||
|
||||
void BilicraftClient::Handle(ProtocolCraft::ClientboundDisconnectConfigurationPacket &packet)
|
||||
{
|
||||
Botcraft::TemplatedBehaviourClient<BilicraftClient>::Handle(packet);
|
||||
disconnected.store(true);
|
||||
}
|
||||
|
||||
void BilicraftClient::Handle(ProtocolCraft::ClientboundDisconnectPacket &packet)
|
||||
{
|
||||
Botcraft::TemplatedBehaviourClient<BilicraftClient>::Handle(packet);
|
||||
disconnected.store(true);
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,54 @@
|
||||
#include "ConsoleCommand.h"
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
namespace
|
||||
{
|
||||
std::string_view Trim(std::string_view text)
|
||||
{
|
||||
const auto first = text.find_first_not_of(" \t\v\f");
|
||||
if (first == std::string_view::npos) return {};
|
||||
return text.substr(first, text.find_last_not_of(" \t\v\f") - first + 1);
|
||||
}
|
||||
}
|
||||
ConsoleCommand ParseConsoleCommand(std::string_view line)
|
||||
{
|
||||
if (line.size() > 65536 || line.find_first_of("\r\n") != std::string_view::npos ||
|
||||
line.find('\0') != std::string_view::npos)
|
||||
throw std::runtime_error("<console>:1: expected a single line of at most 64 KiB");
|
||||
line = Trim(line.substr(0, line.find('#')));
|
||||
if (line.empty()) return {};
|
||||
const auto split = line.find_first_of(" \t\v\f");
|
||||
const auto verb = line.substr(0, split);
|
||||
auto rest = split == std::string_view::npos ? std::string_view{} : Trim(line.substr(split));
|
||||
if (verb == "run")
|
||||
{
|
||||
if (rest.size() >= 2 && ((rest.front() == '"' && rest.back() == '"') ||
|
||||
(rest.front() == '\'' && rest.back() == '\'')))
|
||||
rest = rest.substr(1, rest.size() - 2);
|
||||
if (rest.empty()) throw std::runtime_error("<console>:1: run requires a .act file path");
|
||||
return {ConsoleKind::Run, std::string(rest), {}};
|
||||
}
|
||||
if (verb == "help" || verb == "tasks" || verb == "quit" || verb == "exit")
|
||||
{
|
||||
if (!rest.empty()) throw std::runtime_error("<console>:1: console control command takes no arguments");
|
||||
return {verb == "help" ? ConsoleKind::Help : verb == "tasks" ? ConsoleKind::Tasks : ConsoleKind::Quit,
|
||||
{}, {}};
|
||||
}
|
||||
auto action = ParseInteractiveCommand(line);
|
||||
return {action ? ConsoleKind::Action : ConsoleKind::Empty, {}, std::move(action)};
|
||||
}
|
||||
std::string ConsoleHelp()
|
||||
{
|
||||
return "Console: run <path.act> | tasks | help | quit (or exit)\n"
|
||||
"Game commands: goto, rclick, lclick, grclick, glclick, sw, swb, drop, sendcmd, sendmsg\n"
|
||||
"rclick/lclick: add entry [t|b|s|n|w|e] for item frames; omit face to require a unique frame.\n"
|
||||
"A game command waits until the running action finishes or reaches wait.\n"
|
||||
"Only one interactive game command can be pending. wait/import are not allowed here.\n"
|
||||
"run validates and queues a file immediately; newest ready action runs first.\n"
|
||||
"Native terminal: fixed input bar, Up/Down history, Left/Right/Home/End editing.\n"
|
||||
"Ctrl+C/quit cancels; EOF drains queued tasks, then disconnects.\n";
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,231 @@
|
||||
#include "EntityInteraction.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
#include "botcraft/Game/Entities/EntityManager.hpp"
|
||||
#include "botcraft/Game/Entities/entities/decoration/GlowItemFrameEntity.hpp"
|
||||
#include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp"
|
||||
#include "botcraft/Game/Enums.hpp"
|
||||
#include "protocolCraft/Packets/Game/Serverbound/ServerboundInteractPacket.hpp"
|
||||
|
||||
static_assert(PROTOCOL_VERSION == 774, "Recheck item frame attachment and Interact semantics for this protocol");
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
namespace
|
||||
{
|
||||
// Minecraft's packed BlockPos range, not a particular dimension's build height.
|
||||
constexpr double MinHorizontal = -33554432.0;
|
||||
constexpr double MaxHorizontal = 33554431.0;
|
||||
constexpr double MinVertical = -2048.0;
|
||||
constexpr double MaxVertical = 2047.0;
|
||||
|
||||
bool ValidBlockPosition(const Botcraft::Vector3<double> &position)
|
||||
{
|
||||
const auto valid = [](double value, double minimum, double maximum)
|
||||
{
|
||||
return std::isfinite(value) && value >= minimum && value <= maximum && std::trunc(value) == value;
|
||||
};
|
||||
return valid(position.x, MinHorizontal, MaxHorizontal) && valid(position.y, MinVertical, MaxVertical) &&
|
||||
valid(position.z, MinHorizontal, MaxHorizontal);
|
||||
}
|
||||
|
||||
bool DirectionNormal(int direction, Botcraft::Vector3<double> &normal)
|
||||
{
|
||||
switch (static_cast<Botcraft::Direction>(direction))
|
||||
{
|
||||
case Botcraft::Direction::Down: normal = {0, -1, 0}; return true;
|
||||
case Botcraft::Direction::Up: normal = {0, 1, 0}; return true;
|
||||
case Botcraft::Direction::North: normal = {0, 0, -1}; return true;
|
||||
case Botcraft::Direction::South: normal = {0, 0, 1}; return true;
|
||||
case Botcraft::Direction::West: normal = {-1, 0, 0}; return true;
|
||||
case Botcraft::Direction::East: normal = {1, 0, 0}; return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
int CommandDirection(const ActionCommand &command)
|
||||
{
|
||||
if (!command.entity || (command.kind != ActionKind::RightClick && command.kind != ActionKind::LeftClick))
|
||||
throw std::runtime_error("item frame targeting requires an entity click command");
|
||||
if (!ValidBlockPosition({static_cast<double>(command.x), static_cast<double>(command.y),
|
||||
static_cast<double>(command.z)}))
|
||||
throw std::runtime_error("item frame support coordinates exceed the protocol block-position range");
|
||||
switch (command.entityFace)
|
||||
{
|
||||
case EntityFace::Any: return -1;
|
||||
case EntityFace::Top: return static_cast<int>(Botcraft::Direction::Up);
|
||||
case EntityFace::Bottom: return static_cast<int>(Botcraft::Direction::Down);
|
||||
case EntityFace::South: return static_cast<int>(Botcraft::Direction::South);
|
||||
case EntityFace::North: return static_cast<int>(Botcraft::Direction::North);
|
||||
case EntityFace::West: return static_cast<int>(Botcraft::Direction::West);
|
||||
case EntityFace::East: return static_cast<int>(Botcraft::Direction::East);
|
||||
default: throw std::runtime_error("invalid item frame face");
|
||||
}
|
||||
}
|
||||
|
||||
bool IsItemFrame(const Botcraft::ItemFrameEntity &frame)
|
||||
{
|
||||
return frame.GetType() == Botcraft::ItemFrameEntity::GetClassType() ||
|
||||
frame.GetType() == Botcraft::GlowItemFrameEntity::GetClassType();
|
||||
}
|
||||
|
||||
bool DecodeAttachment(const Botcraft::Vector3<double> &position, int direction,
|
||||
Botcraft::Vector3<double> &anchor, Botcraft::Vector3<double> &normal)
|
||||
{
|
||||
if (!DirectionNormal(direction, normal)) return false;
|
||||
if (ValidBlockPosition(position))
|
||||
{
|
||||
anchor = position; // AddEntity(Entity, direction, BlockPos)
|
||||
return true;
|
||||
}
|
||||
// EntityPositionSync/absolute teleport carry the actual entity center.
|
||||
// Invert vanilla's exact center formula. No rounding, radius matching or
|
||||
// epsilon: only a geometrically valid integral attachment cell is accepted.
|
||||
anchor = {position.x - 0.5 + normal.x * 0.46875,
|
||||
position.y - 0.5 + normal.y * 0.46875,
|
||||
position.z - 0.5 + normal.z * 0.46875};
|
||||
return ValidBlockPosition(anchor);
|
||||
}
|
||||
|
||||
const char *DirectionName(int direction)
|
||||
{
|
||||
switch (direction)
|
||||
{
|
||||
case -1: return "any";
|
||||
case 0: return "b";
|
||||
case 1: return "t";
|
||||
case 2: return "n";
|
||||
case 3: return "s";
|
||||
case 4: return "w";
|
||||
case 5: return "e";
|
||||
default: return "invalid";
|
||||
}
|
||||
}
|
||||
|
||||
bool Matches(const Botcraft::ItemFrameEntity &frame, const ActionCommand &command, int requestedDirection)
|
||||
{
|
||||
if (!IsItemFrame(frame))
|
||||
return false;
|
||||
const int direction = frame.GetDataDirection();
|
||||
Botcraft::Vector3<double> anchor, normal;
|
||||
if ((requestedDirection != -1 && direction != requestedDirection) ||
|
||||
!DecodeAttachment(frame.GetPosition(), direction, anchor, normal))
|
||||
return false;
|
||||
return anchor.x - normal.x == static_cast<double>(command.x) &&
|
||||
anchor.y - normal.y == static_cast<double>(command.y) &&
|
||||
anchor.z - normal.z == static_cast<double>(command.z);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool MatchesItemFrame(const Botcraft::ItemFrameEntity &frame, const ActionCommand &command)
|
||||
{
|
||||
return Matches(frame, command, CommandDirection(command));
|
||||
}
|
||||
|
||||
std::shared_ptr<Botcraft::ItemFrameEntity> FindItemFrame(Botcraft::EntityManager &manager,
|
||||
const ActionCommand &command)
|
||||
{
|
||||
const int direction = CommandDirection(command);
|
||||
std::shared_ptr<Botcraft::ItemFrameEntity> result;
|
||||
{
|
||||
const auto entities = manager.GetEntities();
|
||||
for (const auto &[id, entity] : *entities)
|
||||
{
|
||||
const auto frame = std::dynamic_pointer_cast<Botcraft::ItemFrameEntity>(entity);
|
||||
if (!frame || !Matches(*frame, command, direction))
|
||||
continue;
|
||||
if (result)
|
||||
throw std::runtime_error("ambiguous item frame target: multiple frames on the requested block/face");
|
||||
result = frame;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Botcraft::Vector3<double> ItemFrameCenter(const Botcraft::ItemFrameEntity &frame)
|
||||
{
|
||||
Botcraft::Vector3<double> anchor, normal;
|
||||
if (!IsItemFrame(frame) || !DecodeAttachment(frame.GetPosition(), frame.GetDataDirection(), anchor, normal))
|
||||
throw std::runtime_error("invalid item frame attachment position or direction");
|
||||
|
||||
// Verified against the official 1.21.11 client bytecode, not inferred from
|
||||
// old spawn-center geometry (mapped names at mappings.dev/1.21.11):
|
||||
// ItemFrame.getAddEntityPacket -> new ClientboundAddEntityPacket(this,
|
||||
// getDirection().get3DDataValue(), getPos()). Its BlockPos constructor
|
||||
// transmits integer XYZ. Later absolute position packets can store center
|
||||
// XYZ in GetPosition(), so decode either representation before using it.
|
||||
// ItemFrame.createBoundingBox separately uses
|
||||
// Vec3.atCenterOf(pos).relative(direction, -0.46875).
|
||||
// https://mappings.dev/1.21.11/net/minecraft/world/entity/decoration/ItemFrame.html
|
||||
// https://mappings.dev/1.21.11/net/minecraft/network/protocol/game/ClientboundAddEntityPacket.html
|
||||
return {anchor.x + 0.5 - normal.x * 0.46875, anchor.y + 0.5 - normal.y * 0.46875,
|
||||
anchor.z + 0.5 - normal.z * 0.46875};
|
||||
}
|
||||
|
||||
std::string DescribeItemFrameTargets(Botcraft::EntityManager &manager, const ActionCommand &command)
|
||||
{
|
||||
const int requested = CommandDirection(command);
|
||||
struct Snapshot
|
||||
{
|
||||
int id, direction;
|
||||
std::string type;
|
||||
Botcraft::Vector3<double> position;
|
||||
double distance;
|
||||
};
|
||||
std::vector<Snapshot> nearby;
|
||||
std::size_t loaded = 0;
|
||||
const Botcraft::Vector3<double> origin(command.x + 0.5, command.y + 0.5, command.z + 0.5);
|
||||
{
|
||||
const auto entities = manager.GetEntities();
|
||||
for (const auto &[id, entity] : *entities)
|
||||
{
|
||||
const auto frame = std::dynamic_pointer_cast<Botcraft::ItemFrameEntity>(entity);
|
||||
if (!frame || !IsItemFrame(*frame)) continue;
|
||||
++loaded;
|
||||
const auto position = frame->GetPosition();
|
||||
const double distance = origin.SqrDist(position);
|
||||
if (!std::isfinite(distance) || distance > 64.0) continue;
|
||||
nearby.push_back({id, frame->GetDataDirection(), frame->GetName(), position, distance});
|
||||
}
|
||||
} // Do not retain the manager lock while formatting diagnostic output.
|
||||
std::sort(nearby.begin(), nearby.end(), [](const auto &a, const auto &b) {
|
||||
return a.distance != b.distance ? a.distance < b.distance : a.id < b.id;
|
||||
});
|
||||
std::ostringstream out;
|
||||
out << std::setprecision(17) << "requested support=(" << command.x << ',' << command.y << ',' << command.z
|
||||
<< "), face=" << DirectionName(requested) << "; loaded_frames=" << loaded
|
||||
<< "; nearby_within_8=" << nearby.size();
|
||||
for (std::size_t i = 0; i < std::min<std::size_t>(8, nearby.size()); ++i)
|
||||
{
|
||||
const auto &entry = nearby[i];
|
||||
Botcraft::Vector3<double> anchor, normal;
|
||||
out << "; id=" << entry.id << " type=" << entry.type << " raw=(" << entry.position.x << ','
|
||||
<< entry.position.y << ',' << entry.position.z << ") direction=" << entry.direction;
|
||||
if (entry.direction >= 0 && entry.direction <= 5) out << '(' << DirectionName(entry.direction) << ')';
|
||||
if (DecodeAttachment(entry.position, entry.direction, anchor, normal))
|
||||
out << " support=(" << anchor.x - normal.x << ',' << anchor.y - normal.y << ',' << anchor.z - normal.z << ')';
|
||||
else
|
||||
out << " support=unknown(invalid position/direction)";
|
||||
}
|
||||
if (nearby.size() > 8) out << "; showing_nearest=8";
|
||||
return out.str();
|
||||
}
|
||||
|
||||
std::shared_ptr<ProtocolCraft::ServerboundInteractPacket> MakeEntityInteractionPacket(int entityId, bool attack,
|
||||
bool secondary)
|
||||
{
|
||||
auto packet = std::make_shared<ProtocolCraft::ServerboundInteractPacket>();
|
||||
packet->SetEntityId(entityId);
|
||||
packet->SetAction(attack ? 1 : 0);
|
||||
if (!attack)
|
||||
packet->SetHand(static_cast<int>(Botcraft::Hand::Main));
|
||||
packet->SetUsingSecondaryAction(secondary);
|
||||
return packet;
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,370 @@
|
||||
#include "LineEditor.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::size_t MaxEscapeBytes = 64;
|
||||
|
||||
bool IsContinuation(unsigned char byte)
|
||||
{
|
||||
return (byte & 0xc0) == 0x80;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::optional<std::string> LineEditor::Feed(char byte)
|
||||
{
|
||||
if (eof)
|
||||
return std::nullopt;
|
||||
|
||||
const auto value = static_cast<unsigned char>(byte);
|
||||
if (swallowLf)
|
||||
{
|
||||
swallowLf = false;
|
||||
if (byte == '\n')
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// A newline is also a recovery boundary for truncated/malformed escapes.
|
||||
if (byte == '\r' || byte == '\n')
|
||||
{
|
||||
swallowLf = byte == '\r';
|
||||
ResetEscape();
|
||||
utf8Pending.clear();
|
||||
utf8Expected = 0;
|
||||
return Submit();
|
||||
}
|
||||
|
||||
if (value == 0x1b && escapeState != EscapeState::String && escapeState != EscapeState::StringEscape)
|
||||
{
|
||||
utf8Pending.clear();
|
||||
utf8Expected = 0;
|
||||
ResetEscape();
|
||||
escapeState = EscapeState::Start;
|
||||
return std::nullopt;
|
||||
}
|
||||
if (escapeState != EscapeState::None)
|
||||
{
|
||||
FeedEscape(value);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
if (value < 0x20 || value == 0x7f)
|
||||
{
|
||||
utf8Pending.clear();
|
||||
utf8Expected = 0;
|
||||
switch (value)
|
||||
{
|
||||
case 0x01: // Ctrl-A
|
||||
cursor = 0;
|
||||
break;
|
||||
case 0x04: // Ctrl-D
|
||||
if (text.empty())
|
||||
eof = true;
|
||||
else
|
||||
DeleteAtCursor();
|
||||
break;
|
||||
case 0x05: // Ctrl-E
|
||||
cursor = text.size();
|
||||
break;
|
||||
case 0x08: // Ctrl-H/backspace
|
||||
case 0x7f:
|
||||
if (cursor != 0)
|
||||
{
|
||||
const auto previous = PreviousBoundary();
|
||||
text.erase(previous, cursor - previous);
|
||||
cursor = previous;
|
||||
}
|
||||
break;
|
||||
case 0x09:
|
||||
InsertCodepoint("\t");
|
||||
break;
|
||||
case 0x0b: // Ctrl-K
|
||||
text.erase(cursor);
|
||||
break;
|
||||
case 0x15: // Ctrl-U
|
||||
text.erase(0, cursor);
|
||||
cursor = 0;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
InsertByte(value);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const std::string &LineEditor::Text() const
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
||||
std::size_t LineEditor::Cursor() const
|
||||
{
|
||||
return cursor;
|
||||
}
|
||||
|
||||
bool LineEditor::IsEof() const
|
||||
{
|
||||
return eof;
|
||||
}
|
||||
|
||||
void LineEditor::ResetEscape()
|
||||
{
|
||||
escapeState = EscapeState::None;
|
||||
escapeParameters.clear();
|
||||
escapeLength = 0;
|
||||
escapeTooLong = false;
|
||||
}
|
||||
|
||||
void LineEditor::FeedEscape(unsigned char byte)
|
||||
{
|
||||
// Never accumulate an unbounded escape. Overlong sequences are discarded up
|
||||
// to their final byte (or newline/new ESC), rather than leaking their tail
|
||||
// into a command. Even control strings use constant memory.
|
||||
if (escapeLength < MaxEscapeBytes)
|
||||
++escapeLength;
|
||||
else
|
||||
escapeTooLong = true;
|
||||
|
||||
switch (escapeState)
|
||||
{
|
||||
case EscapeState::Start:
|
||||
switch (byte)
|
||||
{
|
||||
case '[':
|
||||
escapeState = EscapeState::Csi;
|
||||
break;
|
||||
case 'O':
|
||||
escapeState = EscapeState::Ss3;
|
||||
break;
|
||||
case ']': // OSC
|
||||
case 'P': // DCS
|
||||
case 'X': // SOS
|
||||
case '^': // PM
|
||||
case '_': // APC
|
||||
escapeState = EscapeState::String;
|
||||
break;
|
||||
default:
|
||||
if (byte >= 0x20 && byte <= 0x2f)
|
||||
escapeState = EscapeState::Intermediate;
|
||||
else
|
||||
ResetEscape();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case EscapeState::Intermediate:
|
||||
if (byte < 0x20 || byte > 0x2f)
|
||||
ResetEscape();
|
||||
break;
|
||||
case EscapeState::Csi:
|
||||
case EscapeState::Ss3:
|
||||
if (byte >= 0x40 && byte <= 0x7e)
|
||||
{
|
||||
if (!escapeTooLong)
|
||||
FinishControlSequence(static_cast<char>(byte));
|
||||
ResetEscape();
|
||||
}
|
||||
else if (byte >= 0x20 && byte <= 0x3f)
|
||||
{
|
||||
if (!escapeTooLong)
|
||||
escapeParameters.push_back(static_cast<char>(byte));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Invalid bytes invalidate the sequence but keep swallowing until
|
||||
// its final byte. Do not interpret the remainder as literal input.
|
||||
escapeTooLong = true;
|
||||
}
|
||||
break;
|
||||
case EscapeState::String:
|
||||
if (byte == 0x07)
|
||||
ResetEscape();
|
||||
else if (byte == 0x1b)
|
||||
escapeState = EscapeState::StringEscape;
|
||||
break;
|
||||
case EscapeState::StringEscape:
|
||||
if (byte == '\\' || byte == 0x07)
|
||||
ResetEscape();
|
||||
else if (byte != 0x1b)
|
||||
escapeState = EscapeState::String;
|
||||
break;
|
||||
case EscapeState::None:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void LineEditor::FinishControlSequence(char finalByte)
|
||||
{
|
||||
if (escapeParameters.empty())
|
||||
{
|
||||
switch (finalByte)
|
||||
{
|
||||
case 'A':
|
||||
HistoryUp();
|
||||
break;
|
||||
case 'B':
|
||||
HistoryDown();
|
||||
break;
|
||||
case 'C':
|
||||
cursor = NextBoundary();
|
||||
break;
|
||||
case 'D':
|
||||
cursor = PreviousBoundary();
|
||||
break;
|
||||
case 'H':
|
||||
cursor = 0;
|
||||
break;
|
||||
case 'F':
|
||||
cursor = text.size();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (escapeState == EscapeState::Csi && finalByte == '~')
|
||||
{
|
||||
if (escapeParameters == "1" || escapeParameters == "7")
|
||||
cursor = 0;
|
||||
else if (escapeParameters == "4" || escapeParameters == "8")
|
||||
cursor = text.size();
|
||||
else if (escapeParameters == "3")
|
||||
DeleteAtCursor();
|
||||
}
|
||||
}
|
||||
|
||||
void LineEditor::InsertByte(unsigned char byte)
|
||||
{
|
||||
if (!utf8Pending.empty())
|
||||
{
|
||||
if (IsContinuation(byte))
|
||||
{
|
||||
const auto lead = static_cast<unsigned char>(utf8Pending.front());
|
||||
if (utf8Pending.size() == 1 && ((lead == 0xe0 && byte < 0xa0) || (lead == 0xed && byte >= 0xa0) ||
|
||||
(lead == 0xf0 && byte < 0x90) || (lead == 0xf4 && byte >= 0x90)))
|
||||
{
|
||||
utf8Pending.clear();
|
||||
utf8Expected = 0;
|
||||
return;
|
||||
}
|
||||
utf8Pending.push_back(static_cast<char>(byte));
|
||||
if (utf8Pending.size() == utf8Expected)
|
||||
{
|
||||
// Clear the decoder before insertion, including when the line
|
||||
// limit throws, so the next byte starts from a clean state.
|
||||
auto codepoint = std::move(utf8Pending);
|
||||
utf8Pending.clear();
|
||||
utf8Expected = 0;
|
||||
InsertCodepoint(codepoint);
|
||||
}
|
||||
return;
|
||||
}
|
||||
utf8Pending.clear();
|
||||
utf8Expected = 0;
|
||||
// A non-continuation byte can start a new codepoint; do not lose it.
|
||||
}
|
||||
|
||||
if (byte < 0x80)
|
||||
InsertCodepoint(std::string(1, static_cast<char>(byte)));
|
||||
else
|
||||
{
|
||||
if (byte >= 0xc2 && byte <= 0xdf)
|
||||
utf8Expected = 2;
|
||||
else if (byte >= 0xe0 && byte <= 0xef)
|
||||
utf8Expected = 3;
|
||||
else if (byte >= 0xf0 && byte <= 0xf4)
|
||||
utf8Expected = 4;
|
||||
else
|
||||
return;
|
||||
utf8Pending.assign(1, static_cast<char>(byte));
|
||||
}
|
||||
}
|
||||
|
||||
void LineEditor::InsertCodepoint(const std::string &codepoint)
|
||||
{
|
||||
if (codepoint.size() > MaxLineBytes - text.size())
|
||||
throw std::length_error("Terminal input line exceeds 64 KiB; delete characters before continuing");
|
||||
text.insert(cursor, codepoint);
|
||||
cursor += codepoint.size();
|
||||
}
|
||||
|
||||
std::size_t LineEditor::PreviousBoundary() const
|
||||
{
|
||||
if (cursor == 0)
|
||||
return 0;
|
||||
auto previous = cursor - 1;
|
||||
while (previous != 0 && IsContinuation(static_cast<unsigned char>(text[previous])))
|
||||
--previous;
|
||||
return previous;
|
||||
}
|
||||
|
||||
std::size_t LineEditor::NextBoundary() const
|
||||
{
|
||||
if (cursor == text.size())
|
||||
return cursor;
|
||||
auto next = cursor + 1;
|
||||
while (next < text.size() && IsContinuation(static_cast<unsigned char>(text[next])))
|
||||
++next;
|
||||
return next;
|
||||
}
|
||||
|
||||
void LineEditor::DeleteAtCursor()
|
||||
{
|
||||
text.erase(cursor, NextBoundary() - cursor);
|
||||
}
|
||||
|
||||
void LineEditor::HistoryUp()
|
||||
{
|
||||
if (history.empty() || historyIndex == 0)
|
||||
return;
|
||||
if (historyIndex == history.size())
|
||||
{
|
||||
draft = text;
|
||||
draftCursor = cursor;
|
||||
}
|
||||
text = history[--historyIndex];
|
||||
cursor = text.size();
|
||||
}
|
||||
|
||||
void LineEditor::HistoryDown()
|
||||
{
|
||||
if (historyIndex == history.size())
|
||||
return;
|
||||
++historyIndex;
|
||||
if (historyIndex == history.size())
|
||||
{
|
||||
text = draft;
|
||||
cursor = draftCursor;
|
||||
}
|
||||
else
|
||||
{
|
||||
text = history[historyIndex];
|
||||
cursor = text.size();
|
||||
}
|
||||
}
|
||||
|
||||
std::string LineEditor::Submit()
|
||||
{
|
||||
if (std::any_of(text.begin(), text.end(), [](unsigned char byte) { return !std::isspace(byte); }) &&
|
||||
(history.empty() || history.back() != text))
|
||||
{
|
||||
history.push_back(text);
|
||||
if (history.size() > MaxHistoryEntries)
|
||||
history.erase(history.begin());
|
||||
}
|
||||
historyIndex = history.size();
|
||||
draft.clear();
|
||||
draftCursor = 0;
|
||||
cursor = 0;
|
||||
auto line = std::move(text);
|
||||
text.clear();
|
||||
return line;
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,610 @@
|
||||
#include "TerminalConsole.h"
|
||||
|
||||
#include "LineEditor.h"
|
||||
#include "TerminalInput.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <streambuf>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <io.h>
|
||||
#else
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
namespace
|
||||
{
|
||||
#ifndef _WIN32
|
||||
// A disconnected redirected logger must not terminate the process with SIGPIPE
|
||||
// while its terminal is raw. Block only this writer thread; preserve any signal
|
||||
// which was already pending rather than changing the application's disposition.
|
||||
class BlockBrokenPipe
|
||||
{
|
||||
public:
|
||||
BlockBrokenPipe() noexcept
|
||||
{
|
||||
sigemptyset(&blocked);
|
||||
sigaddset(&blocked, SIGPIPE);
|
||||
active = pthread_sigmask(SIG_BLOCK, &blocked, &previous) == 0;
|
||||
sigset_t pending{};
|
||||
pendingBefore = !active || sigpending(&pending) != 0 || sigismember(&pending, SIGPIPE) == 1;
|
||||
}
|
||||
void OnFailure() noexcept { broken = errno == EPIPE; }
|
||||
~BlockBrokenPipe() noexcept
|
||||
{
|
||||
if (!active) return;
|
||||
if (broken && !pendingBefore)
|
||||
{
|
||||
#ifdef __APPLE__
|
||||
// Darwin lacks sigtimedwait. EPIPE generated SIGPIPE for this
|
||||
// blocked writer thread; check pending in case SIGPIPE is ignored.
|
||||
sigset_t pending{};
|
||||
if (sigpending(&pending) == 0 && sigismember(&pending, SIGPIPE) == 1)
|
||||
{
|
||||
int signal = 0;
|
||||
sigwait(&blocked, &signal);
|
||||
}
|
||||
#else
|
||||
timespec immediate{};
|
||||
while (sigtimedwait(&blocked, nullptr, &immediate) < 0 && errno == EINTR) {}
|
||||
#endif
|
||||
}
|
||||
pthread_sigmask(SIG_SETMASK, &previous, nullptr);
|
||||
}
|
||||
private:
|
||||
sigset_t blocked{}, previous{};
|
||||
bool active = false, pendingBefore = true, broken = false;
|
||||
};
|
||||
#endif
|
||||
|
||||
// No iostreams here: callers may route their iostream buffers back into us.
|
||||
bool WriteFd(int fd, std::string_view text) noexcept
|
||||
{
|
||||
#ifndef _WIN32
|
||||
BlockBrokenPipe blocked;
|
||||
#endif
|
||||
while (!text.empty())
|
||||
{
|
||||
#ifdef _WIN32
|
||||
const auto count = _write(fd, text.data(), static_cast<unsigned>(std::min<std::size_t>(text.size(), 65536)));
|
||||
#else
|
||||
const auto count = write(fd, text.data(), text.size());
|
||||
#endif
|
||||
if (count < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (count <= 0)
|
||||
{
|
||||
#ifndef _WIN32
|
||||
if (count < 0) blocked.OnFailure();
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
text.remove_prefix(static_cast<std::size_t>(count));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifndef _WIN32
|
||||
bool SameTty(int a, int b)
|
||||
{
|
||||
struct stat left{}, right{};
|
||||
return isatty(a) && isatty(b) && fstat(a, &left) == 0 && fstat(b, &right) == 0 &&
|
||||
left.st_dev == right.st_dev && left.st_ino == right.st_ino && left.st_rdev == right.st_rdev;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Locale-independent terminal widths: CJK and common emoji are double width;
|
||||
// combining marks/variation selectors are zero width. This intentionally does
|
||||
// not promise grapheme-cluster shaping for every terminal's emoji font.
|
||||
int CellWidth(std::uint32_t c)
|
||||
{
|
||||
if ((c >= 0x300 && c <= 0x36f) || (c >= 0x1ab0 && c <= 0x1aff) ||
|
||||
(c >= 0x1dc0 && c <= 0x1dff) || (c >= 0x20d0 && c <= 0x20ff) ||
|
||||
(c >= 0xfe00 && c <= 0xfe0f) || (c >= 0xfe20 && c <= 0xfe2f) ||
|
||||
(c >= 0xe0100 && c <= 0xe01ef) || c == 0x200d)
|
||||
return 0;
|
||||
if (c >= 0x1100 && (c <= 0x115f || c == 0x2329 || c == 0x232a ||
|
||||
(c >= 0x2e80 && c <= 0xa4cf && c != 0x303f) || (c >= 0xac00 && c <= 0xd7a3) ||
|
||||
(c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe10 && c <= 0xfe19) ||
|
||||
(c >= 0xfe30 && c <= 0xfe6f) || (c >= 0xff00 && c <= 0xff60) ||
|
||||
(c >= 0xffe0 && c <= 0xffe6) || (c >= 0x1f300 && c <= 0x1faff) ||
|
||||
(c >= 0x20000 && c <= 0x3fffd)))
|
||||
return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Stateful across output fragments. Strip *all* terminal escape sequences,
|
||||
// including OSC/DCS and their payloads, and reject malformed UTF-8/C1 controls.
|
||||
// A logger cannot reset margins, move the cursor or invoke terminal commands.
|
||||
class LogFilter
|
||||
{
|
||||
public:
|
||||
std::string Feed(std::string_view input)
|
||||
{
|
||||
std::string result;
|
||||
for (const unsigned char c : input)
|
||||
{
|
||||
// Treat a physical log line as a trust boundary. A truncated escape
|
||||
// or UTF-8 sequence in one line must not swallow subsequent logs.
|
||||
if (c == '\n')
|
||||
{
|
||||
state = State::Ground;
|
||||
remaining = 0;
|
||||
utf8.clear();
|
||||
result += "\r\n";
|
||||
continue;
|
||||
}
|
||||
if (state == State::StringEscape)
|
||||
{
|
||||
if (c == '\\' || c == 7) state = State::Ground;
|
||||
else if (c != 27) state = State::String;
|
||||
continue;
|
||||
}
|
||||
if (state == State::String)
|
||||
{
|
||||
if (c == 7) state = State::Ground;
|
||||
else if (c == 27) state = State::StringEscape;
|
||||
continue;
|
||||
}
|
||||
if (state == State::Escape)
|
||||
{
|
||||
if (c == '[') state = State::Csi;
|
||||
else if (c == ']' || c == 'P' || c == '^' || c == '_' || c == 'X') state = State::String;
|
||||
else if (c >= 0x20 && c <= 0x2f) state = State::Intermediate;
|
||||
else state = State::Ground;
|
||||
continue;
|
||||
}
|
||||
if (state == State::Csi || state == State::Intermediate)
|
||||
{
|
||||
if (c == 27) state = State::Escape;
|
||||
else if (c >= (state == State::Csi ? 0x40 : 0x30) && c <= 0x7e) state = State::Ground;
|
||||
continue;
|
||||
}
|
||||
if (remaining)
|
||||
{
|
||||
if ((c & 0xc0) == 0x80)
|
||||
{
|
||||
utf8.push_back(static_cast<char>(c));
|
||||
codepoint = (codepoint << 6) | (c & 0x3f);
|
||||
if (--remaining == 0)
|
||||
{
|
||||
if (codepoint >= minimum && codepoint <= 0x10ffff &&
|
||||
!(codepoint >= 0xd800 && codepoint <= 0xdfff) &&
|
||||
!(codepoint >= 0x80 && codepoint <= 0x9f))
|
||||
result += utf8;
|
||||
utf8.clear();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
remaining = 0;
|
||||
utf8.clear();
|
||||
}
|
||||
if (c == 27) state = State::Escape;
|
||||
else if (c == '\n') result += "\r\n";
|
||||
else if (c == '\r' || c == '\t' || (c >= 0x20 && c < 0x7f)) result += static_cast<char>(c);
|
||||
else if (c >= 0xc2 && c <= 0xf4)
|
||||
{
|
||||
remaining = c < 0xe0 ? 1 : c < 0xf0 ? 2 : 3;
|
||||
minimum = remaining == 1 ? 0x80 : remaining == 2 ? 0x800 : 0x10000;
|
||||
codepoint = c & (remaining == 1 ? 0x1f : remaining == 2 ? 0x0f : 0x07);
|
||||
utf8.assign(1, static_cast<char>(c));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private:
|
||||
enum class State { Ground, Escape, Csi, Intermediate, String, StringEscape };
|
||||
State state = State::Ground;
|
||||
int remaining = 0;
|
||||
std::uint32_t codepoint = 0, minimum = 0;
|
||||
std::string utf8;
|
||||
};
|
||||
|
||||
struct Glyph
|
||||
{
|
||||
std::size_t byte;
|
||||
std::string text;
|
||||
int width;
|
||||
};
|
||||
|
||||
std::vector<Glyph> DisplayGlyphs(const std::string &text)
|
||||
{
|
||||
std::vector<Glyph> result;
|
||||
for (std::size_t i = 0; i < text.size();)
|
||||
{
|
||||
const std::size_t start = i;
|
||||
const auto first = static_cast<unsigned char>(text[i++]);
|
||||
std::uint32_t cp = first;
|
||||
int continuation = first < 0x80 ? 0 : first >= 0xc2 && first < 0xe0 ? 1 :
|
||||
first >= 0xe0 && first < 0xf0 ? 2 : first >= 0xf0 && first <= 0xf4 ? 3 : -1;
|
||||
const int count = continuation;
|
||||
if (continuation > 0)
|
||||
cp &= continuation == 1 ? 0x1f : continuation == 2 ? 0xf : 7;
|
||||
bool valid = continuation >= 0;
|
||||
while (continuation-- > 0)
|
||||
{
|
||||
if (i == text.size() || (static_cast<unsigned char>(text[i]) & 0xc0) != 0x80)
|
||||
{ valid = false; break; }
|
||||
cp = (cp << 6) | (static_cast<unsigned char>(text[i++]) & 0x3f);
|
||||
}
|
||||
if (!valid || (count == 1 && cp < 0x80) || (count == 2 && cp < 0x800) ||
|
||||
(count == 3 && cp < 0x10000) || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff) ||
|
||||
cp < 0x20 || (cp >= 0x7f && cp <= 0x9f))
|
||||
result.push_back({start, cp == '\t' ? " " : "?", 1});
|
||||
else
|
||||
result.push_back({start, text.substr(start, i - start), CellWidth(cp)});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string Position(int row, int column = 1)
|
||||
{
|
||||
return "\033[" + std::to_string(row) + ";" + std::to_string(column) + "H";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
struct TerminalConsole::Impl
|
||||
{
|
||||
struct Buffer : std::streambuf
|
||||
{
|
||||
Buffer(Impl &owner, bool error) : owner(owner), error(error) {}
|
||||
std::streamsize xsputn(const char *data, std::streamsize count) override
|
||||
{
|
||||
if (count > 0) owner.SafeLog(std::string_view(data, static_cast<std::size_t>(count)), error);
|
||||
return count;
|
||||
}
|
||||
int_type overflow(int_type ch) override
|
||||
{
|
||||
if (!traits_type::eq_int_type(ch, traits_type::eof()))
|
||||
{
|
||||
const char byte = traits_type::to_char_type(ch);
|
||||
owner.SafeLog(std::string_view(&byte, 1), error);
|
||||
}
|
||||
return traits_type::not_eof(ch);
|
||||
}
|
||||
int sync() override { return 0; }
|
||||
Impl &owner;
|
||||
bool error;
|
||||
};
|
||||
|
||||
Impl(int input, int output, int error)
|
||||
: inputFd(input), outputFd(output), errorFd(error), fallback(input),
|
||||
outBuffer(*this, false), errBuffer(*this, true), out(&outBuffer), err(&errBuffer) {}
|
||||
|
||||
~Impl() noexcept
|
||||
{
|
||||
// Lifetime contract: the logger must have been detached before this.
|
||||
Restore();
|
||||
}
|
||||
|
||||
void Restore() noexcept
|
||||
{
|
||||
#ifndef _WIN32
|
||||
if (raw)
|
||||
{
|
||||
while (tcsetattr(inputFd, TCSANOW, &saved) < 0 && errno == EINTR) {}
|
||||
raw = false;
|
||||
}
|
||||
if (split)
|
||||
{
|
||||
// No alternate screen: prior log history remains visible.
|
||||
try
|
||||
{
|
||||
std::string sequence = "\033[r";
|
||||
if (rows >= 2) sequence += Position(rows - 1) + "\033[2K";
|
||||
sequence += Position(std::max(1, rows)) + "\033[2K\r\033[?25h";
|
||||
WriteFd(outputFd, sequence);
|
||||
}
|
||||
catch (...) { WriteFd(outputFd, "\033[r\033[?25h\r\n"); }
|
||||
split = false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool Ended() const { return eof || (split ? editor.IsEof() : fallback.IsEof()); }
|
||||
|
||||
void Prompt()
|
||||
{
|
||||
if (started && !split && enabled && !Ended() && !promptShown)
|
||||
{
|
||||
WriteFd(outputFd, ">>> ");
|
||||
promptShown = true;
|
||||
}
|
||||
}
|
||||
|
||||
void Draw()
|
||||
{
|
||||
if (!split) { Prompt(); return; }
|
||||
if (rows <= 0 || columns <= 1) return;
|
||||
// Reserve the final column: writing it would set auto-wrap pending.
|
||||
const int budget = columns - 1;
|
||||
std::string sequence;
|
||||
if (rows >= 2)
|
||||
{
|
||||
const std::string status = Ended() ? "-- EOF --" : enabled ? "-- commands --" : "-- busy / pending --";
|
||||
sequence += Position(rows - 1) + "\033[2K" + status.substr(0, static_cast<std::size_t>(budget));
|
||||
}
|
||||
sequence += Position(rows) + "\033[2K";
|
||||
const std::string prompt = std::string(">>> ").substr(0, static_cast<std::size_t>(budget));
|
||||
sequence += prompt;
|
||||
const int available = budget - static_cast<int>(prompt.size());
|
||||
int cursorCells = 0;
|
||||
if (available > 0)
|
||||
{
|
||||
const auto glyphs = DisplayGlyphs(editor.Text());
|
||||
std::size_t cursor = 0;
|
||||
while (cursor < glyphs.size() && glyphs[cursor].byte < editor.Cursor()) ++cursor;
|
||||
std::size_t start = cursor;
|
||||
// Keep the cursor inside the viewport, even at end of a long line.
|
||||
while (start > 0 && cursorCells + glyphs[start - 1].width < available)
|
||||
{ --start; cursorCells += glyphs[start].width; }
|
||||
int used = 0;
|
||||
for (std::size_t i = start; i < glyphs.size(); ++i)
|
||||
{
|
||||
if (used + glyphs[i].width > available) break;
|
||||
// Avoid rendering a leading combining mark against the prompt.
|
||||
if (used == 0 && glyphs[i].width == 0) continue;
|
||||
sequence += glyphs[i].text;
|
||||
used += glyphs[i].width;
|
||||
}
|
||||
}
|
||||
sequence += Position(rows, std::min(columns, static_cast<int>(prompt.size()) + cursorCells + 1));
|
||||
WriteFd(outputFd, sequence);
|
||||
}
|
||||
|
||||
bool Layout(int newRows, int newColumns)
|
||||
{
|
||||
std::string sequence = "\033[r";
|
||||
// Clear only former footer rows which still exist after shrinking.
|
||||
if (rows >= 2 && rows - 1 <= newRows) sequence += Position(rows - 1) + "\033[2K";
|
||||
if (rows > 0 && rows <= newRows) sequence += Position(rows) + "\033[2K";
|
||||
rows = newRows;
|
||||
columns = newColumns;
|
||||
if (rows >= 3)
|
||||
sequence += "\033[1;" + std::to_string(rows - 2) + "r" + Position(rows - 2);
|
||||
else
|
||||
sequence += Position(1);
|
||||
sequence += "\0337"; // saved cursor belongs to the log region, never footer
|
||||
if (!WriteFd(outputFd, sequence)) return false;
|
||||
Draw();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Log(std::string_view text, bool error)
|
||||
{
|
||||
if (text.empty()) return;
|
||||
if (!split || (error && !errorOnScreen))
|
||||
{
|
||||
const int destination = error ? errorFd : outputFd;
|
||||
if (!split && promptShown && (!error || errorFd == outputFd || errorOnScreen))
|
||||
{
|
||||
WriteFd(outputFd, "\n");
|
||||
promptShown = false;
|
||||
}
|
||||
WriteFd(destination, text);
|
||||
return;
|
||||
}
|
||||
const std::string safe = (error ? errFilter : outFilter).Feed(text);
|
||||
if (safe.empty()) return;
|
||||
// Less than three rows cannot hold both regions. Retain raw editing and
|
||||
// suppress on-screen logs until it grows, rather than damage the input.
|
||||
if (rows >= 3)
|
||||
{
|
||||
WriteFd(outputFd, "\0338");
|
||||
WriteFd(outputFd, safe);
|
||||
WriteFd(outputFd, "\0337");
|
||||
}
|
||||
Draw();
|
||||
}
|
||||
|
||||
void SafeLog(std::string_view text, bool error) noexcept
|
||||
{
|
||||
try
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(mutex);
|
||||
Resize();
|
||||
Log(text, error);
|
||||
}
|
||||
catch (...) {} // logger callbacks must never propagate exceptions
|
||||
}
|
||||
|
||||
void Resize()
|
||||
{
|
||||
#ifndef _WIN32
|
||||
if (split)
|
||||
{
|
||||
winsize size{};
|
||||
if (ioctl(outputFd, TIOCGWINSZ, &size) == 0 && size.ws_row > 0 && size.ws_col > 0 &&
|
||||
(rows != size.ws_row || columns != size.ws_col))
|
||||
Layout(size.ws_row, size.ws_col);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
[[noreturn]] void InputError(const std::string &message)
|
||||
{
|
||||
eof = true;
|
||||
Draw();
|
||||
throw std::runtime_error("Terminal input: " + message);
|
||||
}
|
||||
|
||||
int inputFd, outputFd, errorFd;
|
||||
TerminalInput fallback;
|
||||
LineEditor editor;
|
||||
mutable std::mutex mutex;
|
||||
bool started = false, split = false, raw = false, enabled = true, eof = false;
|
||||
bool promptShown = false, errorOnScreen = false;
|
||||
int rows = 0, columns = 0;
|
||||
#ifndef _WIN32
|
||||
termios saved{};
|
||||
#endif
|
||||
LogFilter outFilter, errFilter;
|
||||
Buffer outBuffer, errBuffer;
|
||||
std::ostream out, err;
|
||||
};
|
||||
|
||||
TerminalConsole::TerminalConsole(int inputFd, int outputFd, int errorFd)
|
||||
: impl(std::make_unique<Impl>(inputFd, outputFd, errorFd)) {}
|
||||
TerminalConsole::~TerminalConsole() noexcept = default;
|
||||
|
||||
void TerminalConsole::Start()
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(impl->mutex);
|
||||
if (impl->started) return;
|
||||
impl->started = true;
|
||||
#ifndef _WIN32
|
||||
impl->errorOnScreen = SameTty(impl->outputFd, impl->errorFd);
|
||||
const char *term = std::getenv("TERM");
|
||||
winsize size{};
|
||||
if (term && *term && std::string_view(term) != "dumb" && SameTty(impl->inputFd, impl->outputFd) &&
|
||||
ioctl(impl->outputFd, TIOCGWINSZ, &size) == 0 && size.ws_row >= 4 && size.ws_col >= 20 &&
|
||||
tcgetattr(impl->inputFd, &impl->saved) == 0)
|
||||
{
|
||||
termios mode = impl->saved;
|
||||
mode.c_lflag &= static_cast<tcflag_t>(~(ICANON | ECHO | ECHONL | IEXTEN));
|
||||
mode.c_lflag |= ISIG;
|
||||
mode.c_iflag &= static_cast<tcflag_t>(~IXON);
|
||||
mode.c_cc[VMIN] = 0;
|
||||
mode.c_cc[VTIME] = 0;
|
||||
#ifdef VQUIT
|
||||
// SIGQUIT's default disposition skips destructors and leaves raw mode
|
||||
// behind. Ctrl+C remains the supported cooperative cancellation key.
|
||||
mode.c_cc[VQUIT] = _POSIX_VDISABLE;
|
||||
#endif
|
||||
#ifdef VSUSP
|
||||
mode.c_cc[VSUSP] = _POSIX_VDISABLE;
|
||||
#endif
|
||||
#ifdef VDSUSP
|
||||
mode.c_cc[VDSUSP] = _POSIX_VDISABLE;
|
||||
#endif
|
||||
int changed;
|
||||
do { changed = tcsetattr(impl->inputFd, TCSANOW, &mode); } while (changed < 0 && errno == EINTR);
|
||||
if (changed == 0)
|
||||
{
|
||||
impl->raw = true;
|
||||
impl->split = true;
|
||||
try
|
||||
{
|
||||
if (impl->Layout(size.ws_row, size.ws_col)) return;
|
||||
}
|
||||
catch (...) { impl->Restore(); throw; }
|
||||
impl->Restore();
|
||||
}
|
||||
else
|
||||
{
|
||||
// A failed mode change must not leave a partially applied mode.
|
||||
while (tcsetattr(impl->inputFd, TCSANOW, &impl->saved) < 0 && errno == EINTR) {}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
impl->Prompt();
|
||||
}
|
||||
|
||||
bool TerminalConsole::IsSplit() const
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(impl->mutex);
|
||||
return impl->split;
|
||||
}
|
||||
bool TerminalConsole::IsEof() const
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(impl->mutex);
|
||||
return impl->Ended();
|
||||
}
|
||||
void TerminalConsole::SetInputEnabled(bool enabled)
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(impl->mutex);
|
||||
if (impl->enabled == enabled) { impl->Prompt(); return; }
|
||||
impl->enabled = enabled;
|
||||
impl->Resize();
|
||||
impl->Draw();
|
||||
}
|
||||
void TerminalConsole::Tick()
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(impl->mutex);
|
||||
impl->Resize();
|
||||
impl->Prompt();
|
||||
}
|
||||
std::ostream &TerminalConsole::Out() { return impl->out; }
|
||||
std::ostream &TerminalConsole::Err() { return impl->err; }
|
||||
void TerminalConsole::WriteLog(std::string_view text, bool error) noexcept { impl->SafeLog(text, error); }
|
||||
|
||||
std::optional<std::string> TerminalConsole::PollLine()
|
||||
{
|
||||
const std::lock_guard<std::mutex> guard(impl->mutex);
|
||||
impl->Resize();
|
||||
if (!impl->enabled || impl->Ended()) return std::nullopt;
|
||||
if (!impl->split)
|
||||
{
|
||||
impl->Prompt();
|
||||
auto line = impl->fallback.PollLine();
|
||||
if (line || impl->fallback.IsEof())
|
||||
{
|
||||
if (impl->promptShown && !impl->fallback.IsInteractive()) WriteFd(impl->outputFd, "\n");
|
||||
impl->promptShown = false;
|
||||
}
|
||||
return line;
|
||||
}
|
||||
#ifndef _WIN32
|
||||
bool changed = false;
|
||||
for (std::size_t consumed = 0; consumed < 4096; ++consumed)
|
||||
{
|
||||
pollfd descriptor{impl->inputFd, POLLIN, 0};
|
||||
const int ready = poll(&descriptor, 1, 0);
|
||||
if (ready < 0)
|
||||
{
|
||||
if (errno == EINTR) break;
|
||||
impl->InputError(std::generic_category().message(errno));
|
||||
}
|
||||
if (!ready) break;
|
||||
if (descriptor.revents & POLLNVAL) impl->InputError("invalid or closed descriptor");
|
||||
if (!(descriptor.revents & (POLLIN | POLLHUP)))
|
||||
{
|
||||
if (descriptor.revents & POLLERR) impl->InputError("device polling error");
|
||||
break;
|
||||
}
|
||||
char byte = 0;
|
||||
const auto count = read(impl->inputFd, &byte, 1);
|
||||
if (count < 0)
|
||||
{
|
||||
if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) break;
|
||||
// Linux PTYs may report EIO once the master disappears.
|
||||
if (errno == EIO && (descriptor.revents & POLLHUP)) { impl->eof = true; break; }
|
||||
impl->InputError(std::generic_category().message(errno));
|
||||
}
|
||||
if (count == 0)
|
||||
{
|
||||
// VMIN=0 can return zero without EOF. Only a hangup is conclusive.
|
||||
if (descriptor.revents & POLLHUP) impl->eof = true;
|
||||
break;
|
||||
}
|
||||
changed = true;
|
||||
auto line = impl->editor.Feed(byte);
|
||||
if (line)
|
||||
{
|
||||
impl->Log(">>> " + *line + "\n", false);
|
||||
impl->Draw();
|
||||
return line; // Never consume any byte of the following request.
|
||||
}
|
||||
if (impl->editor.IsEof()) break;
|
||||
}
|
||||
if (changed || impl->Ended()) impl->Draw();
|
||||
#endif
|
||||
return std::nullopt;
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,182 @@
|
||||
#include "TerminalInput.h"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <Windows.h>
|
||||
#include <io.h>
|
||||
#else
|
||||
#include <poll.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
TerminalInput::TerminalInput()
|
||||
#ifdef _WIN32
|
||||
: TerminalInput(_fileno(stdin))
|
||||
#else
|
||||
: TerminalInput(STDIN_FILENO)
|
||||
#endif
|
||||
{
|
||||
}
|
||||
|
||||
TerminalInput::TerminalInput(int descriptor)
|
||||
: fd(descriptor),
|
||||
#ifdef _WIN32
|
||||
interactive(descriptor >= 0 && _isatty(descriptor) != 0)
|
||||
#else
|
||||
interactive(descriptor >= 0 && isatty(descriptor) != 0)
|
||||
#endif
|
||||
{
|
||||
}
|
||||
|
||||
bool TerminalInput::IsEof() const
|
||||
{
|
||||
return eof;
|
||||
}
|
||||
|
||||
bool TerminalInput::IsInteractive() const
|
||||
{
|
||||
return interactive;
|
||||
}
|
||||
|
||||
[[noreturn]] void TerminalInput::Fail(const std::string &message)
|
||||
{
|
||||
eof = true;
|
||||
partial.clear();
|
||||
throw std::runtime_error("Terminal input: " + message);
|
||||
}
|
||||
|
||||
std::string TerminalInput::TakeLine(bool removeCr)
|
||||
{
|
||||
std::string line;
|
||||
line.swap(partial);
|
||||
if (removeCr && !line.empty() && line.back() == '\r')
|
||||
line.pop_back();
|
||||
return line;
|
||||
}
|
||||
|
||||
TerminalInput::ReadResult TerminalInput::ReadByte(char &byte)
|
||||
{
|
||||
if (fd < 0)
|
||||
Fail("invalid file descriptor");
|
||||
#ifdef _WIN32
|
||||
// ReadFile deliberately bypasses CRT text translation: CRLF is handled
|
||||
// consistently by PollLine, and Ctrl-Z in a redirected file is not EOF.
|
||||
const auto rawHandle = _get_osfhandle(fd);
|
||||
if (rawHandle == -1)
|
||||
Fail("invalid input handle");
|
||||
const auto handle = reinterpret_cast<HANDLE>(rawHandle);
|
||||
const DWORD kind = GetFileType(handle);
|
||||
if (kind == FILE_TYPE_PIPE)
|
||||
{
|
||||
DWORD available = 0;
|
||||
if (!PeekNamedPipe(handle, nullptr, 0, nullptr, &available, nullptr))
|
||||
{
|
||||
const DWORD error = GetLastError();
|
||||
if (error == ERROR_BROKEN_PIPE || error == ERROR_PIPE_NOT_CONNECTED)
|
||||
return ReadResult::End;
|
||||
Fail("PeekNamedPipe: " + std::system_category().message(static_cast<int>(error)));
|
||||
}
|
||||
if (available == 0)
|
||||
return ReadResult::NotReady;
|
||||
}
|
||||
else if (kind != FILE_TYPE_DISK)
|
||||
{
|
||||
Fail("nonblocking native Windows console/device input is unsupported; redirect a pipe or file");
|
||||
}
|
||||
|
||||
DWORD count = 0;
|
||||
const bool success = ReadFile(handle, &byte, 1, &count, nullptr) != FALSE;
|
||||
if (!success)
|
||||
{
|
||||
const DWORD error = GetLastError();
|
||||
// Message-mode named pipes may deliver a byte and report more data.
|
||||
if (error == ERROR_MORE_DATA && count == 1)
|
||||
return ReadResult::Byte;
|
||||
if (error == ERROR_BROKEN_PIPE || error == ERROR_PIPE_NOT_CONNECTED || error == ERROR_HANDLE_EOF)
|
||||
return ReadResult::End;
|
||||
if (error == ERROR_NO_DATA)
|
||||
return ReadResult::NotReady;
|
||||
Fail("ReadFile: " + std::system_category().message(static_cast<int>(error)));
|
||||
}
|
||||
return count == 0 ? ReadResult::End : ReadResult::Byte;
|
||||
#else
|
||||
// Check before EVERY byte, not only once per line. A pipe can have a partial
|
||||
// line while its writer stays open. Reading chunks would consume later
|
||||
// requests while the caller is still executing the first one.
|
||||
pollfd descriptor{fd, POLLIN, 0};
|
||||
const int ready = poll(&descriptor, 1, 0);
|
||||
if (ready < 0)
|
||||
{
|
||||
const int error = errno;
|
||||
if (error == EINTR)
|
||||
return ReadResult::NotReady;
|
||||
Fail("poll: " + std::generic_category().message(error));
|
||||
}
|
||||
if (ready == 0)
|
||||
return ReadResult::NotReady;
|
||||
if ((descriptor.revents & POLLNVAL) != 0)
|
||||
Fail("invalid or closed file descriptor");
|
||||
if ((descriptor.revents & (POLLIN | POLLHUP)) == 0)
|
||||
{
|
||||
if ((descriptor.revents & POLLERR) != 0)
|
||||
Fail("input device reported a polling error");
|
||||
return ReadResult::NotReady;
|
||||
}
|
||||
|
||||
// HUP can coexist with unread bytes; drain them before observing read == 0.
|
||||
// With one reader, readiness guarantees this one-byte read cannot wait for
|
||||
// more input. No O_NONBLOCK toggle (which would affect duplicate fds).
|
||||
const auto count = read(fd, &byte, 1);
|
||||
if (count < 0)
|
||||
{
|
||||
const int error = errno;
|
||||
if (error == EINTR || error == EAGAIN || error == EWOULDBLOCK)
|
||||
return ReadResult::NotReady;
|
||||
Fail("read: " + std::generic_category().message(error));
|
||||
}
|
||||
return count == 0 ? ReadResult::End : ReadResult::Byte;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::optional<std::string> TerminalInput::PollLine()
|
||||
{
|
||||
if (eof)
|
||||
return std::nullopt;
|
||||
|
||||
// Prevent a continuously available long line from monopolising a tick.
|
||||
constexpr std::size_t byteBudget = 4096;
|
||||
for (std::size_t i = 0; i < byteBudget; ++i)
|
||||
{
|
||||
char byte = 0;
|
||||
const auto result = ReadByte(byte);
|
||||
if (result == ReadResult::NotReady)
|
||||
return std::nullopt;
|
||||
if (result == ReadResult::End)
|
||||
{
|
||||
eof = true;
|
||||
if (partial.empty())
|
||||
return std::nullopt;
|
||||
return TakeLine(false);
|
||||
}
|
||||
if (byte == '\n')
|
||||
return TakeLine(true);
|
||||
if (partial.size() == MaxLineBytes)
|
||||
{
|
||||
eof = true;
|
||||
partial.clear();
|
||||
throw std::length_error("Terminal input: line exceeds 64 KiB limit");
|
||||
}
|
||||
partial.push_back(byte);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
} // namespace Bilicraft
|
||||
@@ -0,0 +1,231 @@
|
||||
#include "ActionExecutor.h"
|
||||
#include "ActionFile.h"
|
||||
#include "BilicraftClient.h"
|
||||
|
||||
#include <climits>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "protocolCraft/Packets/Game/Serverbound/ServerboundContainerClickPacket.hpp"
|
||||
#include "botcraft/Game/Inventory/Window.hpp"
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace Bilicraft;
|
||||
using Botcraft::InventoryType;
|
||||
|
||||
TEST(ActionExecutor, MapsEveryGenericContainerSize)
|
||||
{
|
||||
const InventoryType types[] = {InventoryType::Generic9x1, InventoryType::Generic9x2, InventoryType::Generic9x3,
|
||||
InventoryType::Generic9x4, InventoryType::Generic9x5, InventoryType::Generic9x6};
|
||||
for (int rows = 1; rows <= 6; ++rows)
|
||||
{
|
||||
EXPECT_EQ(ActionGuiSlot(types[rows - 1], 1, 1), 0);
|
||||
EXPECT_EQ(ActionGuiSlot(types[rows - 1], rows, 9), rows * 9 - 1);
|
||||
EXPECT_THROW(ActionGuiSlot(types[rows - 1], rows + 1, 1), std::runtime_error);
|
||||
}
|
||||
EXPECT_EQ(ActionGuiSlot(InventoryType::ShulkerBox, 3, 9), 26);
|
||||
EXPECT_THROW(ActionGuiSlot(InventoryType::ShulkerBox, 4, 1), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, RejectsNonNineColumnGuiRatherThanGuessing)
|
||||
{
|
||||
for (const auto type : {InventoryType::PlayerInventory, InventoryType::Default, InventoryType::Generic3x3,
|
||||
InventoryType::Furnace, InventoryType::Hopper, InventoryType::Crafting,
|
||||
InventoryType::Merchant, InventoryType::Anvil})
|
||||
EXPECT_THROW(ActionGuiSlot(type, 1, 1), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, RejectsGuiBoundsBeforeArithmetic)
|
||||
{
|
||||
for (int bad : {INT_MIN, -1, 0, 10, INT_MAX})
|
||||
EXPECT_THROW(ActionGuiSlot(InventoryType::Generic9x6, 1, bad), std::runtime_error);
|
||||
for (int bad : {INT_MIN, -1, 0, 7, INT_MAX})
|
||||
EXPECT_THROW(ActionGuiSlot(InventoryType::Generic9x6, bad, 1), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, MapsAllBackpackAndHotbarPositions)
|
||||
{
|
||||
for (int row = 1; row <= 3; ++row)
|
||||
for (int col = 1; col <= 9; ++col)
|
||||
EXPECT_EQ(ActionBackpackSlot(row, col), 9 + (row - 1) * 9 + col - 1);
|
||||
for (int slot = 1; slot <= 9; ++slot)
|
||||
EXPECT_EQ(ActionHotbarIndex(slot), slot - 1);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, RejectsBackpackAndHotbarBounds)
|
||||
{
|
||||
for (int bad : {INT_MIN, -1, 0, 4, INT_MAX})
|
||||
EXPECT_THROW(ActionBackpackSlot(bad, 1), std::runtime_error);
|
||||
for (int bad : {INT_MIN, -1, 0, 10, INT_MAX})
|
||||
{
|
||||
EXPECT_THROW(ActionBackpackSlot(1, bad), std::runtime_error);
|
||||
EXPECT_THROW(ActionHotbarIndex(bad), std::runtime_error);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, BuildsRealNumberKeySwapWithoutCursorPrediction)
|
||||
{
|
||||
const auto packet = MakeBackpackSwapPacket(3, 9, 9);
|
||||
EXPECT_EQ(packet->GetContainerId(), 0);
|
||||
EXPECT_EQ(packet->GetStateId(), -1);
|
||||
EXPECT_EQ(packet->GetSlotNum(), 35);
|
||||
EXPECT_EQ(packet->GetButtonNum(), 8);
|
||||
EXPECT_EQ(packet->GetClickType(), 2);
|
||||
EXPECT_TRUE(packet->GetChangedSlots().empty());
|
||||
EXPECT_FALSE(packet->GetCarriedItem().GetActualItem().has_value());
|
||||
ProtocolCraft::WriteContainer bytes;
|
||||
packet->Write(bytes);
|
||||
EXPECT_FALSE(bytes.empty());
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, SwapPacketRejectsInvalidPositions)
|
||||
{
|
||||
EXPECT_THROW(MakeBackpackSwapPacket(0, 1, 1), std::runtime_error);
|
||||
EXPECT_THROW(MakeBackpackSwapPacket(1, 10, 1), std::runtime_error);
|
||||
EXPECT_THROW(MakeBackpackSwapPacket(1, 1, 10), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, ResolvesDropTargetWithoutChangingTheSelection)
|
||||
{
|
||||
for (int selected = 0; selected < 9; ++selected)
|
||||
{
|
||||
EXPECT_EQ(ActionDropSlot(0, selected), selected + 1);
|
||||
for (int requested = 1; requested <= 9; ++requested)
|
||||
EXPECT_EQ(ActionDropSlot(requested, selected), requested);
|
||||
}
|
||||
for (int invalid : {INT_MIN, -1, 9, INT_MAX})
|
||||
EXPECT_THROW(ActionDropSlot(0, invalid), std::runtime_error);
|
||||
for (int invalid : {INT_MIN, -1, 10, INT_MAX})
|
||||
EXPECT_THROW(ActionDropSlot(invalid, 0), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, BuildsSingleAndWholeStackDropPacketsForEveryHotbarSlot)
|
||||
{
|
||||
for (int slot = 1; slot <= 9; ++slot)
|
||||
for (bool all : {false, true})
|
||||
{
|
||||
const auto packet = MakeHotbarDropPacket(slot, all);
|
||||
EXPECT_EQ(packet->GetContainerId(), 0);
|
||||
EXPECT_EQ(packet->GetStateId(), -1);
|
||||
EXPECT_EQ(packet->GetSlotNum(), 35 + slot);
|
||||
EXPECT_EQ(packet->GetClickType(), 4);
|
||||
EXPECT_EQ(packet->GetButtonNum(), all ? 1 : 0);
|
||||
EXPECT_TRUE(packet->GetChangedSlots().empty());
|
||||
EXPECT_FALSE(packet->GetCarriedItem().GetActualItem().has_value());
|
||||
ProtocolCraft::WriteContainer bytes;
|
||||
packet->Write(bytes);
|
||||
EXPECT_FALSE(bytes.empty());
|
||||
}
|
||||
for (int invalid : {INT_MIN, -1, 0, 10, INT_MAX})
|
||||
EXPECT_THROW(MakeHotbarDropPacket(invalid, false), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, DropRemainderHandlesEmptySingleAndFullStacksWithoutMutatingInput)
|
||||
{
|
||||
const ProtocolCraft::Slot empty;
|
||||
EXPECT_TRUE(RemainingAfterDrop(empty, false).IsEmptySlot());
|
||||
EXPECT_TRUE(RemainingAfterDrop(empty, true).IsEmptySlot());
|
||||
ProtocolCraft::Slot original;
|
||||
original.SetItemId(1);
|
||||
for (int count : {1, 2, 64})
|
||||
{
|
||||
original.SetItemCount(count);
|
||||
const auto remaining = RemainingAfterDrop(original, false);
|
||||
EXPECT_EQ(remaining.GetItemCount(), count - 1);
|
||||
EXPECT_EQ(remaining.IsEmptySlot(), count == 1);
|
||||
if (count > 1)
|
||||
{
|
||||
auto expected = original;
|
||||
expected.SetItemCount(count - 1);
|
||||
ProtocolCraft::WriteContainer actualBytes, expectedBytes;
|
||||
remaining.Write(actualBytes);
|
||||
expected.Write(expectedBytes);
|
||||
EXPECT_EQ(actualBytes, expectedBytes);
|
||||
}
|
||||
EXPECT_TRUE(RemainingAfterDrop(original, true).IsEmptySlot());
|
||||
EXPECT_EQ(original.GetItemCount(), count);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, DropDistinguishesKnownEmptySlotsFromInventoryReset)
|
||||
{
|
||||
Botcraft::Window window(InventoryType::PlayerInventory);
|
||||
EXPECT_THROW(ReadDropSlot(window, 36), std::runtime_error);
|
||||
window.SetSlot(36, ProtocolCraft::Slot());
|
||||
EXPECT_TRUE(ReadDropSlot(window, 36).IsEmptySlot());
|
||||
ProtocolCraft::Slot stack;
|
||||
stack.SetItemId(1);
|
||||
stack.SetItemCount(4);
|
||||
window.SetSlot(36, stack);
|
||||
EXPECT_EQ(ReadDropSlot(window, 36).GetItemCount(), 4);
|
||||
window.Init(); // Clears the contents but preserves window identity.
|
||||
EXPECT_THROW(ReadDropSlot(window, 36), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, OfflineFailureIncludesSourceAndLine)
|
||||
{
|
||||
BilicraftClient client;
|
||||
ActionCommand command{};
|
||||
command.kind = ActionKind::SendCommand;
|
||||
command.text = "/help";
|
||||
command.source = "offline.act";
|
||||
command.line = 42;
|
||||
try
|
||||
{
|
||||
ExecuteAction(client, command);
|
||||
FAIL() << "Offline execution should fail before sending a packet";
|
||||
}
|
||||
catch (const std::runtime_error &error)
|
||||
{
|
||||
EXPECT_NE(std::string(error.what()).find("offline.act:42:"), std::string::npos);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, ValidatesWorldAndPackedCoordinateBounds)
|
||||
{
|
||||
EXPECT_NO_THROW(ValidateActionPosition(-29999984, -2048, 29999984));
|
||||
EXPECT_NO_THROW(ValidateActionPosition(29999984, 2047, -29999984));
|
||||
EXPECT_THROW(ValidateActionPosition(29999985, 0, 0), std::runtime_error);
|
||||
EXPECT_THROW(ValidateActionPosition(0, -2049, 0), std::runtime_error);
|
||||
EXPECT_THROW(ValidateActionPosition(0, 2048, 0), std::runtime_error);
|
||||
EXPECT_THROW(ValidateActionPosition(0, 0, INT_MIN), std::runtime_error);
|
||||
EXPECT_THROW(ValidateActionPosition(INT_MAX, 0, 0), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, MaintainingInputsWithoutShiftDoesNotRequirePlayer)
|
||||
{
|
||||
BilicraftClient client;
|
||||
EXPECT_NO_THROW(MaintainActionInputs(client));
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, ItemOnlyClicksNeverAttackKnownEmptyFrames)
|
||||
{
|
||||
EXPECT_EQ(PlanFrameAttack(false, false, false), FrameAttackIntent::None);
|
||||
EXPECT_EQ(PlanFrameAttack(false, false, true), FrameAttackIntent::None);
|
||||
EXPECT_EQ(PlanFrameAttack(false, true, false), FrameAttackIntent::TakeItem);
|
||||
EXPECT_THROW(PlanFrameAttack(false, true, true), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, ExplicitFrameRemovalPlansOnlyTheNecessaryPhases)
|
||||
{
|
||||
for (bool creative : {false, true})
|
||||
{
|
||||
EXPECT_EQ(PlanFrameAttack(true, false, creative), FrameAttackIntent::RemoveFrame);
|
||||
EXPECT_EQ(PlanFrameAttack(true, true, creative), FrameAttackIntent::TakeItem);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, ChangedFrameContentsCannotTurnTakeItemIntoAnExtraRemovalAttack)
|
||||
{
|
||||
EXPECT_NO_THROW(ValidateFrameAttack(FrameAttackIntent::TakeItem, true, true, false));
|
||||
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::TakeItem, true, false, false), std::runtime_error);
|
||||
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::TakeItem, false, false, false), std::runtime_error);
|
||||
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::TakeItem, false, true, true), std::runtime_error);
|
||||
EXPECT_NO_THROW(ValidateFrameAttack(FrameAttackIntent::RemoveFrame, true, false, false));
|
||||
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::RemoveFrame, true, true, false), std::runtime_error);
|
||||
EXPECT_THROW(ValidateFrameAttack(FrameAttackIntent::None, false, false, false), std::runtime_error);
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,849 @@
|
||||
#include "ActionFile.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
namespace fs = std::filesystem;
|
||||
using Bilicraft::ActionKind;
|
||||
using Bilicraft::EntityFace;
|
||||
using Bilicraft::LoadActionFile;
|
||||
using Bilicraft::ParseInteractiveCommand;
|
||||
|
||||
void RejectInteractive(std::string_view text, std::string_view reason = {})
|
||||
{
|
||||
try
|
||||
{
|
||||
(void)ParseInteractiveCommand(text);
|
||||
FAIL() << "Expected console rejection for: " << text;
|
||||
}
|
||||
catch (const std::runtime_error &error)
|
||||
{
|
||||
const std::string message = error.what();
|
||||
EXPECT_TRUE(message.starts_with("<console>:1:")) << message;
|
||||
EXPECT_NE(message.find(reason), std::string::npos) << message;
|
||||
}
|
||||
}
|
||||
|
||||
class ActionFileTest : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
fs::path base;
|
||||
fs::path directory;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
// CMake compiles this source with an absolute path. Standalone builds
|
||||
// should likewise pass its absolute path, or run from the source root.
|
||||
const auto source = fs::absolute(fs::path(__FILE__)).lexically_normal();
|
||||
ASSERT_TRUE(fs::is_regular_file(source));
|
||||
const auto build = source.parent_path().parent_path() / "build";
|
||||
fs::create_directories(build);
|
||||
base = fs::canonical(build);
|
||||
ASSERT_EQ(base.parent_path(), fs::canonical(source.parent_path().parent_path()));
|
||||
static std::atomic<unsigned long> sequence{0};
|
||||
const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
|
||||
for (unsigned attempt = 0; attempt < 100; ++attempt)
|
||||
{
|
||||
const auto candidate =
|
||||
base / ("action-file-tests-" + std::to_string(stamp) + "-" + std::to_string(sequence++));
|
||||
if (fs::create_directory(candidate))
|
||||
{
|
||||
directory = fs::canonical(candidate);
|
||||
return;
|
||||
}
|
||||
}
|
||||
FAIL() << "Unable to allocate unique test directory under " << base;
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
if (directory.empty())
|
||||
return;
|
||||
std::error_code ec;
|
||||
const auto resolved = fs::canonical(directory, ec);
|
||||
// Verify the exact absolute deletion target remains our own directory.
|
||||
ASSERT_FALSE(ec);
|
||||
ASSERT_EQ(resolved, directory);
|
||||
ASSERT_EQ(resolved.parent_path(), base);
|
||||
ASSERT_TRUE(resolved.filename().string().starts_with("action-file-tests-"));
|
||||
fs::remove_all(resolved, ec);
|
||||
EXPECT_FALSE(ec);
|
||||
}
|
||||
|
||||
fs::path Write(std::string_view filename, std::string_view contents)
|
||||
{
|
||||
const auto path = directory / std::string(filename);
|
||||
std::ofstream out(path, std::ios::binary);
|
||||
if (!out || !out.write(contents.data(), static_cast<std::streamsize>(contents.size())))
|
||||
throw std::runtime_error("Unable to write test file: " + path.string());
|
||||
return path;
|
||||
}
|
||||
|
||||
Bilicraft::ActionProgram Parse(std::string_view contents)
|
||||
{
|
||||
return LoadActionFile(Write("test.act", contents));
|
||||
}
|
||||
|
||||
void Reject(std::string_view contents, std::string_view reason = {}, std::size_t line = 2)
|
||||
{
|
||||
const auto path = Write("test.act", contents);
|
||||
try
|
||||
{
|
||||
(void)LoadActionFile(path);
|
||||
FAIL() << "Expected rejection for: " << contents;
|
||||
}
|
||||
catch (const std::runtime_error &error)
|
||||
{
|
||||
const std::string message = error.what();
|
||||
EXPECT_NE(message.find(path.string() + ":" + std::to_string(line) + ":"), std::string::npos) << message;
|
||||
EXPECT_NE(message.find(reason), std::string::npos) << message;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(ActionFileTest, ParsesEveryInstructionAndStoresSourceLocations)
|
||||
{
|
||||
const auto program = Parse("# action: farming\n"
|
||||
"goto -1 +2 3\nrclick 4 5 6 shift\nlclick 7 8 9 shift destory\n"
|
||||
"grclick 2 9\nglclick 4 1\nsw 9\nswb 3 8 2\n"
|
||||
"sendcmd /say hello world\nsendmsg hello everyone\nsendmsg @Farmer hello friend\n");
|
||||
EXPECT_EQ(program.name, "farming");
|
||||
ASSERT_EQ(program.commands.size(), 10U);
|
||||
const auto &c = program.commands;
|
||||
EXPECT_EQ(c[0].kind, ActionKind::Goto);
|
||||
EXPECT_EQ(c[0].x, -1);
|
||||
EXPECT_EQ(c[0].y, 2);
|
||||
EXPECT_EQ(c[0].z, 3);
|
||||
EXPECT_EQ(c[1].kind, ActionKind::RightClick);
|
||||
EXPECT_TRUE(c[1].shift);
|
||||
EXPECT_FALSE(c[1].destroy);
|
||||
EXPECT_EQ(c[2].kind, ActionKind::LeftClick);
|
||||
EXPECT_TRUE(c[2].shift);
|
||||
EXPECT_TRUE(c[2].destroy);
|
||||
EXPECT_EQ(c[3].kind, ActionKind::GuiRightClick);
|
||||
EXPECT_EQ(c[3].row, 2);
|
||||
EXPECT_EQ(c[3].col, 9);
|
||||
EXPECT_EQ(c[4].kind, ActionKind::GuiLeftClick);
|
||||
EXPECT_EQ(c[4].row, 4);
|
||||
EXPECT_EQ(c[4].col, 1);
|
||||
EXPECT_EQ(c[5].kind, ActionKind::SelectHotbar);
|
||||
EXPECT_EQ(c[5].slot, 9);
|
||||
EXPECT_EQ(c[6].kind, ActionKind::SwapBackpack);
|
||||
EXPECT_EQ(c[6].row, 3);
|
||||
EXPECT_EQ(c[6].col, 8);
|
||||
EXPECT_EQ(c[6].slot, 2);
|
||||
EXPECT_EQ(c[7].kind, ActionKind::SendCommand);
|
||||
EXPECT_EQ(c[7].text, "/say hello world");
|
||||
EXPECT_EQ(c[8].kind, ActionKind::SendMessage);
|
||||
EXPECT_EQ(c[8].text, "hello everyone");
|
||||
EXPECT_TRUE(c[8].recipient.empty());
|
||||
EXPECT_EQ(c[9].text, "hello friend");
|
||||
EXPECT_EQ(c[9].recipient, "Farmer");
|
||||
for (std::size_t i = 0; i < c.size(); ++i)
|
||||
{
|
||||
EXPECT_FALSE(c[i].entity);
|
||||
EXPECT_EQ(c[i].entityFace, EntityFace::Any);
|
||||
EXPECT_EQ(c[i].source, directory / "test.act");
|
||||
EXPECT_EQ(c[i].line, i + 2);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, ParsesDropCurrentOrExplicitSlotAndOptionalAll)
|
||||
{
|
||||
const auto program = Parse("# action: dropping\ndrop\ndrop 1\ndrop 9\ndrop all\n"
|
||||
"drop 3 all # entire stack\ndrop all 5\n");
|
||||
ASSERT_EQ(program.commands.size(), 6U);
|
||||
const int slots[] = {0, 1, 9, 0, 3, 5};
|
||||
for (std::size_t i = 0; i < program.commands.size(); ++i)
|
||||
{
|
||||
EXPECT_EQ(program.commands[i].kind, ActionKind::Drop);
|
||||
EXPECT_EQ(program.commands[i].slot, slots[i]);
|
||||
EXPECT_EQ(program.commands[i].all, i >= 3);
|
||||
EXPECT_EQ(program.commands[i].line, i + 2);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsInvalidDropSlotsFlagsAndExtraArguments)
|
||||
{
|
||||
for (const auto command :
|
||||
{"drop 0", "drop -1", "drop 10", "drop 2147483648", "drop 1.5", "drop ALL", "drop shift", "drop ?all",
|
||||
"drop all all", "drop 1 2", "drop 1 all all", "drop all 0", "drop all 1 2", "drop 1 unknown"})
|
||||
{
|
||||
SCOPED_TRACE(command);
|
||||
Reject("# action: test\n" + std::string(command));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, DropKeepsCurrentSlotUnresolvedAcrossImports)
|
||||
{
|
||||
Write("child.act", "# action: child\ndrop all\n");
|
||||
const auto program = Parse("# action: parent\nsw 9\nimport child\ndrop 2\n");
|
||||
ASSERT_EQ(program.commands.size(), 3U);
|
||||
EXPECT_EQ(program.commands[1].kind, ActionKind::Drop);
|
||||
EXPECT_EQ(program.commands[1].slot, 0); // Resolve at execution, after sw 9.
|
||||
EXPECT_TRUE(program.commands[1].all);
|
||||
EXPECT_EQ(program.commands[1].source, directory / "child.act");
|
||||
EXPECT_EQ(program.commands[2].slot, 2);
|
||||
EXPECT_FALSE(program.commands[2].all);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, HandlesBomCrLfWhitespaceAndInlineComments)
|
||||
{
|
||||
const auto program = Parse("\xEF\xBB\xBF # ordinary comment\r\n\r\n # action: example # note\r\n"
|
||||
"\t goto\t1 2 3 # comment\r\n sendmsg hello # removed\r\n# trailing\r\n");
|
||||
EXPECT_EQ(program.name, "example");
|
||||
ASSERT_EQ(program.commands.size(), 2U);
|
||||
EXPECT_EQ(program.commands[0].line, 4U);
|
||||
EXPECT_EQ(program.commands[1].text, "hello");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, AllowsHeaderOnlyAndNoFinalNewline)
|
||||
{
|
||||
EXPECT_TRUE(Parse("# action: empty").commands.empty());
|
||||
EXPECT_EQ(Parse("# action: test\nsw 1").commands.size(), 1U);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, SupportsDestroyAliasAndEitherFlagOrder)
|
||||
{
|
||||
const auto program = Parse("# action: test\nlclick 1 2 3 destroy shift\nlclick 1 2 3 destory\n"
|
||||
"lclick 1 2 3 shift\nlclick 1 2 3\nrclick 1 2 3\n");
|
||||
ASSERT_EQ(program.commands.size(), 5U);
|
||||
EXPECT_TRUE(program.commands[0].shift);
|
||||
EXPECT_TRUE(program.commands[0].destroy);
|
||||
EXPECT_TRUE(program.commands[1].destroy);
|
||||
EXPECT_FALSE(program.commands[1].shift);
|
||||
EXPECT_TRUE(program.commands[2].shift);
|
||||
EXPECT_FALSE(program.commands[2].destroy);
|
||||
EXPECT_FALSE(program.commands[3].shift);
|
||||
EXPECT_FALSE(program.commands[3].destroy);
|
||||
EXPECT_FALSE(program.commands[4].shift);
|
||||
for (const auto &command : program.commands)
|
||||
{
|
||||
EXPECT_FALSE(command.entity);
|
||||
EXPECT_EQ(command.entityFace, EntityFace::Any);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, ParsesAllEntryFacesWithShortAndFullNamesInFilesAndConsole)
|
||||
{
|
||||
const struct
|
||||
{
|
||||
const char *shortName;
|
||||
const char *fullName;
|
||||
EntityFace face;
|
||||
} faces[] = {{"t", "top", EntityFace::Top}, {"b", "bottom", EntityFace::Bottom},
|
||||
{"s", "south", EntityFace::South}, {"n", "north", EntityFace::North},
|
||||
{"w", "west", EntityFace::West}, {"e", "east", EntityFace::East}};
|
||||
for (const auto verb : {"rclick", "lclick"})
|
||||
{
|
||||
for (const auto &face : faces)
|
||||
{
|
||||
for (const auto token : {face.shortName, face.fullName})
|
||||
{
|
||||
const auto text = std::string(verb) + " -1 +2 3 entry " + token + " # frame";
|
||||
SCOPED_TRACE(text);
|
||||
const auto program = Parse("# action: test\n" + text);
|
||||
ASSERT_EQ(program.commands.size(), 1U);
|
||||
const auto interactive = ParseInteractiveCommand(text);
|
||||
ASSERT_TRUE(interactive.has_value());
|
||||
const auto &file = program.commands[0];
|
||||
for (const auto *command : {&file, &*interactive})
|
||||
{
|
||||
EXPECT_EQ(command->kind,
|
||||
std::string_view(verb) == "rclick" ? ActionKind::RightClick : ActionKind::LeftClick);
|
||||
EXPECT_EQ(command->x, -1);
|
||||
EXPECT_EQ(command->y, 2);
|
||||
EXPECT_EQ(command->z, 3);
|
||||
EXPECT_TRUE(command->entity);
|
||||
EXPECT_EQ(command->entityFace, face.face);
|
||||
EXPECT_FALSE(command->shift);
|
||||
EXPECT_FALSE(command->destroy);
|
||||
}
|
||||
EXPECT_EQ(file.source, directory / "test.act");
|
||||
EXPECT_EQ(file.line, 2U);
|
||||
EXPECT_EQ(interactive->source, fs::path("<console>"));
|
||||
EXPECT_EQ(interactive->line, 1U);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, EntryAllowsOmittedFaceAndEveryLegacyFlagOrder)
|
||||
{
|
||||
// Treat entry [face] as one flag group: it may precede, follow or sit
|
||||
// between the legacy flags, but the face itself cannot move independently.
|
||||
for (const auto entry : {"entry", "entry n", "entry north"})
|
||||
{
|
||||
for (const auto verb : {"rclick", "lclick"})
|
||||
{
|
||||
for (const auto suffix : {std::string(entry), std::string(entry) + " shift", "shift " + std::string(entry)})
|
||||
{
|
||||
const auto text = std::string(verb) + " 1 2 3 " + suffix;
|
||||
SCOPED_TRACE(text);
|
||||
const auto program = Parse("# action: test\n" + text);
|
||||
ASSERT_EQ(program.commands.size(), 1U);
|
||||
const auto interactive = ParseInteractiveCommand(text);
|
||||
ASSERT_TRUE(interactive.has_value());
|
||||
for (const auto *command : {&program.commands[0], &*interactive})
|
||||
{
|
||||
EXPECT_TRUE(command->entity);
|
||||
EXPECT_EQ(command->entityFace,
|
||||
std::string_view(entry) == "entry" ? EntityFace::Any : EntityFace::North);
|
||||
EXPECT_EQ(command->shift, suffix.find("shift") != std::string::npos);
|
||||
EXPECT_FALSE(command->destroy);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto destroy : {"destory", "destroy"})
|
||||
{
|
||||
const std::string e = entry, d = destroy;
|
||||
for (const auto &suffix :
|
||||
{e + " " + d, d + " " + e, e + " shift " + d, e + " " + d + " shift", "shift " + e + " " + d,
|
||||
"shift " + d + " " + e, d + " " + e + " shift", d + " shift " + e})
|
||||
{
|
||||
const auto text = "lclick 1 2 3 " + suffix;
|
||||
SCOPED_TRACE(text);
|
||||
const auto program = Parse("# action: test\n" + text);
|
||||
ASSERT_EQ(program.commands.size(), 1U);
|
||||
const auto interactive = ParseInteractiveCommand(text);
|
||||
ASSERT_TRUE(interactive.has_value());
|
||||
for (const auto *command : {&program.commands[0], &*interactive})
|
||||
{
|
||||
EXPECT_TRUE(command->entity);
|
||||
EXPECT_EQ(command->entityFace, e == "entry" ? EntityFace::Any : EntityFace::North);
|
||||
EXPECT_EQ(command->shift, suffix.find("shift") != std::string::npos);
|
||||
EXPECT_TRUE(command->destroy);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsInvalidEntryFacesFlagsAndOrderingInFilesAndConsole)
|
||||
{
|
||||
for (const auto text : {"rclick 1 2 3 entry entry",
|
||||
"lclick 1 2 3 entry n entry",
|
||||
"lclick 1 2 3 entry entry n",
|
||||
"rclick 1 2 3 entry n n",
|
||||
"lclick 1 2 3 entry n north",
|
||||
"lclick 1 2 3 entry n s",
|
||||
"rclick 1 2 3 n entry",
|
||||
"lclick 1 2 3 north entry",
|
||||
"rclick 1 2 3 entry shift n",
|
||||
"lclick 1 2 3 entry destroy n",
|
||||
"lclick 1 2 3 entry destory north",
|
||||
"lclick 1 2 3 entry n shift e",
|
||||
"rclick 1 2 3 n",
|
||||
"lclick 1 2 3 top",
|
||||
"rclick 1 2 3 shift n",
|
||||
"rclick 1 2 3 entry any",
|
||||
"lclick 1 2 3 entry unknown",
|
||||
"rclick 1 2 3 ENTRY",
|
||||
"rclick 1 2 3 entry N",
|
||||
"lclick 1 2 3 entry North",
|
||||
"rclick 1 2 3 entry shift shift",
|
||||
"lclick 1 2 3 entry n shift shift",
|
||||
"lclick 1 2 3 entry destroy destroy",
|
||||
"lclick 1 2 3 entry destory destroy",
|
||||
"lclick 1 2 3 entry destroy destory",
|
||||
"lclick 1 2 3 entry destory destory",
|
||||
"rclick 1 2 3 entry destroy",
|
||||
"rclick 1 2 3 entry n destory",
|
||||
"rclick 1 2 3 destroy entry",
|
||||
"rclick 1 2 3 destory entry n",
|
||||
"goto 1 2 3 entry",
|
||||
"goto 1 2 3 entry n",
|
||||
"goto 1 2 3 n",
|
||||
"grclick 1 2 entry",
|
||||
"glclick 1 2 entry",
|
||||
"sw 1 entry",
|
||||
"swb 1 2 3 entry",
|
||||
"drop entry",
|
||||
"rclick entry 1 2 3",
|
||||
"lclick 1 2 entry",
|
||||
"lclick 1 2 3 entry n shift destroy extra"})
|
||||
{
|
||||
SCOPED_TRACE(text);
|
||||
Reject("# action: test\n" + std::string(text));
|
||||
RejectInteractive(text);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, AcceptsIntegerAndSlotBoundaries)
|
||||
{
|
||||
const auto program = Parse("# action: bounds\ngoto -2147483648 2147483647 -0\n"
|
||||
"grclick 2147483647 9\nglclick 1 1\nsw 1\nsw 9\nswb 1 1 1\nswb 3 9 9\n");
|
||||
ASSERT_EQ(program.commands.size(), 7U);
|
||||
EXPECT_EQ(program.commands[0].x, std::numeric_limits<int>::min());
|
||||
EXPECT_EQ(program.commands[0].y, std::numeric_limits<int>::max());
|
||||
EXPECT_EQ(program.commands[1].row, std::numeric_limits<int>::max());
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, PreservesUtf8NamesAndMessageText)
|
||||
{
|
||||
const auto program = Parse("# action: 种田\nsendmsg @玩家 你好 世界\n");
|
||||
EXPECT_EQ(program.name, "种田");
|
||||
ASSERT_EQ(program.commands.size(), 1U);
|
||||
EXPECT_EQ(program.commands[0].recipient, "玩家");
|
||||
EXPECT_EQ(program.commands[0].text, "你好 世界");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsMissingHeader)
|
||||
{
|
||||
Reject("", "missing action header", 1);
|
||||
Reject("# ordinary comment", "missing action header", 1);
|
||||
Reject("goto 1 2 3\n# action: late\n", "before first instruction", 1);
|
||||
Reject("import child\n# action: late\n", "before first instruction", 1);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsDuplicateHeaders)
|
||||
{
|
||||
Reject("# action: test\n# action: test\n", "duplicate");
|
||||
Reject("# action: test\nsw 1\n# action: other\n", "duplicate", 3);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsEmptyAndUnsafeHeaderNames)
|
||||
{
|
||||
for (const auto name :
|
||||
{"", " ", ".", "..", "../evil", "dir/name", "dir\\name", "C:evil", "a b", "a.", "a*", "name.act"})
|
||||
{
|
||||
SCOPED_TRACE(name);
|
||||
Reject("# action: " + std::string(name), "simple filename", 1);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsInvalidIntegers)
|
||||
{
|
||||
for (const auto value : {"1.0", "1x", "0x10", "2147483648", "-2147483649", "+", "-", "+-1", "--1", "++1", "1e2"})
|
||||
{
|
||||
SCOPED_TRACE(value);
|
||||
Reject("# action: test\ngoto " + std::string(value) + " 2 3\n", "integer");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsIncorrectArgumentCounts)
|
||||
{
|
||||
for (const auto command : {"goto", "goto 1 2", "goto 1 2 3 4", "rclick 1 2", "rclick 1 2 3 shift shift",
|
||||
"lclick 1 2", "lclick 1 2 3 shift destory extra", "grclick 1", "grclick 1 2 3",
|
||||
"glclick 1", "glclick 1 2 3", "sw", "sw 1 2", "swb 1 2", "swb 1 2 3 4"})
|
||||
{
|
||||
SCOPED_TRACE(command);
|
||||
Reject("# action: test\n" + std::string(command));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsUnknownAndDuplicateFlags)
|
||||
{
|
||||
for (const auto command : {"rclick 1 2 3 destory", "rclick 1 2 3 SHIFT", "rclick 1 2 3 unknown",
|
||||
"lclick 1 2 3 shift shift", "lclick 1 2 3 destroy destory",
|
||||
"lclick 1 2 3 destory destory", "lclick 1 2 3 nope", "lclick 1 2 3 destory nope"})
|
||||
{
|
||||
SCOPED_TRACE(command);
|
||||
Reject("# action: test\n" + std::string(command), "unknown or duplicate flag");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsInvalidGuiBackpackAndHotbarRanges)
|
||||
{
|
||||
for (const auto command :
|
||||
{"grclick 0 1", "grclick -1 1", "grclick 1 0", "grclick 1 10", "glclick 0 1", "glclick 1 10", "sw 0", "sw 10",
|
||||
"sw -1", "swb 0 1 1", "swb 4 1 1", "swb 1 0 1", "swb 1 10 1", "swb 1 1 0", "swb 1 1 10"})
|
||||
{
|
||||
SCOPED_TRACE(command);
|
||||
Reject("# action: test\n" + std::string(command));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsEmptyTextAndMissingRecipientMessages)
|
||||
{
|
||||
for (const auto command : {"sendcmd", "sendcmd # comment", "sendcmd /", "sendcmd / ", "sendcmd / # comment",
|
||||
"sendmsg", "sendmsg @Player", "sendmsg @Player # comment", "sendmsg @ hello"})
|
||||
{
|
||||
SCOPED_TRACE(command);
|
||||
Reject("# action: test\n" + std::string(command));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsUnknownInstructionsAndEmbeddedNul)
|
||||
{
|
||||
Reject("# action: test\nunknown 1 2 3", "unknown instruction");
|
||||
const std::string input = std::string("# action: test\nsendmsg hi") + '\0' + "hidden";
|
||||
Reject(input, "NUL");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, ExpandsNestedAndRepeatedImportsInExactOrder)
|
||||
{
|
||||
Write("leaf.act", "# action: leaf\nsendmsg leaf\n");
|
||||
Write("child.act", "# action: child\nsendmsg child-before\nimport leaf\nsendmsg child-after\n");
|
||||
const auto program =
|
||||
Parse("# action: root\nsendmsg before\nimport child\nsendmsg middle\nimport child\nsendmsg after\n");
|
||||
EXPECT_EQ(program.name, "root");
|
||||
ASSERT_EQ(program.commands.size(), 9U);
|
||||
const std::string expected[] = {"before", "child-before", "leaf", "child-after", "middle",
|
||||
"child-before", "leaf", "child-after", "after"};
|
||||
for (std::size_t i = 0; i < 9; ++i)
|
||||
EXPECT_EQ(program.commands[i].text, expected[i]);
|
||||
EXPECT_EQ(program.commands[2].source, directory / "leaf.act");
|
||||
EXPECT_EQ(program.commands[2].line, 2U);
|
||||
EXPECT_EQ(program.commands[3].source, directory / "child.act");
|
||||
EXPECT_EQ(program.commands[3].line, 4U);
|
||||
EXPECT_EQ(program.commands[8].source, directory / "test.act");
|
||||
EXPECT_EQ(program.commands[8].line, 6U);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, AllowsEmptyImports)
|
||||
{
|
||||
Write("empty.act", "# action: empty\n");
|
||||
EXPECT_TRUE(Parse("# action: root\nimport empty\nimport empty\n").commands.empty());
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsMissingImportWithImportSite)
|
||||
{
|
||||
Reject("# action: root\nimport missing\n", "cannot import 'missing'");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsImportHeaderMismatchWithBothLocations)
|
||||
{
|
||||
const auto child = Write("child.act", "# action: different\n");
|
||||
Reject("# action: root\nimport child\n", child.string() + ":1:");
|
||||
Reject("# action: root\nimport child\n", "does not match imported name");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, ReportsImportedSyntaxErrorWithBothLocations)
|
||||
{
|
||||
const auto child = Write("child.act", "# action: child\nsw 99\n");
|
||||
Reject("# action: root\nimport child\n", child.string() + ":2:");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsDirectAndIndirectCycles)
|
||||
{
|
||||
Reject("# action: test\nimport test\n", "cyclic import");
|
||||
Write("child.act", "# action: child\nimport test\n");
|
||||
Reject("# action: test\nimport child\n", "cyclic import");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsUnsafeImportPathsAndArity)
|
||||
{
|
||||
for (const auto name : {"", "../child", "./child", "/child", "folder/child", "folder\\child", "C:child", ".", "..",
|
||||
"child extra", "child.act"})
|
||||
{
|
||||
SCOPED_TRACE(name);
|
||||
Reject("# action: test\nimport " + std::string(name), "one simple action name");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsSymlinkImportEscapingDirectory)
|
||||
{
|
||||
fs::create_directory(directory / "outside");
|
||||
const auto outside = Write("outside/child.act", "# action: child\nsw 1\n");
|
||||
std::error_code ec;
|
||||
fs::create_symlink(outside, directory / "child.act", ec);
|
||||
if (ec)
|
||||
GTEST_SKIP() << "Symlinks unavailable: " << ec.message();
|
||||
Reject("# action: test\nimport child\n", "escapes");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsMissingAndNonregularRootFiles)
|
||||
{
|
||||
EXPECT_THROW(LoadActionFile(directory / "missing.act"), std::runtime_error);
|
||||
fs::create_directory(directory / "folder.act");
|
||||
EXPECT_THROW(LoadActionFile(directory / "folder.act"), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsEntryFilesWithoutActExtension)
|
||||
{
|
||||
for (const auto name : {"plain", "test.txt", "test.ACT", "test.act.bak"})
|
||||
{
|
||||
const auto path = Write(name, "# action: test\n");
|
||||
try
|
||||
{
|
||||
(void)LoadActionFile(path);
|
||||
FAIL() << "Accepted unsupported extension: " << name;
|
||||
}
|
||||
catch (const std::runtime_error &error)
|
||||
{
|
||||
const std::string message = error.what();
|
||||
EXPECT_NE(message.find(path.string() + ":1:"), std::string::npos);
|
||||
EXPECT_NE(message.find(".act extension"), std::string::npos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, PreservesCommandsWithOrWithoutLeadingSlash)
|
||||
{
|
||||
const auto program = Parse("# action: test\nsendcmd /say hi there\nsendcmd say hi there\n");
|
||||
ASSERT_EQ(program.commands.size(), 2U);
|
||||
EXPECT_EQ(program.commands[0].text, "/say hi there");
|
||||
EXPECT_EQ(program.commands[1].text, "say hi there");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, ParsesWaitDefaultUnitEveryUnitAndZero)
|
||||
{
|
||||
const auto program = Parse("# action: waits\nwait 2\nwait 2 s\nwait 2 ms\nwait 2 min\nwait 2 h\nwait 2 d\n"
|
||||
"wait 0\nwait 0 s\nwait 0 ms\nwait 0 min\nwait 0 h\nwait 0 d\n");
|
||||
const std::chrono::milliseconds::rep expected[] = {2000, 2000, 2, 120000, 7200000, 172800000, 0, 0, 0, 0, 0, 0};
|
||||
ASSERT_EQ(program.commands.size(), std::size(expected));
|
||||
for (std::size_t i = 0; i < program.commands.size(); ++i)
|
||||
{
|
||||
EXPECT_EQ(program.commands[i].kind, ActionKind::Wait);
|
||||
EXPECT_EQ(program.commands[i].waitDuration.count(), expected[i]);
|
||||
EXPECT_EQ(program.commands[i].source, directory / "test.act");
|
||||
EXPECT_EQ(program.commands[i].line, i + 2);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, ParsesExactWaitFractionsWithoutRounding)
|
||||
{
|
||||
const auto program = Parse("# action: waits\nwait 0.001\nwait 1.125 s\nwait 1.000 ms\nwait 0.00005 min\n"
|
||||
"wait 0.000005 h\nwait 0.0000003125 d\nwait 0002.500000 s\n"
|
||||
"wait 0.0000000000000000000000000 ms\nwait 0.1230000000000000000000000 s\n");
|
||||
const std::chrono::milliseconds::rep expected[] = {1, 1125, 1, 3, 18, 27, 2500, 0, 123};
|
||||
ASSERT_EQ(program.commands.size(), std::size(expected));
|
||||
for (std::size_t i = 0; i < program.commands.size(); ++i)
|
||||
EXPECT_EQ(program.commands[i].waitDuration.count(), expected[i]);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, AcceptsWaitLimitInEveryUnitAndRejectsOverflow)
|
||||
{
|
||||
for (const auto duration : {"31536000", "31536000 s", "31536000000 ms", "525600 min", "8760 h", "365 d",
|
||||
"365.000000000000000000000000000000 d"})
|
||||
{
|
||||
SCOPED_TRACE(duration);
|
||||
const auto program = Parse("# action: waits\nwait " + std::string(duration));
|
||||
ASSERT_EQ(program.commands.size(), 1U);
|
||||
EXPECT_EQ(program.commands[0].waitDuration.count(), 31536000000LL);
|
||||
}
|
||||
for (const auto duration :
|
||||
{"31536000.001", "31536000.001 s", "31536000001 ms", "525600.00005 min", "8760.000005 h", "365.0000003125 d",
|
||||
"366 d", "999999999999999999999999999999999999 s", "18446744073709551616 ms", "9223372036854775808 d"})
|
||||
{
|
||||
SCOPED_TRACE(duration);
|
||||
Reject("# action: waits\nwait " + std::string(duration), "365 days");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsSubMillisecondWaitFractions)
|
||||
{
|
||||
for (const auto duration : {"0.0001", "0.0001 s", "0.5 ms", "0.00001 min", "0.0000001 h", "0.000000001 d",
|
||||
"0.000000000000000000000000000000000001 s", "1.0000000000000000000000001 ms"})
|
||||
{
|
||||
SCOPED_TRACE(duration);
|
||||
Reject("# action: waits\nwait " + std::string(duration), "whole number of milliseconds");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, RejectsInvalidWaitNumbersUnitsAndArgumentCounts)
|
||||
{
|
||||
for (const auto command :
|
||||
{"wait", "wait s", "wait -1", "wait -0", "wait +1", "wait NaN", "wait nan",
|
||||
"wait Inf", "wait inf", "wait infinity", "wait 1e3", "wait 1E3", "wait 0x10", "wait 1,5",
|
||||
"wait .", "wait .5", "wait 1.", "wait 1.2.3", "wait 1s", "wait 1 S", "wait 1 m",
|
||||
"wait 1 sec", "wait 1 seconds", "wait 1 unknown", "wait 1 ms extra", "wait 1 2 3", "wait 1 s ms"})
|
||||
{
|
||||
SCOPED_TRACE(command);
|
||||
Reject("# action: waits\n" + std::string(command));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, KeepsWaitImportOrderingLocationsAndErrorContext)
|
||||
{
|
||||
const auto child = Write("child.act", "# action: child\nwait 0.125 s\n");
|
||||
const auto program = Parse("# action: parent\nwait 0\nimport child\nsendmsg still here\nwait 2 ms # pause\n");
|
||||
ASSERT_EQ(program.commands.size(), 4U);
|
||||
EXPECT_EQ(program.commands[0].waitDuration.count(), 0);
|
||||
EXPECT_EQ(program.commands[1].kind, ActionKind::Wait);
|
||||
EXPECT_EQ(program.commands[1].waitDuration.count(), 125);
|
||||
EXPECT_EQ(program.commands[1].source, child);
|
||||
EXPECT_EQ(program.commands[1].line, 2U);
|
||||
EXPECT_EQ(program.commands[2].text, "still here");
|
||||
EXPECT_EQ(program.commands[3].waitDuration.count(), 2);
|
||||
Write("child.act", "# action: child\nwait 366 d\n");
|
||||
Reject("# action: parent\nimport child\n", child.string() + ":2:");
|
||||
}
|
||||
|
||||
TEST(InteractiveCommandTest, BlankAndCommentLinesHaveNoCommand)
|
||||
{
|
||||
for (const auto text : {"", " ", "\t", "# comment", " \t# action: not-a-file", "# wait 1", "# import child"})
|
||||
EXPECT_FALSE(ParseInteractiveCommand(text).has_value()) << text;
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, InteractiveCommandsReuseEveryGameInstructionAndFlag)
|
||||
{
|
||||
for (const auto text : {"goto -1 +2 3",
|
||||
"rclick 1 2 3",
|
||||
"rclick 1 2 3 shift",
|
||||
"lclick 1 2 3",
|
||||
"lclick 1 2 3 destroy shift",
|
||||
"lclick 1 2 3 shift destory",
|
||||
"lclick 1 2 3 destory shift",
|
||||
"lclick 1 2 3 shift destroy",
|
||||
"rclick 1 2 3 entry",
|
||||
"rclick 1 2 3 entry t shift",
|
||||
"rclick 1 2 3 shift entry bottom",
|
||||
"lclick 1 2 3 entry",
|
||||
"lclick 1 2 3 entry south",
|
||||
"lclick 1 2 3 entry n shift destroy",
|
||||
"lclick 1 2 3 shift entry w destory",
|
||||
"lclick 1 2 3 destory shift entry east",
|
||||
"lclick 1 2 3 destroy entry shift",
|
||||
"grclick 2 9",
|
||||
"glclick 4 1",
|
||||
"sw 9",
|
||||
"swb 3 8 2",
|
||||
"drop",
|
||||
"drop all",
|
||||
"drop 3",
|
||||
"drop 3 all",
|
||||
"drop all 3",
|
||||
"sendcmd /say hello world",
|
||||
"sendcmd say hi",
|
||||
"sendmsg hello everyone",
|
||||
"sendmsg @Farmer hello friend",
|
||||
"sendmsg @玩家 你好 世界",
|
||||
"\t sw\t2 # inline comment"})
|
||||
{
|
||||
SCOPED_TRACE(text);
|
||||
const auto interactive = ParseInteractiveCommand(text);
|
||||
ASSERT_TRUE(interactive.has_value());
|
||||
const auto program = Parse("# action: test\n" + std::string(text));
|
||||
ASSERT_EQ(program.commands.size(), 1U);
|
||||
const auto &file = program.commands[0];
|
||||
EXPECT_EQ(interactive->kind, file.kind);
|
||||
EXPECT_EQ(interactive->x, file.x);
|
||||
EXPECT_EQ(interactive->y, file.y);
|
||||
EXPECT_EQ(interactive->z, file.z);
|
||||
EXPECT_EQ(interactive->row, file.row);
|
||||
EXPECT_EQ(interactive->col, file.col);
|
||||
EXPECT_EQ(interactive->slot, file.slot);
|
||||
EXPECT_EQ(interactive->shift, file.shift);
|
||||
EXPECT_EQ(interactive->destroy, file.destroy);
|
||||
EXPECT_EQ(interactive->entity, file.entity);
|
||||
EXPECT_EQ(interactive->entityFace, file.entityFace);
|
||||
EXPECT_EQ(interactive->all, file.all);
|
||||
EXPECT_EQ(interactive->text, file.text);
|
||||
EXPECT_EQ(interactive->recipient, file.recipient);
|
||||
EXPECT_EQ(interactive->waitDuration, std::chrono::milliseconds{0});
|
||||
EXPECT_EQ(interactive->waitDuration, file.waitDuration);
|
||||
EXPECT_EQ(interactive->source, fs::path("<console>"));
|
||||
EXPECT_EQ(interactive->line, 1U);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(InteractiveCommandTest, PreservesMessageTextAndInlineCommentRules)
|
||||
{
|
||||
auto command = ParseInteractiveCommand(" sendmsg @玩家 你好 世界 # hidden");
|
||||
ASSERT_TRUE(command.has_value());
|
||||
EXPECT_EQ(command->recipient, "玩家");
|
||||
EXPECT_EQ(command->text, "你好 世界");
|
||||
command = ParseInteractiveCommand("sendmsg run child.act; wait 1");
|
||||
ASSERT_TRUE(command.has_value());
|
||||
EXPECT_EQ(command->kind, ActionKind::SendMessage);
|
||||
EXPECT_EQ(command->text, "run child.act; wait 1");
|
||||
}
|
||||
|
||||
TEST(InteractiveCommandTest, RejectsWaitAndImportWithRunGuidance)
|
||||
{
|
||||
for (const auto text : {"wait 0", "wait 1 s", "wait", "wait nonsense", "import child", "import ../child", "import"})
|
||||
{
|
||||
SCOPED_TRACE(text);
|
||||
RejectInteractive(text, "run file.act");
|
||||
}
|
||||
}
|
||||
|
||||
TEST(InteractiveCommandTest, RejectsInvalidGameCommandsWithConsoleLocation)
|
||||
{
|
||||
for (const auto text :
|
||||
{"unknown", "goto", "goto 1 2 3 4", "goto 2147483648 1 2", "rclick 1 2 3 destroy", "lclick 1 2 3 shift shift",
|
||||
"grclick 0 1", "glclick 1 10", "sw 0", "swb 4 1 2", "drop all all", "drop 0", "sendcmd", "sendcmd /",
|
||||
"sendmsg", "sendmsg @Player", "sendmsg @ hello", "run file.act", "sw 1; sw 2"})
|
||||
{
|
||||
SCOPED_TRACE(text);
|
||||
RejectInteractive(text);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(InteractiveCommandTest, RejectsNewlineAndNulEvenInsideComments)
|
||||
{
|
||||
for (const auto text : {"\n", "\r", "sw 1\n", "sw 1\r\n", "sw 1\nsw 2", "sendmsg hi\rsw 2", "# comment\nsw 2",
|
||||
"# comment\r", "sendcmd /say hello\n/stop"})
|
||||
{
|
||||
SCOPED_TRACE(text);
|
||||
RejectInteractive(text, "one line");
|
||||
}
|
||||
RejectInteractive(std::string("sendmsg hi") + '\0' + "hidden", "NUL");
|
||||
RejectInteractive(std::string("# comment") + '\0', "NUL");
|
||||
RejectInteractive(std::string(1, '\0'), "NUL");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, EnforcesDepthLimitAndAcceptsBoundary)
|
||||
{
|
||||
for (int i = 0; i < 32; ++i)
|
||||
{
|
||||
std::string body = "# action: depth" + std::to_string(i) + "\n";
|
||||
if (i != 31)
|
||||
body += "import depth" + std::to_string(i + 1) + "\n";
|
||||
Write("depth" + std::to_string(i) + ".act", body);
|
||||
}
|
||||
EXPECT_TRUE(LoadActionFile(directory / "depth0.act").commands.empty());
|
||||
Reject("# action: root\nimport depth0\n", "depth limit");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, EnforcesExpandedCommandLimitAndAcceptsBoundary)
|
||||
{
|
||||
std::string contents = "# action: test\n";
|
||||
for (int i = 0; i < 100000; ++i)
|
||||
contents += "sw 1\n";
|
||||
EXPECT_EQ(Parse(contents).commands.size(), 100000U);
|
||||
contents += "sw 1\n";
|
||||
Reject(contents, "expanded command limit", 100002);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, EnforcesExpandedCommandLimitAcrossImports)
|
||||
{
|
||||
std::string child = "# action: child\n";
|
||||
for (int i = 0; i < 50001; ++i)
|
||||
child += "sw 1\n";
|
||||
Write("child.act", child);
|
||||
Reject("# action: root\nimport child\nimport child\n", "expanded command limit", 3);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, EnforcesIndividualFileSizeLimit)
|
||||
{
|
||||
std::string contents = "# action: test\n#";
|
||||
contents.resize(1024 * 1024, 'x');
|
||||
EXPECT_TRUE(Parse(contents).commands.empty());
|
||||
contents += 'x';
|
||||
Reject(contents, "file size limit", 1);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, EnforcesTotalInputSizeLimit)
|
||||
{
|
||||
std::string child = "# action: child\n#";
|
||||
child.resize(1024 * 1024, 'x');
|
||||
Write("child.act", child);
|
||||
std::string contents = "# action: root\n";
|
||||
for (int i = 0; i < 16; ++i)
|
||||
contents += "import child\n";
|
||||
Reject(contents, "total action input limit", 17);
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, EnforcesLoadLimitEvenForEmptyImports)
|
||||
{
|
||||
Write("empty.act", "# action: empty\n");
|
||||
std::string contents = "# action: root\n";
|
||||
for (int i = 0; i < 4096; ++i)
|
||||
contents += "import empty\n";
|
||||
Reject(contents, "file load limit", 4097);
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,177 @@
|
||||
#include "ActionScheduler.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
namespace
|
||||
{
|
||||
using namespace Bilicraft;
|
||||
ActionCommand Command(std::string text)
|
||||
{
|
||||
ActionCommand command{};
|
||||
command.kind = ActionKind::SendMessage;
|
||||
command.text = std::move(text);
|
||||
return command;
|
||||
}
|
||||
ActionCommand Wait(std::chrono::milliseconds delay)
|
||||
{
|
||||
ActionCommand command{};
|
||||
command.kind = ActionKind::Wait;
|
||||
command.waitDuration = delay;
|
||||
return command;
|
||||
}
|
||||
const ActionScheduler::Clock::time_point start{};
|
||||
|
||||
TEST(ActionScheduler, NewestActionFirstButRunningActionIsNotPreempted)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
queue.Enqueue({"old", {Command("old")}});
|
||||
queue.Enqueue({"new", {Command("new1"), Command("new2")}});
|
||||
ASSERT_EQ(queue.Next(start)->command.text, "new1");
|
||||
queue.Enqueue({"newest", {Command("newest")}});
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "new2");
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "newest");
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "old");
|
||||
queue.Finish(true);
|
||||
EXPECT_FALSE(queue.HasWork());
|
||||
}
|
||||
|
||||
TEST(ActionScheduler, WaitBlocksOnlyItsActionAndResumesAtFollowingCommand)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
queue.Enqueue({"other", {Command("other")}});
|
||||
const auto id = queue.Enqueue({"waiting", {Wait(2s), Command("resumed")}});
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "other");
|
||||
const auto tasks = queue.Tasks();
|
||||
ASSERT_EQ(tasks.size(), 2U);
|
||||
EXPECT_EQ(tasks[1].id, id);
|
||||
EXPECT_EQ(tasks[1].state, ActionScheduler::State::Blocked);
|
||||
EXPECT_EQ(tasks[1].nextCommand, 1U);
|
||||
queue.Finish(true);
|
||||
EXPECT_FALSE(queue.Next(start + 1999ms));
|
||||
EXPECT_EQ(queue.NextWake(), start + 2s);
|
||||
EXPECT_EQ(queue.Next(start + 2s)->command.text, "resumed");
|
||||
queue.Finish(true);
|
||||
EXPECT_FALSE(queue.HasWork());
|
||||
}
|
||||
|
||||
TEST(ActionScheduler, InteractiveWaitsForActionBoundaryButWinsOverQueuedTasks)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
queue.Enqueue({"active", {Command("a"), Command("b")}});
|
||||
queue.Next(start);
|
||||
queue.SubmitInteractive(Command("interactive"));
|
||||
queue.Enqueue({"queued", {Command("queued")}});
|
||||
EXPECT_THROW(queue.SubmitInteractive(Command("second")), std::runtime_error);
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "b");
|
||||
queue.Finish(true);
|
||||
auto work = queue.Next(start);
|
||||
ASSERT_TRUE(work);
|
||||
EXPECT_TRUE(work->interactive);
|
||||
EXPECT_EQ(work->command.text, "interactive");
|
||||
EXPECT_TRUE(queue.InteractivePending());
|
||||
queue.Finish(true);
|
||||
EXPECT_FALSE(queue.InteractivePending());
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "queued");
|
||||
}
|
||||
|
||||
TEST(ActionScheduler, InteractiveRunsWhenActiveActionReachesWait)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
queue.Enqueue({"active", {Command("a"), Wait(10s), Command("b")}});
|
||||
queue.Next(start);
|
||||
queue.SubmitInteractive(Command("interactive"));
|
||||
queue.Finish(true);
|
||||
EXPECT_TRUE(queue.Next(start)->interactive);
|
||||
queue.Finish(true);
|
||||
EXPECT_FALSE(queue.Next(start + 1s));
|
||||
EXPECT_EQ(queue.Next(start + 10s)->command.text, "b");
|
||||
}
|
||||
|
||||
TEST(ActionScheduler, AwakenedActionDoesNotInterruptRunningAction)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
queue.Enqueue({"other", {Command("a"), Command("b")}});
|
||||
queue.Enqueue({"sleeper", {Wait(1s), Command("awake")}});
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "a");
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start + 2s)->command.text, "b");
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start + 2s)->command.text, "awake");
|
||||
}
|
||||
|
||||
TEST(ActionScheduler, ZeroWaitYieldsAndFinalWaitCompletesOnlyAfterDeadline)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
queue.Enqueue({"other", {Command("other")}});
|
||||
queue.Enqueue({"zero", {Wait(0ms), Command("zero")}});
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "other");
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "zero");
|
||||
queue.Finish(true);
|
||||
queue.Enqueue({"final", {Wait(1h)}});
|
||||
EXPECT_FALSE(queue.Next(start));
|
||||
EXPECT_TRUE(queue.HasWork());
|
||||
EXPECT_FALSE(queue.Next(start + 1h));
|
||||
EXPECT_FALSE(queue.HasWork());
|
||||
}
|
||||
|
||||
TEST(ActionScheduler, FailedActionDoesNotDiscardOtherJobsOrPendingInteractive)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
queue.Enqueue({"other", {Command("other")}});
|
||||
queue.Enqueue({"bad", {Command("fail"), Command("must not execute")}});
|
||||
queue.Next(start);
|
||||
queue.SubmitInteractive(Command("interactive"));
|
||||
queue.Finish(false);
|
||||
EXPECT_TRUE(queue.Next(start)->interactive);
|
||||
queue.Finish(false);
|
||||
EXPECT_FALSE(queue.InteractivePending());
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "other");
|
||||
}
|
||||
|
||||
TEST(ActionScheduler, RejectsInteractiveWaitInvalidDurationsAndDuplicateDispatch)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
EXPECT_THROW(queue.SubmitInteractive(Wait(1s)), std::runtime_error);
|
||||
EXPECT_THROW(queue.Enqueue({"bad", {Wait(-1ms)}}), std::runtime_error);
|
||||
EXPECT_THROW(queue.Enqueue({"bad", {Wait(24h * 366)}}), std::runtime_error);
|
||||
EXPECT_THROW(queue.Finish(true), std::logic_error);
|
||||
queue.Enqueue({"good", {Command("one")}});
|
||||
queue.Next(start);
|
||||
EXPECT_THROW(queue.Next(start), std::logic_error);
|
||||
queue.Finish(true);
|
||||
EXPECT_FALSE(queue.Next(start));
|
||||
}
|
||||
|
||||
TEST(ActionScheduler, MultipleWakeupsUseNewestReadyOrderAndInteractivePriority)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
queue.Enqueue({"later", {Wait(2s), Command("later")}});
|
||||
queue.Enqueue({"earlier", {Wait(1s), Command("earlier")}});
|
||||
EXPECT_FALSE(queue.Next(start));
|
||||
queue.SubmitInteractive(Command("interactive"));
|
||||
EXPECT_TRUE(queue.Next(start + 3s)->interactive);
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start + 3s)->command.text, "later");
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start + 3s)->command.text, "earlier");
|
||||
}
|
||||
|
||||
TEST(ActionScheduler, NewSubmissionAfterWaitExpiryIsNewerThanTheAwakenedTask)
|
||||
{
|
||||
ActionScheduler queue;
|
||||
queue.Enqueue({"running", {Command("long")}}, start);
|
||||
queue.Enqueue({"sleeping", {Wait(1s), Command("awake")}}, start);
|
||||
EXPECT_EQ(queue.Next(start)->command.text, "long");
|
||||
queue.Enqueue({"new submission", {Command("new")}}, start + 5s);
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start + 10s)->command.text, "new");
|
||||
queue.Finish(true);
|
||||
EXPECT_EQ(queue.Next(start + 10s)->command.text, "awake");
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,86 @@
|
||||
#include "AppConfig.h"
|
||||
|
||||
#include <initializer_list>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
Bilicraft::AppConfig Parse(std::initializer_list<std::string_view> arguments)
|
||||
{
|
||||
return Bilicraft::ParseArguments({arguments.begin(), arguments.size()});
|
||||
}
|
||||
|
||||
TEST(AppConfig, DefaultsMatchBilicraftServer)
|
||||
{
|
||||
const auto config = Parse({});
|
||||
EXPECT_EQ(config.server, "mc.bilicraft.com:25577");
|
||||
EXPECT_EQ(Bilicraft::kGameVersion, "1.21.11");
|
||||
EXPECT_TRUE(config.account.empty());
|
||||
EXPECT_FALSE(config.help);
|
||||
}
|
||||
|
||||
TEST(AppConfig, OverridesServerAndCacheKey)
|
||||
{
|
||||
const auto config = Parse({"--server", "localhost:25565", "--account", "farmer"});
|
||||
EXPECT_EQ(config.server, "localhost:25565");
|
||||
EXPECT_EQ(config.account, "farmer");
|
||||
}
|
||||
|
||||
TEST(AppConfig, LastRepeatedOptionWins)
|
||||
{
|
||||
const auto config = Parse({"--account", "first", "--account", "second"});
|
||||
EXPECT_EQ(config.account, "second");
|
||||
}
|
||||
|
||||
TEST(AppConfig, AcceptsHelpAliases)
|
||||
{
|
||||
EXPECT_TRUE(Parse({"--help"}).help);
|
||||
EXPECT_TRUE(Parse({"-h"}).help);
|
||||
}
|
||||
|
||||
TEST(AppConfig, RejectsUnknownOptionsAndPositionalArguments)
|
||||
{
|
||||
EXPECT_THROW(Parse({"--unknown"}), std::invalid_argument);
|
||||
EXPECT_THROW(Parse({"localhost:25565"}), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(AppConfig, RejectsMissingValues)
|
||||
{
|
||||
EXPECT_THROW(Parse({"--server"}), std::invalid_argument);
|
||||
EXPECT_THROW(Parse({"--account"}), std::invalid_argument);
|
||||
EXPECT_THROW(Parse({"--server", "--account", "farmer"}), std::invalid_argument);
|
||||
EXPECT_THROW(Parse({"--account", "--help"}), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(AppConfig, RejectsEmptyValues)
|
||||
{
|
||||
EXPECT_THROW(Parse({"--server", ""}), std::invalid_argument);
|
||||
EXPECT_THROW(Parse({"--account", ""}), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(AppConfig, ActionExecutionAndOfflineCheck)
|
||||
{
|
||||
auto config = Parse({"--action", "farm.act"});
|
||||
EXPECT_EQ(config.actionFile, "farm.act");
|
||||
EXPECT_FALSE(config.checkAction);
|
||||
config = Parse({"--check-action", "farm.act"});
|
||||
EXPECT_EQ(config.actionFile, "farm.act");
|
||||
EXPECT_TRUE(config.checkAction);
|
||||
EXPECT_THROW(Parse({"--action"}), std::invalid_argument);
|
||||
EXPECT_THROW(Parse({"--check-action", ""}), std::invalid_argument);
|
||||
EXPECT_THROW(Parse({"--action", "a.act", "--check-action", "b.act"}), std::invalid_argument);
|
||||
EXPECT_THROW(Parse({"--action", "a.act", "--action", "b.act"}), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(AppConfig, HelpDescribesDefaultsAndMicrosoftAuthentication)
|
||||
{
|
||||
const auto usage = Bilicraft::Usage();
|
||||
EXPECT_TRUE(usage.starts_with("Usage: bilicraft-bot "));
|
||||
EXPECT_NE(usage.find("1.21.11"), std::string::npos);
|
||||
EXPECT_NE(usage.find("mc.bilicraft.com:25577"), std::string::npos);
|
||||
EXPECT_NE(usage.find("Microsoft"), std::string::npos);
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,75 @@
|
||||
#include "BilicraftClient.h"
|
||||
|
||||
#include <string>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
ProtocolCraft::Chat DisconnectReason()
|
||||
{
|
||||
// Protocol 774 encodes chat as unnamed NBT. A string tag is sufficient.
|
||||
const std::string reason = "Test disconnect";
|
||||
ProtocolCraft::WriteContainer bytes{8};
|
||||
ProtocolCraft::WriteData<unsigned short>(static_cast<unsigned short>(reason.size()), bytes);
|
||||
bytes.insert(bytes.end(), reason.begin(), reason.end());
|
||||
auto iterator = bytes.cbegin();
|
||||
auto remaining = bytes.size();
|
||||
ProtocolCraft::Chat chat;
|
||||
chat.Read(iterator, remaining);
|
||||
return chat;
|
||||
}
|
||||
|
||||
TEST(BilicraftClient, StartsWithoutNetworkOrGameSession)
|
||||
{
|
||||
Bilicraft::BilicraftClient client;
|
||||
EXPECT_FALSE(client.GetNetworkManager());
|
||||
EXPECT_FALSE(client.WasDisconnected());
|
||||
EXPECT_FALSE(client.HasEnteredPlay());
|
||||
EXPECT_FALSE(client.GetAutoRespawn());
|
||||
client.Disconnect();
|
||||
client.Disconnect(); // Cleanup is intentionally idempotent.
|
||||
}
|
||||
|
||||
TEST(BilicraftClient, ActionYieldRunsSynchronouslyAndPropagatesCancellation)
|
||||
{
|
||||
Bilicraft::BilicraftClient client;
|
||||
int ticks = 0;
|
||||
client.SetActionYieldHandler([&ticks] { ++ticks; });
|
||||
client.Yield();
|
||||
client.Yield();
|
||||
EXPECT_EQ(ticks, 2);
|
||||
client.SetActionYieldHandler([] { throw std::runtime_error("cancelled"); });
|
||||
EXPECT_THROW(client.Yield(), std::runtime_error);
|
||||
client.SetActionYieldHandler({});
|
||||
}
|
||||
|
||||
TEST(BilicraftClient, LoginDisconnectSignalsMainThread)
|
||||
{
|
||||
Bilicraft::BilicraftClient client;
|
||||
ProtocolCraft::ClientboundLoginDisconnectPacket packet;
|
||||
packet.SetReason(R"({"text":"Test disconnect"})");
|
||||
packet.Dispatch(&client);
|
||||
EXPECT_TRUE(client.WasDisconnected());
|
||||
EXPECT_FALSE(client.HasEnteredPlay());
|
||||
}
|
||||
|
||||
TEST(BilicraftClient, ConfigurationDisconnectSignalsMainThread)
|
||||
{
|
||||
Bilicraft::BilicraftClient client;
|
||||
ProtocolCraft::ClientboundDisconnectConfigurationPacket packet;
|
||||
packet.SetReason(DisconnectReason());
|
||||
packet.Dispatch(&client);
|
||||
EXPECT_TRUE(client.WasDisconnected());
|
||||
}
|
||||
|
||||
TEST(BilicraftClient, PlayDisconnectSignalsMainThread)
|
||||
{
|
||||
Bilicraft::BilicraftClient client;
|
||||
ProtocolCraft::ClientboundDisconnectPacket packet;
|
||||
packet.SetReason(DisconnectReason());
|
||||
packet.Dispatch(&client);
|
||||
EXPECT_TRUE(client.WasDisconnected());
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,125 @@
|
||||
#include "ConsoleCommand.h"
|
||||
#include "ActionScheduler.h"
|
||||
#include "TerminalInput.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <thread>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <cstdlib>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace Bilicraft;
|
||||
TEST(ConsoleCommand, ParsesControlCommandsAndPathsWithSpaces)
|
||||
{
|
||||
EXPECT_EQ(ParseConsoleCommand(" ").kind, ConsoleKind::Empty);
|
||||
EXPECT_EQ(ParseConsoleCommand("# comment").kind, ConsoleKind::Empty);
|
||||
EXPECT_EQ(ParseConsoleCommand("help # help").kind, ConsoleKind::Help);
|
||||
EXPECT_EQ(ParseConsoleCommand("tasks").kind, ConsoleKind::Tasks);
|
||||
EXPECT_EQ(ParseConsoleCommand("exit").kind, ConsoleKind::Quit);
|
||||
EXPECT_EQ(ParseConsoleCommand("quit").kind, ConsoleKind::Quit);
|
||||
EXPECT_EQ(ParseConsoleCommand("run ../../actions/demo.act").path, "../../actions/demo.act");
|
||||
EXPECT_EQ(ParseConsoleCommand("run \"path with spaces.act\"").path, "path with spaces.act");
|
||||
EXPECT_EQ(ParseConsoleCommand("run 'path with spaces.act'").path, "path with spaces.act");
|
||||
}
|
||||
TEST(ConsoleCommand, RejectsInvalidControlsAndInteractiveWaitOrImport)
|
||||
{
|
||||
for (auto text : {"run", "run \"\"", "help now", "tasks 1", "quit now", "wait 3", "import demo",
|
||||
"sw 1\nsw 2", "sw 1\rsw 2"})
|
||||
EXPECT_THROW(ParseConsoleCommand(text), std::exception) << text;
|
||||
EXPECT_THROW(ParseConsoleCommand(std::string("sw 1\0x", 6)), std::exception);
|
||||
}
|
||||
TEST(ConsoleCommand, UsesTheSameGameCommandParser)
|
||||
{
|
||||
const auto message = ParseConsoleCommand("sendmsg @Steve hello world");
|
||||
ASSERT_EQ(message.kind, ConsoleKind::Action);
|
||||
ASSERT_TRUE(message.action);
|
||||
EXPECT_EQ(message.action->recipient, "Steve");
|
||||
EXPECT_EQ(message.action->text, "hello world");
|
||||
EXPECT_EQ(ParseConsoleCommand("drop all").action->kind, ActionKind::Drop);
|
||||
EXPECT_TRUE(ParseConsoleCommand("drop all").action->all);
|
||||
}
|
||||
|
||||
#ifndef _WIN32
|
||||
TEST(ConsoleCommand, NativePseudoTerminalWaitsForEnterAndParsesTheCommand)
|
||||
{
|
||||
const int master = posix_openpt(O_RDWR | O_NOCTTY);
|
||||
ASSERT_GE(master, 0);
|
||||
struct Fd
|
||||
{
|
||||
int value;
|
||||
~Fd() { if (value >= 0) close(value); }
|
||||
} masterGuard{master};
|
||||
ASSERT_EQ(grantpt(master), 0);
|
||||
ASSERT_EQ(unlockpt(master), 0);
|
||||
const char *name = ptsname(master);
|
||||
ASSERT_NE(name, nullptr);
|
||||
const int slave = open(name, O_RDWR | O_NOCTTY);
|
||||
ASSERT_GE(slave, 0);
|
||||
Fd slaveGuard{slave};
|
||||
TerminalInput terminal(slave);
|
||||
ASSERT_TRUE(terminal.IsInteractive());
|
||||
ASSERT_EQ(write(master, "sw 3", 4), 4);
|
||||
EXPECT_FALSE(terminal.PollLine());
|
||||
ASSERT_EQ(write(master, "\n", 1), 1);
|
||||
// Delivery through a PTY can be asynchronous; a bounded poll, not a blocking read.
|
||||
std::optional<std::string> line;
|
||||
const auto deadline = ActionScheduler::Clock::now() + std::chrono::seconds(1);
|
||||
while (!line && ActionScheduler::Clock::now() < deadline)
|
||||
{
|
||||
line = terminal.PollLine();
|
||||
if (!line) std::this_thread::yield();
|
||||
}
|
||||
ASSERT_TRUE(line);
|
||||
const auto command = ParseConsoleCommand(*line);
|
||||
ASSERT_TRUE(command.action);
|
||||
EXPECT_EQ(command.action->kind, ActionKind::SelectHotbar);
|
||||
EXPECT_EQ(command.action->slot, 3);
|
||||
}
|
||||
|
||||
TEST(ConsoleCommand, PipeInputDoesNotConsumeNextCommandUntilPreviousExecutionFinishes)
|
||||
{
|
||||
int descriptors[2];
|
||||
ASSERT_EQ(pipe(descriptors), 0);
|
||||
struct Close
|
||||
{
|
||||
int a, b;
|
||||
~Close() { close(a); close(b); }
|
||||
} closePipe{descriptors[0], descriptors[1]};
|
||||
const std::string input = "sendmsg first\nsendmsg second\n";
|
||||
ASSERT_EQ(write(descriptors[1], input.data(), input.size()), static_cast<ssize_t>(input.size()));
|
||||
TerminalInput terminal(descriptors[0]);
|
||||
ActionScheduler scheduler;
|
||||
const auto now = ActionScheduler::Clock::time_point{};
|
||||
scheduler.Enqueue({"active", {*ParseInteractiveCommand("sendmsg active")}});
|
||||
auto work = scheduler.Next(now);
|
||||
ASSERT_EQ(work->command.text, "active");
|
||||
int linesRead = 0;
|
||||
const auto pump = [&] {
|
||||
if (scheduler.InteractivePending()) return;
|
||||
if (auto line = terminal.PollLine())
|
||||
{
|
||||
++linesRead;
|
||||
scheduler.SubmitInteractive(*ParseConsoleCommand(*line).action);
|
||||
}
|
||||
};
|
||||
pump();
|
||||
pump();
|
||||
EXPECT_EQ(linesRead, 1);
|
||||
scheduler.Finish(true);
|
||||
work = scheduler.Next(now);
|
||||
ASSERT_TRUE(work->interactive);
|
||||
EXPECT_EQ(work->command.text, "first");
|
||||
pump();
|
||||
EXPECT_EQ(linesRead, 1);
|
||||
scheduler.Finish(true);
|
||||
pump();
|
||||
EXPECT_EQ(linesRead, 2);
|
||||
EXPECT_EQ(scheduler.Next(now)->command.text, "second");
|
||||
}
|
||||
#endif
|
||||
} // namespace
|
||||
@@ -0,0 +1,325 @@
|
||||
#include "EntityInteraction.h"
|
||||
|
||||
#include <array>
|
||||
#include <climits>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "botcraft/Game/Entities/EntityManager.hpp"
|
||||
#include "botcraft/Game/Entities/entities/UnknownEntity.hpp"
|
||||
#include "botcraft/Game/Entities/entities/decoration/GlowItemFrameEntity.hpp"
|
||||
#include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp"
|
||||
#include "botcraft/Game/Entities/entities/decoration/painting/PaintingEntity.hpp"
|
||||
#include "protocolCraft/Packets/Game/Serverbound/ServerboundInteractPacket.hpp"
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace Bilicraft;
|
||||
using Botcraft::Vector3;
|
||||
|
||||
struct FaceCase
|
||||
{
|
||||
EntityFace face;
|
||||
int direction;
|
||||
Vector3<double> normal;
|
||||
};
|
||||
|
||||
const std::array<FaceCase, 6> Faces = {{{EntityFace::Bottom, 0, {0, -1, 0}},
|
||||
{EntityFace::Top, 1, {0, 1, 0}},
|
||||
{EntityFace::North, 2, {0, 0, -1}},
|
||||
{EntityFace::South, 3, {0, 0, 1}},
|
||||
{EntityFace::West, 4, {-1, 0, 0}},
|
||||
{EntityFace::East, 5, {1, 0, 0}}}};
|
||||
|
||||
ActionCommand Command(int x = 0, int y = 0, int z = 0, EntityFace face = EntityFace::Any)
|
||||
{
|
||||
ActionCommand command{};
|
||||
command.kind = ActionKind::RightClick;
|
||||
command.entity = true;
|
||||
command.x = x;
|
||||
command.y = y;
|
||||
command.z = z;
|
||||
command.entityFace = face;
|
||||
return command;
|
||||
}
|
||||
|
||||
std::shared_ptr<Botcraft::ItemFrameEntity> Frame(int id, const Vector3<double> &anchor, int direction, bool glow = false)
|
||||
{
|
||||
std::shared_ptr<Botcraft::ItemFrameEntity> frame;
|
||||
if (glow)
|
||||
frame = std::make_shared<Botcraft::GlowItemFrameEntity>();
|
||||
else
|
||||
frame = std::make_shared<Botcraft::ItemFrameEntity>();
|
||||
frame->SetEntityID(id);
|
||||
frame->SetPosition(anchor);
|
||||
frame->SetDataDirection(direction);
|
||||
return frame;
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, AllSixFacesUseIntegralAttachmentCellsForBothFrameTypes)
|
||||
{
|
||||
for (bool glow : {false, true})
|
||||
for (const auto &support : {Vector3<double>{0, 0, 0}, Vector3<double>{7, 64, 12}, Vector3<double>{-7, -64, -12}})
|
||||
for (const auto &face : Faces)
|
||||
{
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
const auto frame = Frame(42, support + face.normal, face.direction, glow);
|
||||
manager.AddEntity(frame);
|
||||
auto command = Command(static_cast<int>(support.x), static_cast<int>(support.y),
|
||||
static_cast<int>(support.z));
|
||||
EXPECT_EQ(FindItemFrame(manager, command), frame);
|
||||
EXPECT_TRUE(MatchesItemFrame(*frame, command));
|
||||
for (const auto &requested : Faces)
|
||||
{
|
||||
command.entityFace = requested.face;
|
||||
EXPECT_EQ(MatchesItemFrame(*frame, command), requested.face == face.face);
|
||||
EXPECT_EQ(FindItemFrame(manager, command) != nullptr, requested.face == face.face);
|
||||
}
|
||||
// The client-side collider's center is derived, not GetPosition().
|
||||
const auto center = ItemFrameCenter(*frame);
|
||||
EXPECT_DOUBLE_EQ(center.x, support.x + 0.5 + face.normal.x * 0.53125);
|
||||
EXPECT_DOUBLE_EQ(center.y, support.y + 0.5 + face.normal.y * 0.53125);
|
||||
EXPECT_DOUBLE_EQ(center.z, support.z + 0.5 + face.normal.z * 0.53125);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, AnyRequiresUniqueFrameAndExplicitFaceDisambiguates)
|
||||
{
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
EXPECT_EQ(FindItemFrame(manager, Command()), nullptr);
|
||||
const auto south = Frame(1, {0, 0, 1}, 3);
|
||||
const auto top = Frame(2, {0, 1, 0}, 1, true);
|
||||
manager.AddEntity(south);
|
||||
manager.AddEntity(top);
|
||||
EXPECT_THROW(FindItemFrame(manager, Command()), std::runtime_error);
|
||||
EXPECT_EQ(FindItemFrame(manager, Command(0, 0, 0, EntityFace::South)), south);
|
||||
EXPECT_EQ(FindItemFrame(manager, Command(0, 0, 0, EntityFace::Top)), top);
|
||||
EXPECT_EQ(FindItemFrame(manager, Command(0, 0, 0, EntityFace::West)), nullptr);
|
||||
manager.AddEntity(Frame(3, {0, 0, 1}, 3, true));
|
||||
EXPECT_THROW(FindItemFrame(manager, Command(0, 0, 0, EntityFace::South)), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, IgnoresOtherEntitiesEvenHangingEntitiesAtExactAnchor)
|
||||
{
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
const auto unknown = std::make_shared<Botcraft::UnknownEntity>();
|
||||
unknown->SetEntityID(1);
|
||||
unknown->SetPosition({0, 0, 1});
|
||||
manager.AddEntity(unknown);
|
||||
const auto painting = std::make_shared<Botcraft::PaintingEntity>();
|
||||
painting->SetEntityID(2);
|
||||
painting->SetPosition({0, 0, 1});
|
||||
painting->SetDataDirection(3);
|
||||
manager.AddEntity(painting);
|
||||
EXPECT_EQ(FindItemFrame(manager, Command()), nullptr);
|
||||
const auto frame = Frame(3, {0, 0, 1}, 3, true);
|
||||
manager.AddEntity(frame);
|
||||
EXPECT_EQ(FindItemFrame(manager, Command()), frame);
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, DoesNotRoundOrSearchNearbyInvalidPositions)
|
||||
{
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
// None is the requested anchor or its exact vanilla center.
|
||||
int id = 0;
|
||||
for (const auto &anchor : {Vector3<double>{1, 0, 1}, Vector3<double>{0, 1, 1},
|
||||
Vector3<double>{0, 0, 2}, Vector3<double>{0.5, 0.5, 1.031250001},
|
||||
Vector3<double>{0, 0, 0.999999999}, Vector3<double>{-0.000000001, 0, 1}})
|
||||
manager.AddEntity(Frame(++id, anchor, 3));
|
||||
EXPECT_EQ(FindItemFrame(manager, Command()), nullptr);
|
||||
const auto valid = Frame(++id, {0, 0, 1}, 3);
|
||||
manager.AddEntity(valid);
|
||||
EXPECT_EQ(FindItemFrame(manager, Command()), valid);
|
||||
valid->SetPosition({1, 0, 1});
|
||||
EXPECT_FALSE(MatchesItemFrame(*valid, Command()));
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, ExactCentersResolveAllFacesWithoutApplyingCenterOffsetTwice)
|
||||
{
|
||||
for (bool glow : {false, true})
|
||||
for (const auto &support : {Vector3<double>{16487, 94, 3129}, Vector3<double>{-7, -64, -12}})
|
||||
for (const auto &face : Faces)
|
||||
{
|
||||
const Vector3<double> center = support + Vector3<double>{0.5, 0.5, 0.5} + face.normal * 0.53125;
|
||||
const auto frame = Frame(42, center, face.direction, glow);
|
||||
const auto command = Command(static_cast<int>(support.x), static_cast<int>(support.y),
|
||||
static_cast<int>(support.z), face.face);
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
manager.AddEntity(frame);
|
||||
EXPECT_EQ(FindItemFrame(manager, command), frame);
|
||||
const auto actual = ItemFrameCenter(*frame);
|
||||
EXPECT_DOUBLE_EQ(actual.x, center.x);
|
||||
EXPECT_DOUBLE_EQ(actual.y, center.y);
|
||||
EXPECT_DOUBLE_EQ(actual.z, center.z);
|
||||
for (const auto &other : Faces)
|
||||
if (other.face != face.face)
|
||||
EXPECT_FALSE(MatchesItemFrame(*frame, Command(command.x, command.y, command.z, other.face)));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, MixedAnchorAndCenterRepresentationsStillRejectAmbiguity)
|
||||
{
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
manager.AddEntity(Frame(1, {0, 0, 1}, 3));
|
||||
manager.AddEntity(Frame(2, {0.5, 0.5, 1.03125}, 3, true));
|
||||
EXPECT_THROW(FindItemFrame(manager, Command()), std::runtime_error);
|
||||
EXPECT_THROW(FindItemFrame(manager, Command(0, 0, 0, EntityFace::South)), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, MissingTargetDiagnosticExplainsActualSupportDirectionAndCounts)
|
||||
{
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
const auto request = Command(16487, 94, 3129, EntityFace::West);
|
||||
EXPECT_NE(DescribeItemFrameTargets(manager, request).find("loaded_frames=0"), std::string::npos);
|
||||
const auto frame = Frame(42, {16488.03125, 94.5, 3129.5}, 5);
|
||||
manager.AddEntity(frame);
|
||||
EXPECT_EQ(FindItemFrame(manager, request), nullptr);
|
||||
const auto details = DescribeItemFrameTargets(manager, request);
|
||||
EXPECT_NE(details.find("requested support=(16487,94,3129), face=w"), std::string::npos);
|
||||
EXPECT_NE(details.find("loaded_frames=1; nearby_within_8=1"), std::string::npos);
|
||||
EXPECT_NE(details.find("id=42 type=item_frame raw=(16488.03125,94.5,3129.5) direction=5(e) support=(16487,94,3129)"), std::string::npos);
|
||||
EXPECT_DOUBLE_EQ(frame->GetPosition().x, 16488.03125); // Diagnostics never mutate or retarget.
|
||||
EXPECT_EQ(FindItemFrame(manager, request), nullptr);
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, DiagnosticsAreBoundedAndExposeInvalidGeometryWithoutGuessing)
|
||||
{
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
manager.AddEntity(Frame(1, {0.2, 0.3, 0.4}, -1));
|
||||
for (int id = 2; id <= 12; ++id) manager.AddEntity(Frame(id, {0, 0, 1}, 3));
|
||||
manager.AddEntity(Frame(13, {1000, 1000, 1000}, 3));
|
||||
const auto text = DescribeItemFrameTargets(manager, Command());
|
||||
EXPECT_NE(text.find("loaded_frames=13; nearby_within_8=12"), std::string::npos);
|
||||
EXPECT_NE(text.find("support=unknown(invalid position/direction)"), std::string::npos);
|
||||
EXPECT_NE(text.find("showing_nearest=8"), std::string::npos);
|
||||
std::size_t count = 0;
|
||||
for (std::size_t at = 0; (at = text.find("; id=", at)) != std::string::npos; at += 5) ++count;
|
||||
EXPECT_EQ(count, 8U);
|
||||
EXPECT_EQ(text.find("id=13 "), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, RejectsMalformedDirectionAndNonfiniteFractionalOrOutOfRangePositions)
|
||||
{
|
||||
auto frame = Frame(1, {0, 0, 1}, 3);
|
||||
for (int direction : {-1, 6, INT_MIN, INT_MAX})
|
||||
{
|
||||
frame->SetDataDirection(direction);
|
||||
EXPECT_FALSE(MatchesItemFrame(*frame, Command()));
|
||||
EXPECT_THROW(ItemFrameCenter(*frame), std::runtime_error);
|
||||
}
|
||||
frame->SetDataDirection(3);
|
||||
for (double value : {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::infinity(),
|
||||
-std::numeric_limits<double>::infinity(), 0.25, -0.25, 33554432.0, -33554433.0,
|
||||
static_cast<double>(INT_MAX), static_cast<double>(INT_MIN)})
|
||||
for (int axis = 0; axis < 3; ++axis)
|
||||
{
|
||||
Vector3<double> anchor{0, 0, 1};
|
||||
anchor[axis] = value;
|
||||
frame->SetPosition(anchor);
|
||||
EXPECT_FALSE(MatchesItemFrame(*frame, Command()));
|
||||
EXPECT_THROW(ItemFrameCenter(*frame), std::runtime_error);
|
||||
}
|
||||
for (double y : {-2049.0, 2048.0})
|
||||
{
|
||||
frame->SetPosition({0, y, 1});
|
||||
EXPECT_THROW(ItemFrameCenter(*frame), std::runtime_error);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, ValidatesCommandBeforeEmptyManagerSearch)
|
||||
{
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
auto command = Command();
|
||||
command.entity = false;
|
||||
EXPECT_THROW(FindItemFrame(manager, command), std::runtime_error);
|
||||
command = Command();
|
||||
command.kind = ActionKind::Goto;
|
||||
EXPECT_THROW(FindItemFrame(manager, command), std::runtime_error);
|
||||
command = Command();
|
||||
command.entityFace = static_cast<EntityFace>(99);
|
||||
EXPECT_THROW(FindItemFrame(manager, command), std::runtime_error);
|
||||
for (int value : {INT_MIN, -33554433, 33554432, INT_MAX})
|
||||
{
|
||||
EXPECT_THROW(FindItemFrame(manager, Command(value, 0, 0)), std::runtime_error);
|
||||
EXPECT_THROW(FindItemFrame(manager, Command(0, 0, value)), std::runtime_error);
|
||||
}
|
||||
for (int value : {INT_MIN, -2049, 2048, INT_MAX})
|
||||
EXPECT_THROW(FindItemFrame(manager, Command(0, value, 0)), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, HandlesNegativeAndPositiveProtocolEdgesWithoutWrapping)
|
||||
{
|
||||
for (const auto &face : Faces)
|
||||
for (const auto &support : {Vector3<double>{-33554431, -2047, -33554431},
|
||||
Vector3<double>{33554430, 2046, 33554430}})
|
||||
{
|
||||
const auto frame = Frame(1, support + face.normal, face.direction);
|
||||
const auto command = Command(static_cast<int>(support.x), static_cast<int>(support.y),
|
||||
static_cast<int>(support.z), face.face);
|
||||
EXPECT_TRUE(MatchesItemFrame(*frame, command));
|
||||
EXPECT_NO_THROW(ItemFrameCenter(*frame));
|
||||
}
|
||||
EXPECT_TRUE(MatchesItemFrame(*Frame(1, {-33554432, -2048, -33554431}, 3),
|
||||
Command(-33554432, -2048, -33554432)));
|
||||
EXPECT_TRUE(MatchesItemFrame(*Frame(1, {33554431, 2047, 33554430}, 2),
|
||||
Command(33554431, 2047, 33554431)));
|
||||
EXPECT_FALSE(MatchesItemFrame(*Frame(1, {33554432, 0, 0}, 5), Command(33554431, 0, 0)));
|
||||
EXPECT_FALSE(MatchesItemFrame(*Frame(1, {0, -2049, 0}, 0), Command(0, -2048, 0)));
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, ManagerLockIsReleasedOnSuccessAndAmbiguity)
|
||||
{
|
||||
Botcraft::EntityManager manager(nullptr);
|
||||
const auto first = Frame(1, {0, 0, 1}, 3);
|
||||
manager.AddEntity(first);
|
||||
const auto selected = FindItemFrame(manager, Command());
|
||||
EXPECT_EQ(selected, first);
|
||||
manager.AddEntity(Frame(2, {0, 0, 1}, 3));
|
||||
EXPECT_THROW(FindItemFrame(manager, Command()), std::runtime_error);
|
||||
manager.AddEntity(Frame(2, {10, 10, 10}, 3));
|
||||
EXPECT_EQ(FindItemFrame(manager, Command()), first);
|
||||
}
|
||||
|
||||
TEST(EntityInteraction, InteractWireRoundTripUsesMainHandOnlyForRightClick)
|
||||
{
|
||||
using namespace ProtocolCraft;
|
||||
for (int id : {0, 127, 128, 123456, INT_MAX, -1})
|
||||
for (bool attack : {false, true})
|
||||
for (bool secondary : {false, true})
|
||||
{
|
||||
const auto packet = MakeEntityInteractionPacket(id, attack, secondary);
|
||||
EXPECT_EQ(packet->GetEntityId(), id);
|
||||
EXPECT_EQ(packet->GetAction(), attack ? 1 : 0);
|
||||
EXPECT_EQ(packet->GetUsingSecondaryAction(), secondary);
|
||||
WriteContainer bytes;
|
||||
packet->Write(bytes);
|
||||
auto iter = bytes.cbegin();
|
||||
std::size_t remaining = bytes.size();
|
||||
ASSERT_EQ(ReadData<VarInt>(iter, remaining), packet->GetId());
|
||||
const auto payloadBegin = iter;
|
||||
const auto payloadSize = remaining;
|
||||
EXPECT_EQ(ReadData<VarInt>(iter, remaining), id);
|
||||
EXPECT_EQ(ReadData<VarInt>(iter, remaining), attack ? 1 : 0);
|
||||
// Exactly secondary bool for attack; main-hand VarInt + bool
|
||||
// for right-click. No hidden hand or interact-at coordinates.
|
||||
ASSERT_EQ(remaining, attack ? 1u : 2u);
|
||||
if (!attack)
|
||||
EXPECT_EQ(ReadData<VarInt>(iter, remaining), 0);
|
||||
EXPECT_EQ(ReadData<bool>(iter, remaining), secondary);
|
||||
EXPECT_EQ(remaining, 0u);
|
||||
ServerboundInteractPacket decoded;
|
||||
iter = payloadBegin;
|
||||
remaining = payloadSize;
|
||||
decoded.Read(iter, remaining);
|
||||
EXPECT_EQ(remaining, 0u);
|
||||
EXPECT_EQ(decoded.GetEntityId(), id);
|
||||
EXPECT_EQ(decoded.GetAction(), attack ? 1 : 0);
|
||||
EXPECT_EQ(decoded.GetUsingSecondaryAction(), secondary);
|
||||
WriteContainer roundTrip;
|
||||
decoded.Write(roundTrip);
|
||||
EXPECT_EQ(roundTrip, bytes);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,172 @@
|
||||
#include "ActionExecutor.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "botcraft/Game/Inventory/InventoryManager.hpp"
|
||||
#include "botcraft/Game/Inventory/Window.hpp"
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace ProtocolCraft;
|
||||
|
||||
Slot Item(int count)
|
||||
{
|
||||
Slot item;
|
||||
item.SetItemId(1);
|
||||
item.SetItemCount(count);
|
||||
return item;
|
||||
}
|
||||
|
||||
class InventorySync : public testing::Test
|
||||
{
|
||||
protected:
|
||||
Botcraft::InventoryManager inventory{nullptr}; // Packet replay only, no socket or assets.
|
||||
|
||||
void Full(const Slot &cursor = Slot())
|
||||
{
|
||||
ClientboundContainerSetContentPacket packet;
|
||||
packet.SetContainerId(0);
|
||||
packet.SetStateId(7);
|
||||
std::vector<Slot> slots(46);
|
||||
slots[0] = Item(3); // Sentinel: hotbar updates must not touch crafting output.
|
||||
slots[36] = Item(8);
|
||||
packet.SetItems(slots);
|
||||
packet.SetCarriedItem(cursor);
|
||||
packet.Dispatch(&inventory);
|
||||
}
|
||||
|
||||
void PlayerSlot(int index, const Slot &contents)
|
||||
{
|
||||
ClientboundSetPlayerInventoryPacket packet;
|
||||
packet.SetSlot(index);
|
||||
packet.SetContents(contents);
|
||||
packet.Dispatch(&inventory);
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(InventorySync, EmptyHotbarUpdateClearsHeldItemInsteadOfCraftingOutput)
|
||||
{
|
||||
Full();
|
||||
PlayerSlot(0, Slot());
|
||||
EXPECT_TRUE(inventory.GetHotbarSelected().IsEmptySlot());
|
||||
EXPECT_TRUE(Bilicraft::ReadDropSlot(*inventory.GetPlayerInventory(), 36).IsEmptySlot());
|
||||
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(0).GetItemCount(), 3);
|
||||
}
|
||||
|
||||
TEST_F(InventorySync, MapsEveryPlayerInventoryIndexToMenuSlots)
|
||||
{
|
||||
Full();
|
||||
for (int index = 0; index <= 40; ++index)
|
||||
{
|
||||
const int mapped = index < 9 ? 36 + index : index < 36 ? index : index < 40 ? 44 - index : 45;
|
||||
PlayerSlot(index, Item(index + 1));
|
||||
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(mapped).GetItemCount(), index + 1) << index;
|
||||
}
|
||||
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(0).GetItemCount(), 3);
|
||||
}
|
||||
|
||||
TEST_F(InventorySync, IgnoresOutOfRangeInventoryIndices)
|
||||
{
|
||||
Full();
|
||||
const auto before = inventory.GetPlayerInventory()->GetSlots();
|
||||
PlayerSlot(-1, Item(2));
|
||||
PlayerSlot(41, Item(2));
|
||||
PlayerSlot(65536, Item(2));
|
||||
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlots().size(), before.size());
|
||||
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(0).GetItemCount(), 3);
|
||||
}
|
||||
|
||||
TEST_F(InventorySync, CursorPacketNeverOverwritesTheSelectedHotbar)
|
||||
{
|
||||
Full();
|
||||
ClientboundSetCursorItemPacket packet;
|
||||
packet.SetContents(Item(5));
|
||||
packet.Dispatch(&inventory);
|
||||
EXPECT_EQ(inventory.GetCursor().GetItemCount(), 5);
|
||||
EXPECT_EQ(inventory.GetHotbarSelected().GetItemCount(), 8);
|
||||
packet.SetContents(Slot());
|
||||
packet.Dispatch(&inventory);
|
||||
EXPECT_TRUE(inventory.GetCursor().IsEmptySlot());
|
||||
EXPECT_EQ(inventory.GetHotbarSelected().GetItemCount(), 8);
|
||||
}
|
||||
|
||||
TEST_F(InventorySync, FullResyncUpdatesAndClearsCursor)
|
||||
{
|
||||
Full(Item(4));
|
||||
EXPECT_EQ(inventory.GetCursor().GetItemCount(), 4);
|
||||
Full();
|
||||
EXPECT_TRUE(inventory.GetCursor().IsEmptySlot());
|
||||
EXPECT_EQ(inventory.GetPlayerInventory()->GetStateId(), 7);
|
||||
}
|
||||
|
||||
TEST_F(InventorySync, SwapWithEmptyHotbarAndDropClearBothUseAuthoritativeUpdates)
|
||||
{
|
||||
Full();
|
||||
PlayerSlot(0, Slot());
|
||||
PlayerSlot(9, Item(16));
|
||||
auto window = inventory.GetPlayerInventory();
|
||||
ASSERT_TRUE(window->GetSlot(36).IsEmptySlot());
|
||||
// Server reports swb 1 1 1: storage becomes empty, hotbar receives its stack.
|
||||
PlayerSlot(9, Slot());
|
||||
PlayerSlot(0, Item(16));
|
||||
EXPECT_TRUE(window->GetSlot(9).IsEmptySlot());
|
||||
EXPECT_EQ(window->GetSlot(36).GetItemCount(), 16);
|
||||
// Then drop all: an empty authoritative slot, not a stale sixteen-item stack.
|
||||
PlayerSlot(0, Slot());
|
||||
EXPECT_TRUE(Bilicraft::ReadDropSlot(*window, 36).IsEmptySlot());
|
||||
}
|
||||
|
||||
TEST_F(InventorySync, LegacyDirectInventoryUpdatesUseSameIndexMapping)
|
||||
{
|
||||
Full();
|
||||
ClientboundContainerSetSlotPacket packet;
|
||||
packet.SetContainerId(-2);
|
||||
packet.SetStateId(9);
|
||||
packet.SetSlot(9);
|
||||
packet.SetItemStack(Item(12));
|
||||
packet.Dispatch(&inventory);
|
||||
EXPECT_EQ(inventory.GetPlayerInventory()->GetSlot(9).GetItemCount(), 12);
|
||||
EXPECT_TRUE(inventory.GetPlayerInventory()->GetSlot(18).IsEmptySlot());
|
||||
}
|
||||
|
||||
TEST_F(InventorySync, FullPacketWireRoundTripClearsPreviouslyOccupiedHotbar)
|
||||
{
|
||||
Full(Item(4));
|
||||
ClientboundContainerSetContentPacket sent, received;
|
||||
sent.SetContainerId(0);
|
||||
sent.SetStateId(8);
|
||||
sent.SetCarriedItem(Slot());
|
||||
std::vector<Slot> contents(46);
|
||||
// Reuse the receive object across occupied and empty updates, like a packet replay.
|
||||
for (int count : {8, 0})
|
||||
{
|
||||
contents[36] = count == 0 ? Slot() : Item(count);
|
||||
sent.SetItems(contents);
|
||||
WriteContainer wire;
|
||||
sent.Write(wire);
|
||||
auto iter = wire.cbegin();
|
||||
std::size_t remaining = wire.size();
|
||||
ASSERT_EQ(ReadData<VarInt>(iter, remaining), sent.GetId());
|
||||
received.Read(iter, remaining);
|
||||
ASSERT_EQ(remaining, 0U);
|
||||
received.Dispatch(&inventory);
|
||||
EXPECT_EQ(inventory.GetHotbarSelected().GetItemCount(), count);
|
||||
EXPECT_EQ(inventory.GetHotbarSelected().IsEmptySlot(), count == 0);
|
||||
EXPECT_TRUE(inventory.GetCursor().IsEmptySlot());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(InventorySync, SwapEmptyBackpackIntoOccupiedHotbarAndThenBothEmpty)
|
||||
{
|
||||
Full();
|
||||
auto window = inventory.GetPlayerInventory();
|
||||
ASSERT_TRUE(window->GetSlot(9).IsEmptySlot());
|
||||
PlayerSlot(9, Item(8));
|
||||
PlayerSlot(0, Slot());
|
||||
EXPECT_EQ(window->GetSlot(9).GetItemCount(), 8);
|
||||
EXPECT_TRUE(window->GetSlot(36).IsEmptySlot());
|
||||
PlayerSlot(9, Slot());
|
||||
EXPECT_TRUE(window->GetSlot(9).IsEmptySlot());
|
||||
EXPECT_TRUE(window->GetSlot(36).IsEmptySlot());
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,275 @@
|
||||
#include "EntityInteraction.h"
|
||||
|
||||
#include <array>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "botcraft/Game/Entities/EntityManager.hpp"
|
||||
#include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp"
|
||||
#include "botcraft/Game/Entities/entities/decoration/painting/PaintingEntity.hpp"
|
||||
#include "botcraft/Game/Enums.hpp"
|
||||
#include "protocolCraft/Packets/Game/Clientbound/ClientboundAddEntityPacket.hpp"
|
||||
#include "protocolCraft/Packets/Game/Clientbound/ClientboundSetEntityDataPacket.hpp"
|
||||
#include "protocolCraft/Packets/Game/Clientbound/ClientboundEntityPositionSyncPacket.hpp"
|
||||
#include "protocolCraft/Packets/Game/Clientbound/ClientboundTeleportEntityPacket.hpp"
|
||||
|
||||
static_assert(PROTOCOL_VERSION == 774, "Spawn/metadata replay fixtures describe Minecraft 1.21.11");
|
||||
|
||||
namespace
|
||||
{
|
||||
using Botcraft::EntityType;
|
||||
using namespace ProtocolCraft;
|
||||
|
||||
constexpr int EntityId = 715;
|
||||
const UUID EntityUuid{0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80,
|
||||
0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, 0x01};
|
||||
// Direction 3D data order: Down, Up, North, South, West, East.
|
||||
const std::array<Botcraft::Position, 6> Normals{{{0, -1, 0}, {0, 1, 0}, {0, 0, -1},
|
||||
{0, 0, 1}, {-1, 0, 0}, {1, 0, 0}}};
|
||||
|
||||
Bilicraft::ActionCommand SupportFor(int direction)
|
||||
{
|
||||
Bilicraft::ActionCommand command{};
|
||||
command.kind = Bilicraft::ActionKind::RightClick;
|
||||
command.entity = true;
|
||||
command.x = -17 - Normals[direction].x;
|
||||
command.y = 64 - Normals[direction].y;
|
||||
command.z = -31 - Normals[direction].z;
|
||||
return command;
|
||||
}
|
||||
|
||||
// Exercise the public packet dispatch path, including VarInt decoding, rather
|
||||
// than bypassing EntityManager with direct frame setters or an exposed Handle.
|
||||
void Spawn(Botcraft::EntityManager &manager, EntityType type, int data)
|
||||
{
|
||||
ClientboundAddEntityPacket sent, received;
|
||||
sent.SetEntityId(EntityId);
|
||||
sent.SetUuid(EntityUuid);
|
||||
sent.SetType(static_cast<int>(type));
|
||||
sent.SetX(-17.0);
|
||||
sent.SetY(64.0);
|
||||
sent.SetZ(-31.0);
|
||||
LpVec3 movement;
|
||||
movement.SetX(0.0);
|
||||
movement.SetY(0.0);
|
||||
movement.SetZ(0.0);
|
||||
sent.SetMovement(movement);
|
||||
// Deliberately unrelated angles: facing must come from Data.
|
||||
sent.SetXRot(32);
|
||||
sent.SetYRot(64);
|
||||
sent.SetYHeadRot(128);
|
||||
sent.SetData(data);
|
||||
WriteContainer wire;
|
||||
sent.Write(wire);
|
||||
auto iter = wire.cbegin();
|
||||
std::size_t remaining = wire.size();
|
||||
ASSERT_EQ(ReadData<VarInt>(iter, remaining), sent.GetId());
|
||||
received.Read(iter, remaining);
|
||||
ASSERT_EQ(remaining, 0U);
|
||||
received.Dispatch(&manager);
|
||||
}
|
||||
|
||||
void MetadataDirection(Botcraft::EntityManager &manager, int direction)
|
||||
{
|
||||
// Official 1.21.11 HangingEntity DATA_DIRECTION: index 8, DIRECTION=12.
|
||||
// This decodes to Botcraft::Direction in std::any, NOT an int serializer.
|
||||
// Use the real manager metadata path so later authoritative updates must
|
||||
// override the initial spawn value, including the invalid-data sentinel.
|
||||
WriteContainer packed;
|
||||
WriteData<unsigned char>(8, packed);
|
||||
WriteData<VarInt>(12, packed);
|
||||
WriteData<VarInt>(direction, packed);
|
||||
WriteData<unsigned char>(0xff, packed);
|
||||
ClientboundSetEntityDataPacket sent, received;
|
||||
sent.SetEntityId(EntityId);
|
||||
sent.SetPackedItems(packed);
|
||||
WriteContainer wire;
|
||||
sent.Write(wire);
|
||||
auto iter = wire.cbegin();
|
||||
std::size_t remaining = wire.size();
|
||||
ASSERT_EQ(ReadData<VarInt>(iter, remaining), sent.GetId());
|
||||
received.Read(iter, remaining);
|
||||
ASSERT_EQ(remaining, 0U);
|
||||
received.Dispatch(&manager);
|
||||
}
|
||||
|
||||
void ExpectSpawnFields(const Botcraft::Entity &entity, EntityType type)
|
||||
{
|
||||
EXPECT_EQ(entity.GetType(), type);
|
||||
EXPECT_EQ(entity.GetEntityID(), EntityId);
|
||||
EXPECT_EQ(entity.GetUUID(), EntityUuid);
|
||||
// The packet contains the attachment cell, not a rendered frame center.
|
||||
EXPECT_DOUBLE_EQ(entity.GetX(), -17.0);
|
||||
EXPECT_DOUBLE_EQ(entity.GetY(), 64.0);
|
||||
EXPECT_DOUBLE_EQ(entity.GetZ(), -31.0);
|
||||
EXPECT_FLOAT_EQ(entity.GetYaw(), 90.0f);
|
||||
EXPECT_FLOAT_EQ(entity.GetPitch(), 45.0f);
|
||||
EXPECT_DOUBLE_EQ(entity.GetSpeed().x, 0.0);
|
||||
EXPECT_DOUBLE_EQ(entity.GetSpeed().y, 0.0);
|
||||
EXPECT_DOUBLE_EQ(entity.GetSpeed().z, 0.0);
|
||||
}
|
||||
|
||||
class ItemFrameSpawn : public testing::TestWithParam<EntityType>
|
||||
{
|
||||
protected:
|
||||
Botcraft::EntityManager manager{nullptr}; // Offline packet replay; no connection.
|
||||
|
||||
std::shared_ptr<Botcraft::ItemFrameEntity> Frame() const
|
||||
{
|
||||
return std::dynamic_pointer_cast<Botcraft::ItemFrameEntity>(manager.GetEntity(EntityId));
|
||||
}
|
||||
};
|
||||
|
||||
TEST_P(ItemFrameSpawn, AllSixDirectionsAreAvailableImmediatelyWithoutMetadata)
|
||||
{
|
||||
for (int direction = 0; direction < 6; ++direction)
|
||||
{
|
||||
SCOPED_TRACE(direction);
|
||||
Spawn(manager, GetParam(), direction);
|
||||
const auto frame = Frame();
|
||||
ASSERT_NE(frame, nullptr);
|
||||
EXPECT_EQ(frame->GetDataDirection(), direction);
|
||||
ExpectSpawnFields(*frame, GetParam());
|
||||
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(direction)), frame);
|
||||
// Before the fix, non-South frames were selected on this WRONG block.
|
||||
for (int other = 0; other < 6; ++other)
|
||||
{
|
||||
if (other != direction)
|
||||
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(other)), nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Packet>
|
||||
void PositionRoundTrip(Packet &sent, Botcraft::EntityManager &manager)
|
||||
{
|
||||
WriteContainer bytes;
|
||||
sent.Write(bytes);
|
||||
auto iter = bytes.cbegin();
|
||||
std::size_t remaining = bytes.size();
|
||||
ASSERT_EQ(ReadData<VarInt>(iter, remaining), sent.GetId());
|
||||
Packet received;
|
||||
received.Read(iter, remaining);
|
||||
ASSERT_EQ(remaining, 0U);
|
||||
received.Dispatch(&manager);
|
||||
}
|
||||
|
||||
TEST_P(ItemFrameSpawn, AbsoluteCenterUpdatesPreserveTargetAndTeleportChangesSupport)
|
||||
{
|
||||
for (int direction = 0; direction < 6; ++direction)
|
||||
{
|
||||
SCOPED_TRACE(direction);
|
||||
Spawn(manager, GetParam(), direction);
|
||||
const auto frame = Frame();
|
||||
auto command = SupportFor(direction);
|
||||
const auto center = Bilicraft::ItemFrameCenter(*frame);
|
||||
PositionMoveRotation values;
|
||||
values.SetPosition({center.x, center.y, center.z});
|
||||
values.SetDeltaMovement({0.0, 0.0, 0.0});
|
||||
values.SetYRot(0.0f);
|
||||
values.SetXRot(0.0f);
|
||||
ClientboundEntityPositionSyncPacket sync;
|
||||
sync.SetEntityId(EntityId);
|
||||
sync.SetValues(values);
|
||||
sync.SetOnGround(false);
|
||||
PositionRoundTrip(sync, manager);
|
||||
EXPECT_EQ(Bilicraft::FindItemFrame(manager, command), frame);
|
||||
EXPECT_NO_THROW({
|
||||
const auto actual = Bilicraft::ItemFrameCenter(*frame);
|
||||
EXPECT_DOUBLE_EQ(actual.x, center.x);
|
||||
EXPECT_DOUBLE_EQ(actual.y, center.y);
|
||||
EXPECT_DOUBLE_EQ(actual.z, center.z);
|
||||
});
|
||||
|
||||
values.SetPosition({center.x + 16.0, center.y, center.z});
|
||||
ClientboundTeleportEntityPacket teleport;
|
||||
teleport.SetEntityId(EntityId);
|
||||
teleport.SetChange(values);
|
||||
teleport.SetRelatives(0);
|
||||
teleport.SetOnGround(false);
|
||||
PositionRoundTrip(teleport, manager);
|
||||
EXPECT_EQ(Bilicraft::FindItemFrame(manager, command), nullptr);
|
||||
command.x += 16;
|
||||
EXPECT_EQ(Bilicraft::FindItemFrame(manager, command), frame);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_P(ItemFrameSpawn, UnrelatedMetadataDoesNotResetSpawnDirection)
|
||||
{
|
||||
Spawn(manager, GetParam(), 2); // North, not the constructor's South default.
|
||||
const auto frame = Frame();
|
||||
ASSERT_NE(frame, nullptr);
|
||||
ClientboundSetEntityDataPacket packet;
|
||||
packet.SetEntityId(EntityId);
|
||||
// ItemFrame item rotation: metadata index 10, serializer INT=1, rotation 3.
|
||||
packet.SetPackedItems({10, 1, 3, 0xff});
|
||||
packet.Dispatch(&manager);
|
||||
EXPECT_EQ(frame->GetDataDirection(), 2);
|
||||
EXPECT_EQ(frame->GetDataRotation(), 3);
|
||||
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(2)), frame);
|
||||
}
|
||||
|
||||
TEST_P(ItemFrameSpawn, LaterDirectionMetadataOverridesSpawnWithoutChangingIdentityOrPosition)
|
||||
{
|
||||
Spawn(manager, GetParam(), 2);
|
||||
const auto frame = Frame();
|
||||
ASSERT_NE(frame, nullptr);
|
||||
for (int direction = 0; direction < 6; ++direction)
|
||||
{
|
||||
SCOPED_TRACE(direction);
|
||||
MetadataDirection(manager, direction);
|
||||
EXPECT_EQ(Frame(), frame);
|
||||
EXPECT_EQ(frame->GetDataDirection(), direction);
|
||||
ExpectSpawnFields(*frame, GetParam());
|
||||
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(direction)), frame);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_P(ItemFrameSpawn, InvalidSpawnDataNeverAliasesAValidFaceAndMetadataCanRecover)
|
||||
{
|
||||
for (int data : {-1, 6, 255, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()})
|
||||
{
|
||||
SCOPED_TRACE(data);
|
||||
Spawn(manager, GetParam(), data);
|
||||
const auto frame = Frame();
|
||||
ASSERT_NE(frame, nullptr);
|
||||
EXPECT_EQ(frame->GetDataDirection(), -1);
|
||||
ExpectSpawnFields(*frame, GetParam());
|
||||
for (int direction = 0; direction < 6; ++direction)
|
||||
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(direction)), nullptr);
|
||||
EXPECT_THROW(Bilicraft::ItemFrameCenter(*frame), std::runtime_error);
|
||||
MetadataDirection(manager, 4);
|
||||
EXPECT_EQ(frame->GetDataDirection(), 4);
|
||||
EXPECT_EQ(Bilicraft::FindItemFrame(manager, SupportFor(4)), frame);
|
||||
}
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(OrdinaryAndGlow, ItemFrameSpawn,
|
||||
testing::Values(EntityType::ItemFrame, EntityType::GlowItemFrame));
|
||||
|
||||
TEST(ItemFrameSpawnOtherEntities, DoesNotInterpretOtherEntitiesDataAsFrameDirection)
|
||||
{
|
||||
Botcraft::EntityManager manager{nullptr};
|
||||
for (const auto type : {EntityType::Painting, EntityType::ItemEntity})
|
||||
{
|
||||
for (int data : {0, 5, 6, -1})
|
||||
{
|
||||
SCOPED_TRACE(static_cast<int>(type));
|
||||
SCOPED_TRACE(data);
|
||||
Spawn(manager, type, data);
|
||||
const auto entity = manager.GetEntity(EntityId);
|
||||
ASSERT_NE(entity, nullptr);
|
||||
ExpectSpawnFields(*entity, type);
|
||||
EXPECT_EQ(std::dynamic_pointer_cast<Botcraft::ItemFrameEntity>(entity), nullptr);
|
||||
if (type == EntityType::Painting)
|
||||
{
|
||||
const auto painting = std::dynamic_pointer_cast<Botcraft::PaintingEntity>(entity);
|
||||
ASSERT_NE(painting, nullptr);
|
||||
EXPECT_EQ(painting->GetDataDirection(), static_cast<int>(Botcraft::Direction::South));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,466 @@
|
||||
#include "LineEditor.h"
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Bilicraft::LineEditor;
|
||||
constexpr std::string_view Up = "\x1b[A";
|
||||
constexpr std::string_view Down = "\x1b[B";
|
||||
constexpr std::string_view Left = "\x1b[D";
|
||||
constexpr std::string_view Right = "\x1b[C";
|
||||
constexpr std::string_view Home = "\x1b[H";
|
||||
constexpr std::string_view End = "\x1b[F";
|
||||
constexpr std::string_view Delete = "\x1b[3~";
|
||||
const std::string Chinese = "\xe4\xb8\xad\xe6\x96\x87";
|
||||
const std::string Emoji = "\xf0\x9f\x8c\xb1";
|
||||
|
||||
void Type(LineEditor &editor, std::string_view bytes)
|
||||
{
|
||||
for (const char byte : bytes)
|
||||
EXPECT_FALSE(editor.Feed(byte));
|
||||
}
|
||||
|
||||
void Submit(LineEditor &editor, std::string_view text)
|
||||
{
|
||||
Type(editor, text);
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>(text));
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, EmptyEditorAndEmptySubmission)
|
||||
{
|
||||
LineEditor editor;
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
EXPECT_FALSE(editor.IsEof());
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>(""));
|
||||
Type(editor, Up);
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, SubmitsOneLineAtATimeAndClearsText)
|
||||
{
|
||||
LineEditor editor;
|
||||
std::vector<std::string> lines;
|
||||
for (const char byte : std::string("one\ntwo\rthree\r\nfour\n"))
|
||||
if (auto line = editor.Feed(byte))
|
||||
lines.push_back(*line);
|
||||
EXPECT_EQ(lines, (std::vector<std::string>{"one", "two", "three", "four"}));
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, CrLfSuppressionPersistsAcrossRequestBoundaries)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "one");
|
||||
EXPECT_EQ(editor.Feed('\r'), std::optional<std::string>("one"));
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
// No further input is fed until the next request is allowed.
|
||||
EXPECT_FALSE(editor.Feed('\n'));
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>(""));
|
||||
EXPECT_EQ(editor.Feed('\r'), std::optional<std::string>(""));
|
||||
Type(editor, "x");
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("x"));
|
||||
EXPECT_EQ(editor.Feed('\r'), std::optional<std::string>(""));
|
||||
EXPECT_EQ(editor.Feed('\r'), std::optional<std::string>(""));
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, HistoryBrowsesBothDirectionsAndClampsAtEnds)
|
||||
{
|
||||
LineEditor editor;
|
||||
Submit(editor, "one");
|
||||
Submit(editor, "two");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "two");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "one");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "one");
|
||||
Type(editor, Down);
|
||||
EXPECT_EQ(editor.Text(), "two");
|
||||
Type(editor, Down);
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
Type(editor, Down);
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, HistoryRestoresDraftAndItsUtf8Cursor)
|
||||
{
|
||||
LineEditor editor;
|
||||
Submit(editor, "old");
|
||||
Type(editor, "a" + Chinese + "z");
|
||||
Type(editor, Left);
|
||||
Type(editor, Left);
|
||||
const auto expectedText = editor.Text();
|
||||
const auto expectedCursor = editor.Cursor();
|
||||
ASSERT_EQ(expectedCursor, 4U);
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "old");
|
||||
Type(editor, Down);
|
||||
EXPECT_EQ(editor.Text(), expectedText);
|
||||
EXPECT_EQ(editor.Cursor(), expectedCursor);
|
||||
Type(editor, "!");
|
||||
Type(editor, Up);
|
||||
Type(editor, Down);
|
||||
EXPECT_EQ(editor.Text(), "a" + Chinese.substr(0, 3) + "!" + Chinese.substr(3) + "z");
|
||||
EXPECT_EQ(editor.Cursor(), expectedCursor + 1);
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, EditingRecalledLineDoesNotMutateHistory)
|
||||
{
|
||||
LineEditor editor;
|
||||
Submit(editor, "first");
|
||||
Submit(editor, "second");
|
||||
Type(editor, Up);
|
||||
Type(editor, " changed");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "first");
|
||||
Type(editor, Down);
|
||||
EXPECT_EQ(editor.Text(), "second");
|
||||
Type(editor, Down);
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, SubmittingEditedHistoryAddsNewEntryAndResetsDraft)
|
||||
{
|
||||
LineEditor editor;
|
||||
Submit(editor, "original");
|
||||
Type(editor, "draft");
|
||||
Type(editor, Up);
|
||||
Type(editor, "!");
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("original!"));
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "original!");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "original");
|
||||
Type(editor, Down);
|
||||
Type(editor, Down);
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, IgnoresWhitespaceHistoryAndOnlyDeduplicatesConsecutiveEntries)
|
||||
{
|
||||
LineEditor editor;
|
||||
Submit(editor, "alpha");
|
||||
Submit(editor, "alpha");
|
||||
Submit(editor, " \t ");
|
||||
Submit(editor, "");
|
||||
Submit(editor, "alpha");
|
||||
Submit(editor, "beta");
|
||||
Submit(editor, "alpha");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "alpha");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "beta");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "alpha");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "alpha");
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, HistoryPreservesNonblankWhitespaceExactly)
|
||||
{
|
||||
LineEditor editor;
|
||||
Submit(editor, " command\t ");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), " command\t ");
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, HistoryRetainsOnlyLatestTwoHundredEntries)
|
||||
{
|
||||
LineEditor editor;
|
||||
for (std::size_t index = 0; index < LineEditor::MaxHistoryEntries + 7; ++index)
|
||||
Submit(editor, "entry" + std::to_string(index));
|
||||
for (std::size_t index = 0; index < LineEditor::MaxHistoryEntries + 10; ++index)
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "entry7");
|
||||
Type(editor, Down);
|
||||
EXPECT_EQ(editor.Text(), "entry8");
|
||||
for (std::size_t index = 0; index < LineEditor::MaxHistoryEntries; ++index)
|
||||
Type(editor, Down);
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
Submit(editor, "new");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "new");
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, HistoryIsLocalToEachEditor)
|
||||
{
|
||||
LineEditor first;
|
||||
Submit(first, "private");
|
||||
LineEditor second;
|
||||
Type(second, Up);
|
||||
EXPECT_TRUE(second.Text().empty());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, FragmentedCsiAndSs3ArrowsAreNotInserted)
|
||||
{
|
||||
LineEditor editor;
|
||||
Submit(editor, "first");
|
||||
Submit(editor, "second");
|
||||
EXPECT_FALSE(editor.Feed('\x1b'));
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
EXPECT_FALSE(editor.Feed('['));
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
EXPECT_FALSE(editor.Feed('A'));
|
||||
EXPECT_EQ(editor.Text(), "second");
|
||||
EXPECT_FALSE(editor.Feed('\x1b'));
|
||||
EXPECT_FALSE(editor.Feed('O'));
|
||||
EXPECT_EQ(editor.Text(), "second");
|
||||
EXPECT_FALSE(editor.Feed('A'));
|
||||
EXPECT_EQ(editor.Text(), "first");
|
||||
Type(editor, "\x1bOB");
|
||||
EXPECT_EQ(editor.Text(), "second");
|
||||
Type(editor, "\x1bOB");
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, InsertDeleteAndBackspaceAtAsciiCursor)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "ac");
|
||||
Type(editor, Left);
|
||||
Type(editor, "b");
|
||||
EXPECT_EQ(editor.Text(), "abc");
|
||||
EXPECT_EQ(editor.Cursor(), 2U);
|
||||
Type(editor, Delete);
|
||||
EXPECT_EQ(editor.Text(), "ab");
|
||||
Type(editor, "\x7f");
|
||||
EXPECT_EQ(editor.Text(), "a");
|
||||
Type(editor, "\x08");
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
Type(editor, "\x08\x7f");
|
||||
Type(editor, Delete);
|
||||
Type(editor, Left);
|
||||
Type(editor, Right);
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, Utf8CodepointsAreInsertedAtomicallyAndEditedAtByteBoundaries)
|
||||
{
|
||||
LineEditor editor;
|
||||
EXPECT_FALSE(editor.Feed(Chinese[0]));
|
||||
EXPECT_FALSE(editor.Feed(Chinese[1]));
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
EXPECT_FALSE(editor.Feed(Chinese[2]));
|
||||
EXPECT_EQ(editor.Text(), Chinese.substr(0, 3));
|
||||
Type(editor, Chinese.substr(3) + Emoji);
|
||||
EXPECT_EQ(editor.Cursor(), 10U);
|
||||
Type(editor, Left);
|
||||
EXPECT_EQ(editor.Cursor(), 6U);
|
||||
Type(editor, Left);
|
||||
EXPECT_EQ(editor.Cursor(), 3U);
|
||||
Type(editor, Delete);
|
||||
EXPECT_EQ(editor.Text(), Chinese.substr(0, 3) + Emoji);
|
||||
Type(editor, "\x7f");
|
||||
EXPECT_EQ(editor.Text(), Emoji);
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
Type(editor, Right);
|
||||
EXPECT_EQ(editor.Cursor(), 4U);
|
||||
Type(editor, "\x08");
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, MovementClampsAndSupportsAllCommonHomeEndForms)
|
||||
{
|
||||
for (const auto home : {Home, std::string_view("\x1bOH"), std::string_view("\x1b[1~"), std::string_view("\x1b[7~")})
|
||||
{
|
||||
for (const auto end :
|
||||
{End, std::string_view("\x1bOF"), std::string_view("\x1b[4~"), std::string_view("\x1b[8~")})
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, Chinese);
|
||||
Type(editor, home);
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
Type(editor, Left);
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
Type(editor, end);
|
||||
EXPECT_EQ(editor.Cursor(), Chinese.size());
|
||||
Type(editor, Right);
|
||||
EXPECT_EQ(editor.Cursor(), Chinese.size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, Ss3LeftRightMoveByCodepoint)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, Chinese);
|
||||
Type(editor, "\x1bOD");
|
||||
EXPECT_EQ(editor.Cursor(), 3U);
|
||||
Type(editor, "\x1bOC");
|
||||
EXPECT_EQ(editor.Cursor(), 6U);
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, CtrlAEndKillAndClearRespectCursor)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "a" + Chinese + "z");
|
||||
Type(editor, "\x01");
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
Type(editor, Right);
|
||||
Type(editor, Right);
|
||||
Type(editor, "\x15");
|
||||
EXPECT_EQ(editor.Text(), Chinese.substr(3) + "z");
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
Type(editor, Right);
|
||||
Type(editor, "\x0b");
|
||||
EXPECT_EQ(editor.Text(), Chinese.substr(3));
|
||||
Type(editor, "\x05");
|
||||
EXPECT_EQ(editor.Cursor(), 3U);
|
||||
Type(editor, "\x15");
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, CtrlDEmptyLatchesEofAndFutureInputIsIgnored)
|
||||
{
|
||||
LineEditor editor;
|
||||
EXPECT_FALSE(editor.Feed('\x04'));
|
||||
EXPECT_TRUE(editor.IsEof());
|
||||
Type(editor, "ignored\n\r\x1b[A");
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
EXPECT_EQ(editor.Cursor(), 0U);
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, CtrlDOnNonemptyLineDeletesCodepointButDoesNotSetEof)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, Chinese);
|
||||
Type(editor, "\x04");
|
||||
EXPECT_EQ(editor.Text(), Chinese);
|
||||
EXPECT_FALSE(editor.IsEof());
|
||||
Type(editor, Home);
|
||||
Type(editor, "\x04");
|
||||
EXPECT_EQ(editor.Text(), Chinese.substr(3));
|
||||
Type(editor, "\x04");
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
EXPECT_FALSE(editor.IsEof());
|
||||
Type(editor, "\x04");
|
||||
EXPECT_TRUE(editor.IsEof());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, UnknownEscapesAreSwallowedAsWholeSequences)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "safe");
|
||||
Type(editor, "\x1b[99~\x1b[?25l\x1b[1;5D\x1bOP\x1b(0\x1bz");
|
||||
EXPECT_EQ(editor.Text(), "safe");
|
||||
EXPECT_EQ(editor.Cursor(), 4U);
|
||||
Type(editor, "!");
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("safe!"));
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, OscAndControlStringsAreSwallowedThroughTheirTerminator)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "a\x1b]0;window title\x07");
|
||||
Type(editor, "b\x1bPignored [A payload\x1b\\");
|
||||
Type(editor, "c\x1b]title\x1b\\");
|
||||
EXPECT_EQ(editor.Text(), "abc");
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, OverlongEscapeHasBoundedStorageAndDoesNotLeakTail)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "safe\x1b[");
|
||||
Type(editor, std::string(10000, '1'));
|
||||
Type(editor, "~done");
|
||||
EXPECT_EQ(editor.Text(), "safedone");
|
||||
Type(editor, "\x1b]" + std::string(10000, 'x') + "\x07");
|
||||
Type(editor, "!");
|
||||
EXPECT_EQ(editor.Text(), "safedone!");
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, NewlineAndNewEscapeRecoverFromTruncatedSequences)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "ok\x1b[123");
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("ok"));
|
||||
Type(editor, "draft\x1b[12");
|
||||
Type(editor, Up);
|
||||
EXPECT_EQ(editor.Text(), "ok");
|
||||
Type(editor, Down);
|
||||
EXPECT_EQ(editor.Text(), "draft");
|
||||
Type(editor, "\x1b]unterminated");
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("draft"));
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, MalformedUtf8IsDiscardedAndAsciiInputRecovers)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "\x80\xbf\xc0\xaf\xf5\xff\xe0\x80\x80\xed\xa0\x80\xf4\x90\x80\x80");
|
||||
EXPECT_TRUE(editor.Text().empty());
|
||||
Type(editor, "\xe4");
|
||||
Type(editor, "valid");
|
||||
EXPECT_EQ(editor.Text(), "valid");
|
||||
Type(editor, "\xe4\xb8");
|
||||
Type(editor, Left);
|
||||
Type(editor, "!");
|
||||
EXPECT_EQ(editor.Text(), "vali!d");
|
||||
EXPECT_EQ(editor.Cursor(), 5U);
|
||||
Type(editor, "\xe4\xb8");
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>("vali!d"));
|
||||
Type(editor, "next");
|
||||
EXPECT_EQ(editor.Text(), "next");
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, InvalidDecoderPrefixCanBeFollowedByNewValidCodepoint)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "\xe4" + Emoji + "\xe4\xb8" + Chinese);
|
||||
EXPECT_EQ(editor.Text(), Emoji + Chinese);
|
||||
EXPECT_EQ(editor.Cursor(), Emoji.size() + Chinese.size());
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, EmbeddedNulAndUnsupportedControlsAreNotStored)
|
||||
{
|
||||
LineEditor editor;
|
||||
Type(editor, "a");
|
||||
EXPECT_FALSE(editor.Feed('\0'));
|
||||
Type(editor, "\x02\x03\x06\x0c");
|
||||
Type(editor, "b");
|
||||
EXPECT_EQ(editor.Text(), "ab");
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, ExactLineLimitAcceptedAndOverflowCanRecoverByEditing)
|
||||
{
|
||||
LineEditor editor;
|
||||
const std::string full(LineEditor::MaxLineBytes, 'x');
|
||||
Type(editor, full);
|
||||
EXPECT_EQ(editor.Text(), full);
|
||||
EXPECT_THROW(editor.Feed('y'), std::length_error);
|
||||
EXPECT_EQ(editor.Text(), full);
|
||||
EXPECT_EQ(editor.Cursor(), full.size());
|
||||
EXPECT_FALSE(editor.IsEof());
|
||||
Type(editor, "\x7f");
|
||||
Type(editor, "y");
|
||||
EXPECT_EQ(editor.Feed('\n'), std::optional<std::string>(full.substr(1) + "y"));
|
||||
Submit(editor, "next");
|
||||
}
|
||||
|
||||
TEST(LineEditorTest, Utf8OverflowIsAtomicAndDecoderRecovers)
|
||||
{
|
||||
LineEditor editor;
|
||||
const std::string prefix(LineEditor::MaxLineBytes - 2, 'x');
|
||||
Type(editor, prefix);
|
||||
EXPECT_FALSE(editor.Feed(Chinese[0]));
|
||||
EXPECT_FALSE(editor.Feed(Chinese[1]));
|
||||
EXPECT_THROW(editor.Feed(Chinese[2]), std::length_error);
|
||||
EXPECT_EQ(editor.Text(), prefix);
|
||||
EXPECT_EQ(editor.Cursor(), prefix.size());
|
||||
Type(editor, "\x7f");
|
||||
Type(editor, Chinese.substr(0, 3));
|
||||
EXPECT_EQ(editor.Text().size(), LineEditor::MaxLineBytes);
|
||||
EXPECT_EQ(editor.Cursor(), LineEditor::MaxLineBytes);
|
||||
Type(editor, "\x7f");
|
||||
EXPECT_EQ(editor.Text(), prefix.substr(1));
|
||||
}
|
||||
} // namespace
|
||||
@@ -0,0 +1,439 @@
|
||||
#include "TerminalConsole.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <csignal>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/wait.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Bilicraft::TerminalConsole;
|
||||
|
||||
void Put(int fd, std::string_view text)
|
||||
{
|
||||
while (!text.empty())
|
||||
{
|
||||
const auto count = write(fd, text.data(), text.size());
|
||||
if (count < 0 && errno == EINTR) continue;
|
||||
if (count <= 0) throw std::runtime_error("test write failed");
|
||||
text.remove_prefix(static_cast<std::size_t>(count));
|
||||
}
|
||||
}
|
||||
|
||||
std::string Drain(int fd)
|
||||
{
|
||||
std::string result;
|
||||
char bytes[2048];
|
||||
for (;;)
|
||||
{
|
||||
const auto count = read(fd, bytes, sizeof(bytes));
|
||||
if (count > 0) result.append(bytes, static_cast<std::size_t>(count));
|
||||
else if (count < 0 && errno == EINTR) continue;
|
||||
else break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
class Pipe
|
||||
{
|
||||
public:
|
||||
Pipe()
|
||||
{
|
||||
if (pipe(fds) != 0) throw std::runtime_error("pipe failed");
|
||||
if (fcntl(fds[0], F_SETFL, O_NONBLOCK) < 0) throw std::runtime_error("fcntl failed");
|
||||
}
|
||||
~Pipe() { if (fds[0] >= 0) close(fds[0]); if (fds[1] >= 0) close(fds[1]); }
|
||||
void CloseWriter() { close(fds[1]); fds[1] = -1; }
|
||||
int fds[2]{-1, -1};
|
||||
};
|
||||
|
||||
class Pty : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
void SetUp() override
|
||||
{
|
||||
if (const char *value = std::getenv("TERM")) oldTerm = value;
|
||||
ASSERT_EQ(setenv("TERM", "xterm-256color", 1), 0);
|
||||
master = posix_openpt(O_RDWR | O_NOCTTY | O_NONBLOCK);
|
||||
if (master < 0) GTEST_SKIP() << "No POSIX PTY available";
|
||||
ASSERT_EQ(grantpt(master), 0);
|
||||
ASSERT_EQ(unlockpt(master), 0);
|
||||
const char *name = ptsname(master);
|
||||
ASSERT_NE(name, nullptr);
|
||||
slave = open(name, O_RDWR | O_NOCTTY);
|
||||
ASSERT_GE(slave, 0);
|
||||
Size(24, 80);
|
||||
ASSERT_EQ(tcgetattr(slave, &original), 0);
|
||||
}
|
||||
void TearDown() override
|
||||
{
|
||||
if (slave >= 0) { tcsetattr(slave, TCSANOW, &original); close(slave); }
|
||||
if (master >= 0) close(master);
|
||||
if (oldTerm) setenv("TERM", oldTerm->c_str(), 1);
|
||||
else unsetenv("TERM");
|
||||
}
|
||||
void Size(unsigned short rows, unsigned short columns)
|
||||
{
|
||||
winsize size{};
|
||||
size.ws_row = rows;
|
||||
size.ws_col = columns;
|
||||
ASSERT_EQ(ioctl(slave, TIOCSWINSZ, &size), 0);
|
||||
}
|
||||
void Input(std::string_view text)
|
||||
{
|
||||
Put(master, text);
|
||||
pollfd item{slave, POLLIN, 0};
|
||||
ASSERT_GT(poll(&item, 1, 1000), 0);
|
||||
}
|
||||
int Available()
|
||||
{
|
||||
int count = -1;
|
||||
EXPECT_EQ(ioctl(slave, FIONREAD, &count), 0);
|
||||
return count;
|
||||
}
|
||||
void ExpectRestored()
|
||||
{
|
||||
termios current{};
|
||||
ASSERT_EQ(tcgetattr(slave, ¤t), 0);
|
||||
EXPECT_EQ(current.c_iflag, original.c_iflag);
|
||||
EXPECT_EQ(current.c_oflag, original.c_oflag);
|
||||
EXPECT_EQ(current.c_cflag, original.c_cflag);
|
||||
EXPECT_EQ(current.c_lflag, original.c_lflag);
|
||||
EXPECT_EQ(cfgetispeed(¤t), cfgetispeed(&original));
|
||||
EXPECT_EQ(cfgetospeed(¤t), cfgetospeed(&original));
|
||||
for (std::size_t i = 0; i < NCCS; ++i) EXPECT_EQ(current.c_cc[i], original.c_cc[i]);
|
||||
}
|
||||
int master = -1, slave = -1;
|
||||
termios original{};
|
||||
std::optional<std::string> oldTerm;
|
||||
};
|
||||
|
||||
TEST_F(Pty, PlainBeforeStartThenRawAndFullRestoration)
|
||||
{
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Out() << "login\n";
|
||||
EXPECT_EQ(Drain(master).find('\033'), std::string::npos);
|
||||
console.Start();
|
||||
ASSERT_TRUE(console.IsSplit());
|
||||
termios raw{};
|
||||
ASSERT_EQ(tcgetattr(slave, &raw), 0);
|
||||
EXPECT_EQ(raw.c_lflag & (ICANON | ECHO | IEXTEN), 0U);
|
||||
EXPECT_NE(raw.c_lflag & ISIG, 0U);
|
||||
EXPECT_EQ(raw.c_iflag & IXON, 0U);
|
||||
EXPECT_EQ(raw.c_cc[VMIN], 0);
|
||||
EXPECT_EQ(raw.c_cc[VTIME], 0);
|
||||
#ifdef VQUIT
|
||||
EXPECT_EQ(raw.c_cc[VQUIT], _POSIX_VDISABLE);
|
||||
#endif
|
||||
#ifdef VSUSP
|
||||
EXPECT_EQ(raw.c_cc[VSUSP], _POSIX_VDISABLE);
|
||||
#endif
|
||||
const auto screen = Drain(master);
|
||||
EXPECT_NE(screen.find("\033[1;22r"), std::string::npos);
|
||||
EXPECT_NE(screen.find("\033[23;1H"), std::string::npos);
|
||||
EXPECT_NE(screen.find("\033[24;1H"), std::string::npos);
|
||||
EXPECT_EQ(screen.find("?1049"), std::string::npos);
|
||||
console.Start(); // no second mode switch or duplicated prompt
|
||||
EXPECT_TRUE(Drain(master).empty());
|
||||
}
|
||||
ExpectRestored();
|
||||
const auto cleanup = Drain(master);
|
||||
EXPECT_NE(cleanup.find("\033[r"), std::string::npos);
|
||||
EXPECT_NE(cleanup.find("\033[?25h"), std::string::npos);
|
||||
EXPECT_NE(fcntl(slave, F_GETFD), -1); // borrowed descriptor is still open
|
||||
}
|
||||
|
||||
TEST_F(Pty, ExceptionUnwindingRestoresTerminal)
|
||||
{
|
||||
try
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
ASSERT_TRUE(console.IsSplit());
|
||||
throw std::runtime_error("application failure");
|
||||
}
|
||||
catch (const std::runtime_error &) {}
|
||||
ExpectRestored();
|
||||
}
|
||||
|
||||
TEST_F(Pty, BusyConsumesNothingAndSubmissionDoesNotReadAhead)
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
Drain(master);
|
||||
console.SetInputEnabled(false);
|
||||
Input("first\nsecond\n");
|
||||
const int before = Available();
|
||||
EXPECT_FALSE(console.PollLine());
|
||||
console.Tick();
|
||||
EXPECT_EQ(Available(), before);
|
||||
EXPECT_NE(Drain(master).find("busy / pending"), std::string::npos);
|
||||
console.SetInputEnabled(true);
|
||||
EXPECT_EQ(console.PollLine(), std::optional<std::string>("first"));
|
||||
EXPECT_EQ(Available(), 7);
|
||||
EXPECT_EQ(console.PollLine(), std::optional<std::string>("second"));
|
||||
}
|
||||
|
||||
TEST_F(Pty, ArrowHistoryDraftAndUnicodeRemainEditableAcrossThreadedLogs)
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
Input("old\n");
|
||||
ASSERT_EQ(console.PollLine(), std::optional<std::string>("old"));
|
||||
Input("draft\033[A");
|
||||
EXPECT_FALSE(console.PollLine());
|
||||
Drain(master);
|
||||
std::thread logger([&console] { console.WriteLog("network log\n"); });
|
||||
logger.join();
|
||||
const auto logged = Drain(master);
|
||||
EXPECT_NE(logged.find("network log"), std::string::npos);
|
||||
EXPECT_NE(logged.find(">>> old"), std::string::npos);
|
||||
Input("\033[B\n");
|
||||
EXPECT_EQ(console.PollLine(), std::optional<std::string>("draft"));
|
||||
Input("中文\033[D\177\n");
|
||||
EXPECT_EQ(console.PollLine(), std::optional<std::string>("文"));
|
||||
}
|
||||
|
||||
TEST_F(Pty, StripsFragmentedAnsiOscAndControlCharactersFromLogs)
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
Drain(master);
|
||||
console.WriteLog("before\033[");
|
||||
console.WriteLog("999;999Hafter\033]52;c;BAD");
|
||||
console.WriteLog("\aend\033Psecret\033\\\x01\n");
|
||||
const auto screen = Drain(master);
|
||||
EXPECT_NE(screen.find("before"), std::string::npos);
|
||||
EXPECT_NE(screen.find("after"), std::string::npos);
|
||||
EXPECT_NE(screen.find("end"), std::string::npos);
|
||||
EXPECT_EQ(screen.find("999;999H"), std::string::npos);
|
||||
EXPECT_EQ(screen.find("52;c;BAD"), std::string::npos);
|
||||
EXPECT_EQ(screen.find("secret"), std::string::npos);
|
||||
EXPECT_EQ(screen.find('\x01'), std::string::npos);
|
||||
EXPECT_NE(screen.find("\0338"), std::string::npos);
|
||||
EXPECT_NE(screen.find("\0337"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(Pty, MalformedLogEscapesRecoverAtNewlineAndPreserveUtf8Fragments)
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
Drain(master);
|
||||
console.WriteLog("\033]unterminated\nvisible-one\n");
|
||||
console.WriteLog("\033[12;\nvisible-two\n");
|
||||
console.WriteLog("\xe4\xb8");
|
||||
console.WriteLog("\xad\xe6\x96\x87\n");
|
||||
const auto screen = Drain(master);
|
||||
EXPECT_EQ(screen.find("unterminated"), std::string::npos);
|
||||
EXPECT_NE(screen.find("visible-one"), std::string::npos);
|
||||
EXPECT_NE(screen.find("visible-two"), std::string::npos);
|
||||
EXPECT_NE(screen.find("中文"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(Pty, RedirectedStderrContainsOnlyOriginalLogBytes)
|
||||
{
|
||||
Pipe errors;
|
||||
TerminalConsole console(slave, slave, errors.fds[1]);
|
||||
console.Start();
|
||||
Drain(master);
|
||||
console.Err() << "error " << 42 << '\n';
|
||||
EXPECT_EQ(Drain(errors.fds[0]), "error 42\n");
|
||||
EXPECT_TRUE(Drain(master).empty());
|
||||
}
|
||||
|
||||
TEST_F(Pty, BrokenRedirectedPipeDoesNotRaiseSigpipeOrPreventCleanup)
|
||||
{
|
||||
Pipe errors;
|
||||
close(errors.fds[0]);
|
||||
errors.fds[0] = -1;
|
||||
const pid_t child = fork();
|
||||
ASSERT_GE(child, 0);
|
||||
if (child == 0)
|
||||
{
|
||||
struct sigaction action{};
|
||||
action.sa_handler = SIG_DFL;
|
||||
sigemptyset(&action.sa_mask);
|
||||
sigaction(SIGPIPE, &action, nullptr);
|
||||
sigset_t mask;
|
||||
sigemptyset(&mask);
|
||||
sigaddset(&mask, SIGPIPE);
|
||||
sigprocmask(SIG_UNBLOCK, &mask, nullptr);
|
||||
{
|
||||
TerminalConsole console(slave, slave, errors.fds[1]);
|
||||
console.Start();
|
||||
console.WriteLog("closed destination\n", true);
|
||||
}
|
||||
_exit(0);
|
||||
}
|
||||
int status = 0;
|
||||
ASSERT_EQ(waitpid(child, &status, 0), child);
|
||||
ASSERT_TRUE(WIFEXITED(status));
|
||||
EXPECT_EQ(WEXITSTATUS(status), 0);
|
||||
ExpectRestored();
|
||||
}
|
||||
|
||||
TEST_F(Pty, ResizesMarginsAndClipsChineseLineWithoutWrapping)
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
Drain(master);
|
||||
Size(8, 20);
|
||||
console.Tick();
|
||||
EXPECT_NE(Drain(master).find("\033[1;6r"), std::string::npos);
|
||||
Input("中文中文中文中文中文中文中文");
|
||||
EXPECT_FALSE(console.PollLine());
|
||||
const auto narrow = Drain(master);
|
||||
// 19 usable columns - 4 prompt columns = 15; seven CJK glyphs fit.
|
||||
EXPECT_EQ(narrow.find("中文中文中文中文"), std::string::npos);
|
||||
EXPECT_NE(narrow.find("\033[8;"), std::string::npos);
|
||||
Size(2, 5);
|
||||
console.Tick();
|
||||
Drain(master);
|
||||
console.WriteLog("must not overwrite editor\n");
|
||||
EXPECT_EQ(Drain(master).find("must not overwrite editor"), std::string::npos);
|
||||
Size(30, 100);
|
||||
console.Tick();
|
||||
EXPECT_NE(Drain(master).find("\033[1;28r"), std::string::npos);
|
||||
Input("\n");
|
||||
EXPECT_EQ(console.PollLine(), std::optional<std::string>("中文中文中文中文中文中文中文"));
|
||||
}
|
||||
|
||||
TEST_F(Pty, CtrlDAndHangupLatchEof)
|
||||
{
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
Input("\004");
|
||||
EXPECT_FALSE(console.PollLine());
|
||||
EXPECT_TRUE(console.IsEof());
|
||||
EXPECT_FALSE(console.PollLine());
|
||||
}
|
||||
ExpectRestored();
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
close(master);
|
||||
master = -1;
|
||||
EXPECT_NO_THROW(console.PollLine());
|
||||
EXPECT_TRUE(console.IsEof());
|
||||
EXPECT_FALSE(console.PollLine());
|
||||
}
|
||||
|
||||
TEST_F(Pty, DumbSmallOrDifferentOutputFallsBackWithoutAnsi)
|
||||
{
|
||||
setenv("TERM", "dumb", 1);
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
EXPECT_FALSE(console.IsSplit());
|
||||
EXPECT_EQ(Drain(master), ">>> ");
|
||||
ExpectRestored();
|
||||
}
|
||||
setenv("TERM", "xterm", 1);
|
||||
Size(3, 19);
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
EXPECT_FALSE(console.IsSplit());
|
||||
EXPECT_EQ(Drain(master), ">>> ");
|
||||
ExpectRestored();
|
||||
}
|
||||
Size(24, 80);
|
||||
Pipe output;
|
||||
TerminalConsole console(slave, output.fds[1], output.fds[1]);
|
||||
console.Start();
|
||||
EXPECT_FALSE(console.IsSplit());
|
||||
EXPECT_EQ(Drain(output.fds[0]), ">>> ");
|
||||
ExpectRestored();
|
||||
}
|
||||
|
||||
volatile std::sig_atomic_t interrupted = 0;
|
||||
void NotifyInterrupt(int) { interrupted = 1; }
|
||||
|
||||
TEST_F(Pty, SigintNotificationThenNormalUnwindRestoresTermios)
|
||||
{
|
||||
int ready[2];
|
||||
ASSERT_EQ(pipe(ready), 0);
|
||||
const pid_t child = fork();
|
||||
ASSERT_GE(child, 0);
|
||||
if (child == 0)
|
||||
{
|
||||
close(ready[0]);
|
||||
sigset_t blocked, previous;
|
||||
sigemptyset(&blocked);
|
||||
sigaddset(&blocked, SIGINT);
|
||||
sigprocmask(SIG_BLOCK, &blocked, &previous);
|
||||
struct sigaction action{};
|
||||
action.sa_handler = NotifyInterrupt;
|
||||
sigemptyset(&action.sa_mask);
|
||||
sigaction(SIGINT, &action, nullptr);
|
||||
{
|
||||
TerminalConsole console(slave, slave, slave);
|
||||
console.Start();
|
||||
const char state = console.IsSplit() ? 'Y' : 'N';
|
||||
if (write(ready[1], &state, 1) != 1) _exit(3);
|
||||
while (!interrupted) sigsuspend(&previous);
|
||||
}
|
||||
_exit(0);
|
||||
}
|
||||
close(ready[1]);
|
||||
pollfd item{ready[0], POLLIN, 0};
|
||||
const int readyResult = poll(&item, 1, 3000);
|
||||
char state = 0;
|
||||
const auto count = readyResult > 0 ? read(ready[0], &state, 1) : -1;
|
||||
close(ready[0]);
|
||||
// Always reap, even if startup fails, so a failed test leaves no child.
|
||||
kill(child, count == 1 && state == 'Y' ? SIGINT : SIGKILL);
|
||||
int status = 0;
|
||||
ASSERT_EQ(waitpid(child, &status, 0), child);
|
||||
ASSERT_EQ(count, 1);
|
||||
ASSERT_EQ(state, 'Y');
|
||||
ASSERT_TRUE(WIFEXITED(status));
|
||||
EXPECT_EQ(WEXITSTATUS(status), 0);
|
||||
ExpectRestored();
|
||||
}
|
||||
|
||||
TEST(TerminalConsoleTest, PipeFallbackPromptsOnceAndNeverConsumesWhileBusy)
|
||||
{
|
||||
Pipe input, output;
|
||||
TerminalConsole console(input.fds[0], output.fds[1], output.fds[1]);
|
||||
console.Out() << "login\n";
|
||||
EXPECT_EQ(Drain(output.fds[0]), "login\n");
|
||||
console.SetInputEnabled(false);
|
||||
console.Start();
|
||||
EXPECT_FALSE(console.IsSplit());
|
||||
EXPECT_TRUE(Drain(output.fds[0]).empty());
|
||||
Put(input.fds[1], "first\nsecond\n");
|
||||
EXPECT_FALSE(console.PollLine());
|
||||
console.SetInputEnabled(true);
|
||||
console.Tick();
|
||||
console.Tick();
|
||||
EXPECT_EQ(Drain(output.fds[0]), ">>> ");
|
||||
EXPECT_EQ(console.PollLine(), std::optional<std::string>("first"));
|
||||
int remaining = 0;
|
||||
ASSERT_EQ(ioctl(input.fds[0], FIONREAD, &remaining), 0);
|
||||
EXPECT_EQ(remaining, 7);
|
||||
console.Tick();
|
||||
EXPECT_EQ(Drain(output.fds[0]), "\n>>> ");
|
||||
EXPECT_EQ(console.PollLine(), std::optional<std::string>("second"));
|
||||
input.CloseWriter();
|
||||
EXPECT_FALSE(console.PollLine());
|
||||
EXPECT_TRUE(console.IsEof());
|
||||
EXPECT_EQ(Drain(output.fds[0]).find('\033'), std::string::npos);
|
||||
}
|
||||
} // namespace
|
||||
#endif
|
||||
@@ -0,0 +1,345 @@
|
||||
#include "TerminalInput.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <Windows.h>
|
||||
#include <fcntl.h>
|
||||
#include <io.h>
|
||||
#else
|
||||
#include <fcntl.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
using Bilicraft::TerminalInput;
|
||||
|
||||
void CloseDescriptor(int fd)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
_close(fd);
|
||||
#else
|
||||
close(fd);
|
||||
#endif
|
||||
}
|
||||
|
||||
class InputPipe
|
||||
{
|
||||
public:
|
||||
InputPipe()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
if (_pipe(descriptors, 4096, _O_BINARY) != 0)
|
||||
#else
|
||||
if (pipe(descriptors) != 0)
|
||||
#endif
|
||||
throw std::runtime_error("Cannot create test pipe");
|
||||
}
|
||||
|
||||
~InputPipe()
|
||||
{
|
||||
for (const int fd : descriptors)
|
||||
if (fd >= 0)
|
||||
CloseDescriptor(fd);
|
||||
}
|
||||
|
||||
InputPipe(const InputPipe &) = delete;
|
||||
InputPipe &operator=(const InputPipe &) = delete;
|
||||
|
||||
int Reader() const
|
||||
{
|
||||
return descriptors[0];
|
||||
}
|
||||
|
||||
void CloseWriter()
|
||||
{
|
||||
CloseDescriptor(descriptors[1]);
|
||||
descriptors[1] = -1;
|
||||
}
|
||||
|
||||
void Write(std::string_view text)
|
||||
{
|
||||
// These tests only write small messages that fit into the empty pipe.
|
||||
while (!text.empty())
|
||||
{
|
||||
#ifdef _WIN32
|
||||
const auto count = _write(descriptors[1], text.data(), static_cast<unsigned>(text.size()));
|
||||
#else
|
||||
const auto count = write(descriptors[1], text.data(), text.size());
|
||||
#endif
|
||||
if (count <= 0)
|
||||
throw std::runtime_error("Cannot write test pipe");
|
||||
text.remove_prefix(static_cast<std::size_t>(count));
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t BytesAvailable() const
|
||||
{
|
||||
#ifdef _WIN32
|
||||
DWORD bytes = 0;
|
||||
if (!PeekNamedPipe(reinterpret_cast<HANDLE>(_get_osfhandle(Reader())), nullptr, 0, nullptr, &bytes, nullptr))
|
||||
#else
|
||||
int bytes = 0;
|
||||
if (ioctl(Reader(), FIONREAD, &bytes) != 0)
|
||||
#endif
|
||||
throw std::runtime_error("Cannot inspect test pipe");
|
||||
return static_cast<std::size_t>(bytes);
|
||||
}
|
||||
|
||||
private:
|
||||
int descriptors[2]{-1, -1};
|
||||
};
|
||||
|
||||
class InputFile
|
||||
{
|
||||
public:
|
||||
explicit InputFile(std::string_view text) : file(std::tmpfile())
|
||||
{
|
||||
if (!file || std::fwrite(text.data(), 1, text.size(), file.get()) != text.size() ||
|
||||
std::fflush(file.get()) != 0 || std::fseek(file.get(), 0, SEEK_SET) != 0)
|
||||
throw std::runtime_error("Cannot create test input file");
|
||||
}
|
||||
|
||||
int Descriptor() const
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return _fileno(file.get());
|
||||
#else
|
||||
return fileno(file.get());
|
||||
#endif
|
||||
}
|
||||
|
||||
private:
|
||||
struct CloseFile
|
||||
{
|
||||
void operator()(std::FILE *value) const { std::fclose(value); }
|
||||
};
|
||||
std::unique_ptr<std::FILE, CloseFile> file;
|
||||
};
|
||||
|
||||
std::optional<std::string> PollAvailableLine(TerminalInput &input)
|
||||
{
|
||||
// A call has a bounded byte budget. These files contain at most 64 KiB+1.
|
||||
for (int attempt = 0; attempt < 64 && !input.IsEof(); ++attempt)
|
||||
if (auto line = input.PollLine())
|
||||
return line;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, EmptyOpenPipeReturnsImmediatelyWithoutEof)
|
||||
{
|
||||
InputPipe pipe;
|
||||
TerminalInput input(pipe.Reader());
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::milliseconds(500));
|
||||
EXPECT_FALSE(input.IsEof());
|
||||
EXPECT_FALSE(input.IsInteractive());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, ReturnsCompleteLineWithoutWaitingForWriterToClose)
|
||||
{
|
||||
InputPipe pipe;
|
||||
TerminalInput input(pipe.Reader());
|
||||
pipe.Write("hello\n");
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("hello"));
|
||||
EXPECT_FALSE(input.IsEof());
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, DoesNotReadAnyByteOfNextLine)
|
||||
{
|
||||
InputPipe pipe;
|
||||
TerminalInput input(pipe.Reader());
|
||||
pipe.Write("first\nsecond\n");
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("first"));
|
||||
// Check the OS pipe, not just a private buffer: no read-ahead is allowed.
|
||||
EXPECT_EQ(pipe.BytesAvailable(), std::string_view("second\n").size());
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("second"));
|
||||
EXPECT_EQ(pipe.BytesAvailable(), 0U);
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, RetainsPartialLineWithoutWaitingForMoreBytes)
|
||||
{
|
||||
InputPipe pipe;
|
||||
TerminalInput input(pipe.Reader());
|
||||
pipe.Write("par");
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::milliseconds(500));
|
||||
EXPECT_FALSE(input.IsEof());
|
||||
pipe.Write("tial\nnext\n");
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("partial"));
|
||||
EXPECT_EQ(pipe.BytesAvailable(), std::string_view("next\n").size());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, ReturnsFinalUnterminatedLineOnceAndMarksEof)
|
||||
{
|
||||
InputPipe pipe;
|
||||
TerminalInput input(pipe.Reader());
|
||||
pipe.Write("last");
|
||||
pipe.CloseWriter();
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("last"));
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, EmptyClosedPipeMarksEofWithoutAnEmptyLine)
|
||||
{
|
||||
InputPipe pipe;
|
||||
TerminalInput input(pipe.Reader());
|
||||
pipe.CloseWriter();
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, DrainsLinesBeforeReportingHangupAndAddsNoPhantomLine)
|
||||
{
|
||||
InputPipe pipe;
|
||||
TerminalInput input(pipe.Reader());
|
||||
pipe.Write("first\n\n");
|
||||
pipe.CloseWriter();
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("first"));
|
||||
EXPECT_FALSE(input.IsEof());
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>(""));
|
||||
EXPECT_FALSE(input.IsEof());
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, RemovesOnlyCrImmediatelyBeforeLfIncludingAcrossCalls)
|
||||
{
|
||||
InputPipe pipe;
|
||||
TerminalInput input(pipe.Reader());
|
||||
pipe.Write("one\r");
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
pipe.Write("\n\r\nx\ry\nfinal\r");
|
||||
pipe.CloseWriter();
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("one"));
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>(""));
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("x\ry"));
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("final\r"));
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, ReadsRegularFileAndFinalPartialLine)
|
||||
{
|
||||
InputFile file("first\r\nlast");
|
||||
TerminalInput input(file.Descriptor());
|
||||
EXPECT_FALSE(input.IsInteractive());
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("first"));
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("last"));
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, AcceptsExactLengthLimitWithNewline)
|
||||
{
|
||||
const std::string line(TerminalInput::MaxLineBytes, 'x');
|
||||
InputFile file(line + "\n");
|
||||
TerminalInput input(file.Descriptor());
|
||||
EXPECT_EQ(PollAvailableLine(input), std::optional<std::string>(line));
|
||||
EXPECT_FALSE(input.IsEof());
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, AcceptsExactLengthLimitWithoutNewline)
|
||||
{
|
||||
const std::string line(TerminalInput::MaxLineBytes, 'x');
|
||||
InputFile file(line);
|
||||
TerminalInput input(file.Descriptor());
|
||||
EXPECT_EQ(PollAvailableLine(input), std::optional<std::string>(line));
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, RejectsOverlongLineOnceRatherThanExecutingTruncatedCommand)
|
||||
{
|
||||
InputFile file(std::string(TerminalInput::MaxLineBytes + 1, 'x') + "\nnext\n");
|
||||
TerminalInput input(file.Descriptor());
|
||||
EXPECT_THROW(PollAvailableLine(input), std::length_error);
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
EXPECT_NO_THROW(EXPECT_FALSE(input.PollLine()));
|
||||
EXPECT_NO_THROW(EXPECT_FALSE(input.PollLine()));
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, InvalidDescriptorReportsErrorOnlyOnce)
|
||||
{
|
||||
TerminalInput input(-1);
|
||||
EXPECT_THROW(input.PollLine(), std::runtime_error);
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
EXPECT_NO_THROW(EXPECT_FALSE(input.PollLine()));
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, DestructionDoesNotCloseBorrowedDescriptor)
|
||||
{
|
||||
InputPipe pipe;
|
||||
{
|
||||
TerminalInput input(pipe.Reader());
|
||||
EXPECT_FALSE(input.IsEof());
|
||||
}
|
||||
pipe.Write("still open\n");
|
||||
TerminalInput next(pipe.Reader());
|
||||
EXPECT_EQ(next.PollLine(), std::optional<std::string>("still open"));
|
||||
}
|
||||
|
||||
#ifndef _WIN32
|
||||
TEST(TerminalInputTest, PreservesBlockingAndNonblockingDescriptorFlags)
|
||||
{
|
||||
InputPipe pipe;
|
||||
const int original = fcntl(pipe.Reader(), F_GETFL);
|
||||
ASSERT_NE(original, -1);
|
||||
{
|
||||
TerminalInput input(pipe.Reader());
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
EXPECT_EQ(fcntl(pipe.Reader(), F_GETFL), original);
|
||||
}
|
||||
ASSERT_NE(fcntl(pipe.Reader(), F_SETFL, original | O_NONBLOCK), -1);
|
||||
{
|
||||
TerminalInput input(pipe.Reader());
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
pipe.Write("ready\n");
|
||||
EXPECT_EQ(input.PollLine(), std::optional<std::string>("ready"));
|
||||
}
|
||||
EXPECT_EQ(fcntl(pipe.Reader(), F_GETFL), original | O_NONBLOCK);
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, ClosedDescriptorReportsPollingErrorOnlyOnce)
|
||||
{
|
||||
InputPipe pipe;
|
||||
const int duplicate = dup(pipe.Reader());
|
||||
ASSERT_NE(duplicate, -1);
|
||||
TerminalInput input(duplicate);
|
||||
ASSERT_EQ(close(duplicate), 0);
|
||||
EXPECT_THROW(input.PollLine(), std::runtime_error);
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
EXPECT_NO_THROW(EXPECT_FALSE(input.PollLine()));
|
||||
}
|
||||
|
||||
TEST(TerminalInputTest, ReadErrorDiscardsPartialLineAndLatchesEof)
|
||||
{
|
||||
InputPipe pipe;
|
||||
const int duplicate = dup(pipe.Reader());
|
||||
ASSERT_NE(duplicate, -1);
|
||||
TerminalInput input(duplicate);
|
||||
pipe.Write("do not execute");
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
ASSERT_EQ(close(duplicate), 0);
|
||||
EXPECT_THROW(input.PollLine(), std::runtime_error);
|
||||
EXPECT_TRUE(input.IsEof());
|
||||
EXPECT_FALSE(input.PollLine());
|
||||
}
|
||||
#endif
|
||||
} // namespace
|
||||
Reference in new issue
Block a user