Skip to content

Commit

Permalink
refactor: refactoring filehandle/expected
Browse files Browse the repository at this point in the history
  • Loading branch information
OEOTYAN committed Aug 19, 2024
1 parent 5a42407 commit 5ae005f
Show file tree
Hide file tree
Showing 24 changed files with 140 additions and 134 deletions.
8 changes: 3 additions & 5 deletions src-client/ll/core/gui/ImGuiAnsiColor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,6 @@ void RenderAnsiText(ImVec2 pos, const char* text, const char* text_end, bool hid
if (hide_text_after_hash) {
text_display_end = FindRenderedTextEnd(text, text_end);
} else {
if (!text_end) text_end = text + strlen(text); // FIXME-OPT
text_display_end = text_end;
}

Expand All @@ -448,8 +447,6 @@ void RenderAnsiTextWrapped(ImVec2 pos, const char* text, const char* text_end, f
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;

if (!text_end) text_end = text + strlen(text); // FIXME-OPT

if (text != text_end) {
ImDrawList_AddAnsiText(
window->DrawList,
Expand All @@ -465,14 +462,15 @@ void RenderAnsiTextWrapped(ImVec2 pos, const char* text, const char* text_end, f
}
}

void textAnsiUnformatted(const char* text, const char* text_end) {
void textAnsiUnformatted(std::string_view view) {
auto text = &*view.begin(), text_end = &*view.end();

ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems) return;

ImGuiContext& g = *GImGui;
IM_ASSERT(text != nullptr);
const char* text_begin = text;
if (text_end == nullptr) text_end = text + strlen(text); // FIXME-OPT

const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
const float wrap_pos_x = window->DC.TextWrapPos;
Expand Down
4 changes: 3 additions & 1 deletion src-client/ll/core/gui/ImGuiAnsiColor.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#pragma once

#include <string_view>

namespace ll::gui {
void textAnsiUnformatted(const char* text, const char* text_end);
void textAnsiUnformatted(std::string_view view);
} // namespace ll::gui
4 changes: 2 additions & 2 deletions src-client/ll/core/gui/win/GUI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ class LogWindow {
const char* lineEnd =
(lineNum + 1 < lineOffsets.size()) ? (bufBegin + lineOffsets[lineNum + 1] - 1) : bufEnd;
if (filter.PassFilter(lineStart, lineEnd)) {
textAnsiUnformatted(lineStart, lineEnd);
textAnsiUnformatted({lineStart, lineEnd});
}
}
} else {
Expand All @@ -102,7 +102,7 @@ class LogWindow {
const char* lineStart = bufBegin + lineOffsets[lineNum];
const char* lineEnd =
(lineNum + 1 < lineOffsets.size()) ? (bufBegin + lineOffsets[lineNum + 1] - 1) : bufEnd;
textAnsiUnformatted(lineStart, lineEnd);
textAnsiUnformatted({lineStart, lineEnd});
}
}
clipper.End();
Expand Down
8 changes: 4 additions & 4 deletions src-test/client/jsonUITest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ LL_AUTO_TYPE_INSTANCE_HOOK(
uint64_t max = stack.getItem()->getMaxDamage();
if (max != 0) {
uint64_t current = max - stack.getDamageValue();
hovertext.append(fmt::format("/n§7耐久: {} / {}§r", current, max));
hovertext.append(fmt::format("\n§7耐久: {} / {}§r", current, max));
}

if (stack.mChargedItem && stack.mItem && stack.getTypeName() == "minecraft:crossbow") {
hovertext.append(fmt::format("/n§7弹药: {}§r", stack.mChargedItem->toString()));
hovertext.append(fmt::format("\n§7弹药: {}§r", stack.mChargedItem->toString()));
}

auto foodComp = (stack.mItem->getFood());
Expand All @@ -60,8 +60,8 @@ LL_AUTO_TYPE_INSTANCE_HOOK(
auto hunger = ll::memory::dAccess<int>(foodComp, 16);
auto saturationModifier = ll::memory::dAccess<float>(foodComp, 20);
auto saturation = saturationModifier * 2.0f * static_cast<float>(hunger);
hovertext.append(fmt::format("/n§7饥饿值: {}§r", hunger));
hovertext.append(fmt::format("/n§7饱和度: {:.2f}§r", saturation));
hovertext.append(fmt::format("\n§7饥饿值: {}§r", hunger));
hovertext.append(fmt::format("\n§7饱和度: {:.2f}§r", saturation));
}
}
} // namespace ll::test_jsonui
12 changes: 7 additions & 5 deletions src/ll/api/Expected.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

#include "boost/stacktrace.hpp"

#include <stacktrace>

#ifdef LL_DEBUG
#include "ll/api/utils/StacktraceUtils.h"
#endif
Expand Down Expand Up @@ -90,17 +92,17 @@ Error& Error::join(Error err) noexcept {
}
if (isA<ErrorList>()) {
if (err.isA<ErrorList>()) {
as<ErrorList>()->errors.append_range(std::move(err.as<ErrorList>()->errors));
as<ErrorList>().errors.append_range(std::move(err.as<ErrorList>().errors));
} else {
as<ErrorList>()->errors.emplace_back(std::move(err.mInfo));
as<ErrorList>().errors.emplace_back(std::move(err.mInfo));
}
} else {
if (err.isA<ErrorList>()) {
auto ptr = err.as<ErrorList>();
ptr->errors.insert(ptr->errors.begin(), std::move(mInfo));
auto& list = err.as<ErrorList>();
list.errors.insert(list.errors.begin(), std::move(mInfo));
mInfo = std::move(err.mInfo);
} else {
auto list = std::make_shared<ErrorList>();
auto list = std::make_unique<ErrorList>();
list->errors.emplace_back(std::move(mInfo));
list->errors.emplace_back(std::move(err.mInfo));
mInfo = std::move(list);
Expand Down
59 changes: 35 additions & 24 deletions src/ll/api/Expected.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ class CommandOutput;
namespace ll {
class OutputStream;
class Error;

template <class T = void>
using Expected = ::nonstd::expected<T, ::ll::Error>;

using Unexpected = ::nonstd::unexpected_type<::ll::Error>;

class ErrorInfoBase {
friend Error;
struct Impl;
Expand All @@ -28,22 +34,26 @@ class ErrorInfoBase {
virtual std::string message() const noexcept = 0;
};
class Error {
std::shared_ptr<ErrorInfoBase> mInfo;
std::unique_ptr<ErrorInfoBase> mInfo;

public:
Error& operator=(Error&&) noexcept = default;
Error& operator=(Error const&) noexcept = default;
Error& operator=(Error const&) noexcept = delete;
[[nodiscard]] Error(Error&&) noexcept = default;
[[nodiscard]] Error(Error const&) noexcept = default;
[[nodiscard]] Error(Error const&) noexcept = delete;

Error() noexcept = default;
~Error() noexcept = default;
LL_CONSTEXPR23 Error() noexcept = default;
LL_CONSTEXPR23 ~Error() noexcept = default;

Error(std::shared_ptr<ErrorInfoBase> i) noexcept : mInfo(std::move(i)) {}
LL_CONSTEXPR23 Error(std::unique_ptr<ErrorInfoBase> i) noexcept : mInfo(std::move(i)) {}

Error(::nonstd::unexpected_type<::ll::Error> i) noexcept : Error(std::move(i.value())) {}
LL_CONSTEXPR23 Error(::nonstd::unexpected_type<::ll::Error> i) noexcept : Error(std::move(i.value())) {}

operator bool() const noexcept { return mInfo != nullptr; }
LL_CONSTEXPR23 operator bool() const noexcept { return mInfo != nullptr; }

constexpr operator Unexpected() noexcept {
return ::nonstd::make_unexpected<Error>(std::in_place, std::move(mInfo));
}

LLNDAPI std::string message() const noexcept;

Expand All @@ -52,8 +62,8 @@ class Error {
return mInfo ? typeid(T) == typeid(mInfo.get()) : false;
}
template <class T>
auto as() noexcept {
return std::static_pointer_cast<T>(mInfo);
T& as() noexcept {
return *static_cast<T*>(mInfo.get());
}
LLAPI Error& join(Error) noexcept;

Expand All @@ -66,11 +76,6 @@ class Error {
Error const& log(CommandOutput& s) const noexcept { return const_cast<Error*>(this)->log(s); }
};

template <class T = void>
using Expected = ::nonstd::expected<T, ::ll::Error>;

using Unexpected = ::nonstd::unexpected_type<::ll::Error>;

struct StringError : ErrorInfoBase {
std::string str;
StringError(std::string str) : str(std::move(str)) {}
Expand All @@ -83,11 +88,11 @@ struct ErrorCodeError : ErrorInfoBase {
};
inline Unexpected forwardError(::ll::Error& err) noexcept { return ::nonstd::make_unexpected(std::move(err)); }

inline Unexpected makeSuccessError() noexcept { return ::nonstd::make_unexpected(Error{}); }
inline Unexpected makeSuccessed() noexcept { return ::nonstd::make_unexpected(Error{}); }

template <std::derived_from<::ll::ErrorInfoBase> T, class... Args>
inline Unexpected makeError(Args&&... args) noexcept {
return ::nonstd::make_unexpected(::ll::Error{std::make_shared<T>(std::forward<Args>(args)...)});
return ::nonstd::make_unexpected<Error>(std::in_place, std::make_unique<T>(std::forward<Args>(args)...));
}
inline Unexpected makeStringError(std::string str) noexcept { return makeError<StringError>(std::move(str)); }

Expand All @@ -102,20 +107,26 @@ LLNDAPI Unexpected makeExceptionError(std::exception_ptr const& exc = std::curre
namespace nonstd::expected_lite {
template <>
class bad_expected_access<::ll::Error> : public bad_expected_access<void> {
::ll::Error mError;
std::string mMessage;
std::shared_ptr<::ll::Error> mError;
std::string mMessage;

public:
explicit bad_expected_access(::ll::Error const& e) noexcept : mError(e), mMessage(mError.message()) {}
explicit bad_expected_access(::ll::Error& e) noexcept
: mError(::std::make_shared<::ll::Error>(::std::move(e))),
mMessage(mError->message()) {}

char const* what() const noexcept override { return mMessage.c_str(); }

constexpr ::ll::Error& error() & { return mError; }
::ll::Error& error() & { return *mError; }

constexpr ::ll::Error const& error() const& { return mError; }
::ll::Error const& error() const& { return *mError; }

constexpr ::ll::Error&& error() && { return ::std::move(mError); }
::ll::Error&& error() && { return ::std::move(*mError); }

constexpr ::ll::Error const&& error() const&& { return ::std::move(mError); }
::ll::Error const&& error() const&& { return ::std::move(*mError); }
};
template <>
struct error_traits<::ll::Error> {
static void rethrow(::ll::Error const& e) { throw bad_expected_access<::ll::Error>{const_cast<::ll::Error&>(e)}; }
};
} // namespace nonstd::expected_lite
4 changes: 3 additions & 1 deletion src/ll/api/Logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ class OutputStream {
std::array<fmt::text_style, 4> style;
std::array<std::string, 5> consoleFormat;
std::array<std::string, 5> fileFormat;
std::array<std::string, 5> playerFormat; // TODO: remove in release
std::function<void()> playerOutputCallback; // TODO: remove in release

LLAPI explicit OutputStream(
Logger& logger,
Expand Down Expand Up @@ -77,7 +79,7 @@ class Logger {
std::optional<std::ofstream> ofs = std::nullopt;
int consoleLevel = -1;
int fileLevel = -1;
int filler;
int filler; // TODO: remove in release

OutputStream debug;
OutputStream info;
Expand Down
24 changes: 13 additions & 11 deletions src/ll/api/base/CompilerPredefine.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@

#include <optional>

#if defined(_WIN32)
#define LL_WIN32
#elif defined(__linux__)
#define LL_LINUX
#endif

#ifdef _MSC_VER

#include "intrin.h"
Expand Down Expand Up @@ -45,13 +39,17 @@
#define LL_UNREACHABLE _STL_UNREACHABLE
#endif

#ifndef LL_RETURN_ADDRESS
#define LL_RETURN_ADDRESS _ReturnAddress()
#endif

// MSVC has customized some functions and classes inside the compiler, but they are not included in IntelliSense. This
// header file is only used for IntelliSense.
#if defined(__INTELLISENSE__) || defined(__clang__) || defined(__clangd__)
// NOLINTBEGIN
#pragma pack(push, ehdata, 4)

typedef struct _PMD {
typedef struct _PMD {
int mdisp; // Offset of intended data within base
int pdisp; // Displacement to virtual base pointer
int vdisp; // Index within vbTable to offset of base
Expand Down Expand Up @@ -193,10 +191,10 @@ extern "C" struct _IMAGE_DOS_HEADER __ImageBase; // NOLINT(bugprone-reserved-ide

[[nodiscard]] LL_FORCEINLINE void* getCurrentModuleHandle() noexcept { return &__ImageBase; }

[[nodiscard]] LL_FORCEINLINE void* returnAddress() noexcept { return _ReturnAddress(); }

using std_optional_construct_from_invoke_tag = std::_Construct_from_invoke_result_tag;

using FileHandleT = void*;

} // namespace ll::internal

#else
Expand Down Expand Up @@ -237,14 +235,18 @@ using std_optional_construct_from_invoke_tag = std::_Construct_from_invoke_resul
#define LL_UNREACHABLE __builtin_unreachable()
#endif

#ifndef LL_RETURN_ADDRESS
#define LL_RETURN_ADDRESS __builtin_return_address(0)
#endif

namespace ll::internal {

[[nodiscard]] LL_FORCEINLINE void* getCurrentModuleHandle() noexcept; // Implemented in SystemUtils_linux.cpp

[[nodiscard]] LL_FORCEINLINE void* returnAddress() noexcept { return __builtin_return_address(0); }

using std_optional_construct_from_invoke_tag = std::__optional_construct_from_invoke_tag;

using FileHandleT = int;

} // namespace ll::internal

#endif
6 changes: 2 additions & 4 deletions src/ll/api/io/FileUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,8 @@ LLNDAPI std::optional<std::string> readFile(std::filesystem::path const& filePat

LLAPI bool writeFile(std::filesystem::path const& filePath, std::string_view content, bool isBinary = false);

#ifdef LL_WIN32
/// Gets the version property of the file.
/// @note Typically, version properties exist in .exe, .dll, .msi, .cpl, .sys, .chm files.
LLNDAPI data::Version getVersion(std::filesystem::path const& filePath);
#endif
/// @note Typically, version properties exist in .exe, .dll, .msi, .cpl, .sys, .chm files of windows.
LLNDAPI std::optional<data::Version> getVersion(std::filesystem::path const& filePath);

} // namespace ll::inline utils::file_utils
10 changes: 2 additions & 8 deletions src/ll/api/io/Pipe.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,7 @@ class Pipe {

LLAPI void write(std::string_view);

private:
#if defined(LL_WIN32)
void* hRead;
void* hWrite;
#elif defined(LL_LINUX)
int fdRead{};
int fdWrite{};
#endif
internal::FileHandleT hRead;
internal::FileHandleT hWrite;
};
} // namespace ll::io
24 changes: 8 additions & 16 deletions src/ll/api/io/StdoutRedirector.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,24 @@

#include <string>

#include "ll/api/base/Macro.h"

namespace ll::io {

class StdoutRedirector {

public:
enum ProcessChannel { StandardOutput = 1, StandardError = 2 };
#if defined(LL_WIN32)

LLNDAPI explicit StdoutRedirector(
void* outputHandle,
ProcessChannel channels = (ProcessChannel)(StandardOutput | StandardError)
internal::FileHandleT outputHandle,
ProcessChannel channels = (ProcessChannel)(StandardOutput | StandardError)
);

LLAPI ~StdoutRedirector();

ProcessChannel channels;
void* outputHandle;
#elif defined(LL_LINUX)
StdoutRedirector(int outputFd, ProcessChannel channels);

~StdoutRedirector();

ProcessChannel channels;
int outputFd;

private:
int oldStdout;
int oldStderr;
#endif
int oldStdout{-1};
int oldStderr{-1};
};
} // namespace ll::io
5 changes: 5 additions & 0 deletions src/ll/api/io/linux/FileUtils.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#include "ll/api/io/FileUtils.h"

namespace ll::inline utils::file_utils {
std::optional<data::Version> getVersion(std::filesystem::path const& filePath) { return {}; }
} // namespace ll::inline utils::file_utils
Loading

0 comments on commit 5ae005f

Please sign in to comment.