diff --git a/.clang-format b/.clang-format index e051c2692a..4a24aec430 100644 --- a/.clang-format +++ b/.clang-format @@ -24,7 +24,7 @@ AlignConsecutiveBitFields: AcrossEmptyLines: false AcrossComments: false AllowShortLambdasOnASingleLine: All -AllowShortBlocksOnASingleLine: Always +AllowShortBlocksOnASingleLine: Empty AllowShortIfStatementsOnASingleLine: AllIfsAndElse AllowShortLoopsOnASingleLine: true AlwaysBreakAfterDefinitionReturnType: None diff --git a/src/ll/api/Config.h b/src/ll/api/Config.h index be5f0f8e41..cd0dda0f4d 100644 --- a/src/ll/api/Config.h +++ b/src/ll/api/Config.h @@ -56,8 +56,12 @@ inline bool loadConfig(T& config, std::string_view path, bool overwriteAfterFail } else { res = false; } - } catch (...) { res = false; } - if (!res && overwriteAfterFail) { saveConfig(config, path); } + } catch (...) { + res = false; + } + if (!res && overwriteAfterFail) { + saveConfig(config, path); + } return res; } diff --git a/src/ll/api/Logger.cpp b/src/ll/api/Logger.cpp index 8d3899b4ae..3b335ae6f7 100644 --- a/src/ll/api/Logger.cpp +++ b/src/ll/api/Logger.cpp @@ -33,7 +33,9 @@ void Logger::OutputStream::print(std::string_view s) const noexcept { applyTextStyle(style[2], fmt::format(fmt::runtime(consoleFormat[3]), logger->title)), applyTextStyle(style[3], fmt::format(fmt::runtime(consoleFormat[4]), replaceMcToAnsiCode(s))) ); - if (!ll::globalConfig.logger.colorLog) { str = removeEscapeCode(str); } + if (!ll::globalConfig.logger.colorLog) { + str = removeEscapeCode(str); + } fmt::print("{}\r\n", str); } if (logger->getFile().is_open() && checkLogLevel(logger->fileLevel, level)) { @@ -113,8 +115,7 @@ Logger::Logger(std::string_view title) fmt::fg(fmt::color::light_sea_green), {}, {}, - } - }), + }}), warn(OutputStream{ *this, "WARN", @@ -124,8 +125,7 @@ Logger::Logger(std::string_view title) fmt::fg(fmt::terminal_color::bright_yellow), fmt::fg(fmt::terminal_color::bright_yellow), fmt::fg(fmt::terminal_color::bright_yellow) | fmt::emphasis::bold, - } - }), + }}), error(OutputStream{ *this, "ERROR", @@ -135,8 +135,7 @@ Logger::Logger(std::string_view title) fmt::fg(fmt::terminal_color::bright_red), fmt::fg(fmt::terminal_color::bright_red), fmt::fg(fmt::terminal_color::bright_red) | fmt::emphasis::bold, - } - }), + }}), fatal(OutputStream{ *this, "FATAL", @@ -146,8 +145,7 @@ Logger::Logger(std::string_view title) fmt::fg(fmt::color::red), fmt::fg(fmt::color::red), fmt::fg(fmt::color::red) | fmt::emphasis::bold, - } - }) {} + }}) {} void Logger::resetFile() { if (ofs) { @@ -159,7 +157,9 @@ void Logger::resetFile() { bool Logger::setFile(std::string const& logFile, bool appendMode) { resetFile(); - if (logFile.empty()) { return true; } + if (logFile.empty()) { + return true; + } std::error_code ec; std::filesystem::create_directories(file_utils::u8path(logFile).remove_filename(), ec); @@ -169,7 +169,9 @@ bool Logger::setFile(std::string const& logFile, bool appendMode) { bool Logger::setDefaultFile(std::string const& logFile, bool appendMode) { if (logFile.empty()) { - if (defaultFile.is_open()) { defaultFile.close(); } + if (defaultFile.is_open()) { + defaultFile.close(); + } return true; } diff --git a/src/ll/api/Logger.h b/src/ll/api/Logger.h index 1d6d9bd5e4..eda76af4c2 100644 --- a/src/ll/api/Logger.h +++ b/src/ll/api/Logger.h @@ -110,7 +110,9 @@ class Logger { LLAPI static void setDefaultPlayerOutputFunc(PlayerOutputFunc const& func) { defaultPlayerOutputCallback = func; } std::ofstream& getFile() { - if (ofs) { return ofs.value(); } + if (ofs) { + return ofs.value(); + } return defaultFile; } diff --git a/src/ll/api/base/Base64.h b/src/ll/api/base/Base64.h index 2bf87868bb..b6e3e76fec 100644 --- a/src/ll/api/base/Base64.h +++ b/src/ll/api/base/Base64.h @@ -17,7 +17,9 @@ inline size_t getEncodeLength(std::string const& str) { return getEncodeLength(s inline size_t getDecodeLength(std::string const& in) { uchar count = 0; size_t input_size = in.size(); - for (auto it = in.rbegin(); *it == '='; ++it) { ++count; } + for (auto it = in.rbegin(); *it == '='; ++it) { + ++count; + } input_size -= count; // remove padding size count = 0; // reset padding counter while (input_size % 4) { // redo padding @@ -52,10 +54,14 @@ inline std::string encode(std::string const& text_input) { } } - if (j > -6) { result += base64Table[((i << 8) >> (j + 8)) & 0x3F]; } + if (j > -6) { + result += base64Table[((i << 8) >> (j + 8)) & 0x3F]; + } // padding - while (result.size() % 4) { result.push_back('='); } + while (result.size() % 4) { + result.push_back('='); + } return result; } diff --git a/src/ll/api/base/ErrorInfo.cpp b/src/ll/api/base/ErrorInfo.cpp index fe328c84a2..811809461a 100644 --- a/src/ll/api/base/ErrorInfo.cpp +++ b/src/ll/api/base/ErrorInfo.cpp @@ -31,8 +31,12 @@ struct u8system_category : public std::_System_error_category { const std::_System_error_message msg(static_cast(errCode)); if (msg._Length) { std::string res{string_utils::str2str({msg._Str, msg._Length})}; - if (res.ends_with('\n')) { res.pop_back(); } - if (res.ends_with('\r')) { res.pop_back(); } + if (res.ends_with('\n')) { + res.pop_back(); + } + if (res.ends_with('\r')) { + res.pop_back(); + } return string_utils::replaceAll(res, "\r\n", ", "); } return "unknown error"; @@ -70,8 +74,12 @@ struct ntstatus_category : public std::error_category { if (size) { std::string res{string_utils::wstr2str({msg, size})}; LocalFree(msg); - if (res.ends_with('\n')) { res.pop_back(); } - if (res.ends_with('\r')) { res.pop_back(); } + if (res.ends_with('\n')) { + res.pop_back(); + } + if (res.ends_with('\r')) { + res.pop_back(); + } return string_utils::replaceAll(res, "\r\n", ", "); } return "unknown error"; @@ -162,13 +170,17 @@ static std::exception_ptr getNested(T const& e) { if constexpr (can_use_dynamic_cast) { const auto n = dynamic_cast(std::addressof(e)); - if (n) { return n->nested_ptr(); } + if (n) { + return n->nested_ptr(); + } } return nullptr; } std::string makeExceptionString(std::exception_ptr ePtr) { - if (!ePtr) { throw std::bad_exception(); } + if (!ePtr) { + throw std::bad_exception(); + } std::string res; @@ -191,7 +203,7 @@ std::string makeExceptionString(std::exception_ptr ePtr) { } auto expTypeName = exc.getNumCatchableTypes() > 0 ? exc.getTypeInfo(0)->name() : "unknown exception"; if (expTypeName == typeid(seh_exception).name()) { - res += fmt::format("Translated Seh Exception, from <{}>:\n", handleName); + res += fmt::format("Seh Exception, from <{}>:\n", handleName); } else { res += fmt::format( "C++ Exception: {}, from <{}>:\n", @@ -218,7 +230,9 @@ std::string makeExceptionString(std::exception_ptr ePtr) { } catch (const std::exception& e) { res += string_utils::tou8str(e.what()); ePtr = getNested(e); - } catch (const std::string& e) { res += string_utils::tou8str(e); } catch (char const* e) { + } catch (const std::string& e) { + res += string_utils::tou8str(e); + } catch (char const* e) { res += string_utils::tou8str(e); } catch (...) { auto unkExc = current_exception(); @@ -245,7 +259,9 @@ void printCurrentException(optional_ref l, std::exception_ptr const& auto& rlogger = l.value_or(logger); try { auto res = makeExceptionString(e); - for (auto& sv : string_utils::splitByPattern(res, "\n")) { rlogger.error(sv); } + for (auto& sv : string_utils::splitByPattern(res, "\n")) { + rlogger.error(sv); + } return; } catch (...) {} rlogger.error("unknown error"); diff --git a/src/ll/api/base/KeyValueDB.cpp b/src/ll/api/base/KeyValueDB.cpp index f9002c5144..a0d16a09d3 100644 --- a/src/ll/api/base/KeyValueDB.cpp +++ b/src/ll/api/base/KeyValueDB.cpp @@ -34,8 +34,12 @@ class KeyValueDB::KeyValueDBImpl { options.reuse_logs = true; // @warning: experimental options.create_if_missing = create; - if (cacheSize) { options.block_cache = leveldb::NewLRUCache(cacheSize); } - if (filterBit) { options.filter_policy = leveldb::NewBloomFilterPolicy(filterBit); } + if (cacheSize) { + options.block_cache = leveldb::NewLRUCache(cacheSize); + } + if (filterBit) { + options.filter_policy = leveldb::NewBloomFilterPolicy(filterBit); + } leveldb::DB* database = nullptr; status = leveldb::DB::Open(options, path, &database); @@ -52,7 +56,9 @@ class KeyValueDB::KeyValueDBImpl { [[nodiscard]] std::optional get(std::string_view key) const { std::string result; auto s = db->Get(readOptions, leveldb::Slice(key.data(), key.size()), &result); - if (!s.ok()) { return std::nullopt; } + if (!s.ok()) { + return std::nullopt; + } return result; } @@ -79,7 +85,9 @@ class KeyValueDB::KeyValueDBImpl { for (it->SeekToFirst(); it->Valid(); it->Next()) { auto k = it->key(); auto v = it->value(); - if (!fn({k.data(), k.size()}, {v.data(), v.size()})) { break; } + if (!fn({k.data(), k.size()}, {v.data(), v.size()})) { + break; + } } delete it; } diff --git a/src/ll/api/base/Version.h b/src/ll/api/base/Version.h index 1d6e41c7ad..81df5abb4c 100644 --- a/src/ll/api/base/Version.h +++ b/src/ll/api/base/Version.h @@ -27,7 +27,9 @@ constexpr std::uint16_t to_digit(char c) noexcept { return static_cast::max)()) { d = static_cast(t); return first; @@ -39,7 +41,9 @@ constexpr char const* from_chars(char const* first, char const* last, std::uint1 constexpr char const* from_chars(char const* first, char const* last, std::optional& d) noexcept { if (first != last && is_digit(*first)) { std::int32_t t = 0; - for (; first != last && is_digit(*first); ++first) { t = t * 10 + to_digit(*first); } + for (; first != last && is_digit(*first); ++first) { + t = t * 10 + to_digit(*first); + } if (t <= (std::numeric_limits::max)()) { d = static_cast(t); return first; @@ -96,7 +100,9 @@ struct PreRelease { constexpr detail::from_chars_result from_chars(char const* first, char const* last) noexcept { auto begin = first; - while (first != last && !detail::is_plus(*first)) { first++; } + while (first != last && !detail::is_plus(*first)) { + first++; + } std::string s{begin, first}; std::vector tokens; tokens = ll::utils::string_utils::splitByPattern(s, "."); @@ -116,7 +122,9 @@ struct PreRelease { } constexpr PreRelease& from_string(std::string_view str) { - if (!from_string_noexcept(str)) { throw VersionParseError("Invalid version string."); } + if (!from_string_noexcept(str)) { + throw VersionParseError("Invalid version string."); + } return *this; } @@ -130,7 +138,9 @@ struct PreRelease { } str += '.'; } - if (str.ends_with('.')) { str.pop_back(); } + if (str.ends_with('.')) { + str.pop_back(); + } return str; } }; @@ -181,8 +191,12 @@ struct Version { auto next = first; if (next = detail::from_chars(next, last, major); detail::check_delimiter(next, last, '.')) { if (next = detail::from_chars(++next, last, minor); detail::check_delimiter(next, last, '.')) { - if (next = detail::from_chars(++next, last, patch); next == last) { return {next, std::errc{}}; } - if (!next) { return {nullptr, std::errc::invalid_argument}; } + if (next = detail::from_chars(++next, last, patch); next == last) { + return {next, std::errc{}}; + } + if (!next) { + return {nullptr, std::errc::invalid_argument}; + } if (detail::check_delimiter(next, last, '-')) { PreRelease pre; auto result = pre.from_chars(++next, last); @@ -190,11 +204,15 @@ struct Version { if (pre.values.empty()) return {next, std::errc::invalid_argument}; preRelease = pre; next = result.ptr; - if (result && next == last) { return {next, std::errc{}}; } + if (result && next == last) { + return {next, std::errc{}}; + } } if (detail::check_delimiter(next, last, '+')) { build = {++next, static_cast(last - next)}; - if (build->empty()) { return {nullptr, std::errc::invalid_argument}; } + if (build->empty()) { + return {nullptr, std::errc::invalid_argument}; + } next = last; if (std::any_of(build->begin(), build->end(), [](char c) { return !detail::is_digit(c) && !detail::is_letter(c); @@ -202,7 +220,9 @@ struct Version { return {nullptr, std::errc::invalid_argument}; } } - if (next == last) { return {next, std::errc{}}; } + if (next == last) { + return {next, std::errc{}}; + } } } return {first, std::errc::invalid_argument}; @@ -213,7 +233,9 @@ struct Version { } constexpr Version& from_string(std::string_view str) { - if (!from_string_noexcept(str)) { throw VersionParseError("Invalid version string."); } + if (!from_string_noexcept(str)) { + throw VersionParseError("Invalid version string."); + } return *this; } @@ -232,11 +254,19 @@ struct Version { } [[nodiscard]] constexpr std::strong_ordering operator<=>(Version const& other) const noexcept { - if (major != other.major) { return major <=> other.major; } - if (minor != other.minor) { return minor <=> other.minor; } - if (patch != other.patch) { return patch <=> other.patch; } + if (major != other.major) { + return major <=> other.major; + } + if (minor != other.minor) { + return minor <=> other.minor; + } + if (patch != other.patch) { + return patch <=> other.patch; + } if (preRelease.has_value()) { - if (other.preRelease.has_value()) { return preRelease.value() <=> other.preRelease.value(); } + if (other.preRelease.has_value()) { + return preRelease.value() <=> other.preRelease.value(); + } return std::strong_ordering::less; } else if (other.preRelease.has_value()) { return std::strong_ordering::greater; @@ -259,7 +289,9 @@ inline J serialize(Version const& ver) { } template inline void deserialize(Version& ver, J const& j) { - if (j.is_string()) { ver.from_string(j.template get()); } + if (j.is_string()) { + ver.from_string(j.template get()); + } } namespace literals { diff --git a/src/ll/api/chrono/GameChrono.cpp b/src/ll/api/chrono/GameChrono.cpp index bbe16e5309..22b0d9b425 100644 --- a/src/ll/api/chrono/GameChrono.cpp +++ b/src/ll/api/chrono/GameChrono.cpp @@ -18,7 +18,9 @@ LL_AUTO_TYPED_INSTANCE_HOOK(ServerClockTickHook, HookPriority::Normal, ServerLev } GameTimeClock::time_point GameTimeClock::now() noexcept { - if (!ll::Global) { return time_point::max(); } + if (!ll::Global) { + return time_point::max(); + } return time_point(duration((int64)(ll::Global->getCurrentTick().t))); } diff --git a/src/ll/api/command/DynamicCommand.cpp b/src/ll/api/command/DynamicCommand.cpp index 75e0ce31fd..25a6a95a03 100644 --- a/src/ll/api/command/DynamicCommand.cpp +++ b/src/ll/api/command/DynamicCommand.cpp @@ -412,7 +412,9 @@ DynamicCommandInstance* DynamicCommand::preSetup(std::unique_ptr->findCommand(name); - if (signature) { throw std::runtime_error("There is already a command named " + signature->name); } + if (signature) { + throw std::runtime_error("There is already a command named " + signature->name); + } try { if (!commandInstance) throw std::runtime_error("Command instance is null"); @@ -456,7 +458,9 @@ DynamicCommandInstance* DynamicCommand::preSetup(std::unique_ptrswap(fixedName); fixedView = *namePtr; for (auto& data : commandInstance->parameterDatas) { - if (data.description == fixedName) { data.description = *namePtr; } + if (data.description == fixedName) { + data.description = *namePtr; + } } break; } @@ -499,7 +503,9 @@ DynamicCommandInstance* DynamicCommand::preSetup(std::unique_ptroverloads.clear(); auto res = dynamicCommandInstances.emplace(commandInstance->name_, std::move(commandInstance)); return res.first->second.get(); - } catch (...) { OutputError(name); } + } catch (...) { + OutputError(name); + } return nullptr; } @@ -528,15 +534,23 @@ DynamicCommand::~DynamicCommand() { void DynamicCommand::execute(CommandOrigin const& origin, CommandOutput& output) const { auto iter = dynamicCommandInstances.find(getCommandName()); - if (iter == dynamicCommandInstances.end()) { return output.error("Dynamic Command Not Found"); } + if (iter == dynamicCommandInstances.end()) { + return output.error("Dynamic Command Not Found"); + } auto& commandIns = *iter->second; - if (!commandIns.callback_) { return output.error(fmt::format("Command {} has been removed.", getCommandName())); } + if (!commandIns.callback_) { + return output.error(fmt::format("Command {} has been removed.", getCommandName())); + } try { std::unordered_map results; - for (auto& [name, param] : commandIns.parameterPtrs) { results.emplace(name, param.getResult(this, &origin)); } + for (auto& [name, param] : commandIns.parameterPtrs) { + results.emplace(name, param.getResult(this, &origin)); + } commandIns.callback_(*this, origin, output, results); - } catch (...) { OutputError(getCommandName()); } + } catch (...) { + OutputError(getCommandName()); + } } std::unique_ptr DynamicCommand::createCommand( @@ -571,10 +585,16 @@ std::unique_ptr DynamicCommand::createCommand( ) { auto command = createCommand(name, description, permission, flag1, flag2); if (!command) return std::unique_ptr(); - for (auto& [desc, values] : enums) { command->setEnum(desc, std::move(values)); } - for (auto& param : params) { command->newParameter(std::move(param)); } + for (auto& [desc, values] : enums) { + command->setEnum(desc, std::move(values)); + } + for (auto& param : params) { + command->newParameter(std::move(param)); + } if (overloads.size() > 0) { - for (auto& overload : overloads) { command->addOverload(std::move(overload)); } + for (auto& overload : overloads) { + command->addOverload(std::move(overload)); + } } else { command->addOverload(); } @@ -663,7 +683,9 @@ std::unique_ptr DynamicCommandInstance::create( bool DynamicCommandInstance::addOverload(std::vector&& params) { std::vector indices; - for (auto& param : params) { indices.push_back(newParameter(std::forward(param))); } + for (auto& param : params) { + indices.push_back(newParameter(std::forward(param))); + } return addOverload(std::move(indices)); } @@ -801,7 +823,9 @@ bool DynamicCommandInstance::addOverload(std::vector&& params) { std::vector paramIndices; for (auto& param : params) { auto index = findParameterIndex(param); - if (!index.isValid()) { throw std::runtime_error("Parameter " + std::string(param) + "not found"); } + if (!index.isValid()) { + throw std::runtime_error("Parameter " + std::string(param) + "not found"); + } paramIndices.push_back(index); } return addOverload(std::move(paramIndices)); @@ -809,7 +833,9 @@ bool DynamicCommandInstance::addOverload(std::vector&& params) { bool DynamicCommandInstance::addOverload(std::vector&& params) { std::vector paramIndices; - for (auto& param : params) { paramIndices.push_back(findParameterIndex(param)); } + for (auto& param : params) { + paramIndices.push_back(findParameterIndex(param)); + } return addOverload(std::move(paramIndices)); } diff --git a/src/ll/api/command/DynamicCommand.h b/src/ll/api/command/DynamicCommand.h index 8abf1cb787..bf615c46e4 100644 --- a/src/ll/api/command/DynamicCommand.h +++ b/src/ll/api/command/DynamicCommand.h @@ -308,13 +308,17 @@ class DynamicCommand : public Command { return actors; } std::vector rtn; - for (auto& result : getRaw>().results(*origin)) { rtn.push_back(result); } + for (auto& result : getRaw>().results(*origin)) { + rtn.push_back(result); + } return rtn; } template <> std::vector get>() const { std::vector rtn; - for (auto& result : getRaw>().results(*origin)) { rtn.push_back(result); } + for (auto& result : getRaw>().results(*origin)) { + rtn.push_back(result); + } return rtn; } template <> @@ -412,8 +416,7 @@ class DynamicCommand : public Command { description == "" ? nullptr : description.data(), (int)offset, optional, - (int)offset + std::max(8, (int)sizeof(T)) - }; + (int)offset + std::max(8, (int)sizeof(T))}; param.addOptions(option); return param; } diff --git a/src/ll/api/event/EventBus.cpp b/src/ll/api/event/EventBus.cpp index 4910a19533..9cfac3ec2c 100644 --- a/src/ll/api/event/EventBus.cpp +++ b/src/ll/api/event/EventBus.cpp @@ -81,7 +81,9 @@ class EventBus::EventBusImpl { if (auto i = streams.find(eventId); i != streams.end()) { auto& stream = i->second; if (stream.removeListener(listener)) { - if (stream.empty()) { streams.erase(i); } + if (stream.empty()) { + streams.erase(i); + } return true; } } @@ -98,17 +100,25 @@ EventBus& EventBus::getInstance() { void EventBus::publish(Event& event, EventId const& eventId) { std::lock_guard lock(impl->mutex); - if (auto i = impl->streams.find(eventId); i != impl->streams.end()) { i->second.publish(event); } + if (auto i = impl->streams.find(eventId); i != impl->streams.end()) { + i->second.publish(event); + } } size_t EventBus::getListenerCount(EventId const& eventId) { std::lock_guard lock(impl->mutex); - if (auto i = impl->streams.find(eventId); i != impl->streams.end()) { return i->second.count(); } + if (auto i = impl->streams.find(eventId); i != impl->streams.end()) { + return i->second.count(); + } return 0; } bool EventBus::addListener(ListenerPtr const& listener, EventId const& eventId, Canneller& canneller) { - if (!listener) { return false; } + if (!listener) { + return false; + } std::lock_guard lock(impl->mutex); - if (listener->getId() == 0) { listener->setId(impl->getNewListenerId()); } + if (listener->getId() == 0) { + listener->setId(impl->getNewListenerId()); + } if (impl->addListener(listener, eventId)) { auto& info = impl->listeners[listener->getId()]; info.listener = listener; @@ -119,12 +129,16 @@ bool EventBus::addListener(ListenerPtr const& listener, EventId const& eventId, return false; } bool EventBus::removeListener(ListenerPtr const& listener, EventId const& eventId, Canneller& canneller) { - if (!listener) { return false; } + if (!listener) { + return false; + } std::lock_guard lock(impl->mutex); auto& watches = impl->listeners[listener->getId()].watches; bool res = false; if (eventId == EmptyEventId) { - for (auto& eid : watches) { res |= impl->removeListener(listener, eid); } + for (auto& eid : watches) { + res |= impl->removeListener(listener, eid); + } impl->listeners.erase(listener->getId()); canneller.listeners.erase(listener->getId()); } else { @@ -140,15 +154,23 @@ bool EventBus::removeListener(ListenerPtr const& listener, EventId const& eventI return res; } ListenerPtr EventBus::getListener(ListenerId id) const { - if (id == 0) { return nullptr; } + if (id == 0) { + return nullptr; + } std::lock_guard lock(impl->mutex); - if (!impl->listeners.contains(id)) { return nullptr; } + if (!impl->listeners.contains(id)) { + return nullptr; + } return impl->listeners[id].listener.lock(); } bool EventBus::hasListener(ListenerId id, EventId const& eventId) const { - if (id == 0) { return false; } + if (id == 0) { + return false; + } std::lock_guard lock(impl->mutex); - if (!impl->listeners.contains(id)) { return false; } + if (!impl->listeners.contains(id)) { + return false; + } if (eventId == EmptyEventId) { return true; } else { diff --git a/src/ll/api/event/EventBus.h b/src/ll/api/event/EventBus.h index 346df5145c..cf724f8984 100644 --- a/src/ll/api/event/EventBus.h +++ b/src/ll/api/event/EventBus.h @@ -23,7 +23,9 @@ class EventBus { Canneller() = default; ~Canneller() { auto list = listeners; - for (auto id : list) { EventBus::getInstance().removeListener(id); } + for (auto id : list) { + EventBus::getInstance().removeListener(id); + } } public: @@ -82,7 +84,9 @@ class EventBus { template T, std::derived_from L = Listener, class... Args> inline auto emplaceListener(Args&&... args) { auto res = L::create(std::forward(args)...); - if (addListener(res)) { T::tryRegisterHook(); } + if (addListener(res)) { + T::tryRegisterHook(); + } return res; } @@ -103,12 +107,16 @@ class EventBus { LLNDAPI ListenerPtr getListener(ListenerId id) const; bool removeListener(ListenerId id) { - if (auto listener = getListener(id); listener) { return removeListener(listener, EmptyEventId); } + if (auto listener = getListener(id); listener) { + return removeListener(listener, EmptyEventId); + } return false; } template T> bool removeListener(ListenerId id) { - if (auto listener = getListener(id); listener) { return removeListener(listener, getEventId); } + if (auto listener = getListener(id); listener) { + return removeListener(listener, getEventId); + } return false; } [[nodiscard]] bool hasListener(ListenerId id) const { return hasListener(id, EmptyEventId); } diff --git a/src/ll/api/event/EventId.h b/src/ll/api/event/EventId.h index af8ade1e32..f68e4c7290 100644 --- a/src/ll/api/event/EventId.h +++ b/src/ll/api/event/EventId.h @@ -20,7 +20,9 @@ class EventId { } [[nodiscard]] constexpr std::strong_ordering operator<=>(EventId const& other) const noexcept { - if (hash != other.hash) { return hash <=> other.hash; } + if (hash != other.hash) { + return hash <=> other.hash; + } return name <=> other.name; } }; diff --git a/src/ll/api/event/ListenerBase.h b/src/ll/api/event/ListenerBase.h index 10b929f068..1713810cee 100644 --- a/src/ll/api/event/ListenerBase.h +++ b/src/ll/api/event/ListenerBase.h @@ -41,7 +41,9 @@ class ListenerBase { [[nodiscard]] constexpr bool operator!=(ListenerBase const& other) const noexcept { return id != other.id; } [[nodiscard]] constexpr std::strong_ordering operator<=>(ListenerBase const& other) const noexcept { - if (priority != other.priority) { return priority <=> other.priority; } + if (priority != other.priority) { + return priority <=> other.priority; + } return id <=> other.id; } diff --git a/src/ll/api/event/filesystem/FileActionEvent.cpp b/src/ll/api/event/filesystem/FileActionEvent.cpp index 1d3b3be6c4..63dc82b43a 100644 --- a/src/ll/api/event/filesystem/FileActionEvent.cpp +++ b/src/ll/api/event/filesystem/FileActionEvent.cpp @@ -48,7 +48,9 @@ class FileWatch { void init() { closeEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); - if (!closeEvent) { throw ll::error_info::getWinLastError(); } + if (!closeEvent) { + throw ll::error_info::getWinLastError(); + } callbackThread = std::thread([this]() { @@ -82,7 +84,9 @@ class FileWatch { OVERLAPPED overlapped_buffer{0}; overlapped_buffer.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); - if (!overlapped_buffer.hEvent) { std::cerr << "Error creating monitor event" << std::endl; } + if (!overlapped_buffer.hEvent) { + std::cerr << "Error creating monitor event" << std::endl; + } std::array handles{overlapped_buffer.hEvent, closeEvent}; @@ -112,21 +116,24 @@ class FileWatch { } async_pending = false; - if (bytes_returned == 0) { break; } + if (bytes_returned == 0) { + break; + } auto* file_information = reinterpret_cast(&buffer[0]); do { std::wstring changed_file{ file_information->FileName, - file_information->FileNameLength / sizeof(file_information->FileName[0]) - }; + file_information->FileNameLength / sizeof(file_information->FileName[0])}; if (passFilter(changed_file)) { parsed_information.emplace_back( Path{changed_file}, (FileActionType)file_information->Action ); } - if (file_information->NextEntryOffset == 0) { break; } + if (file_information->NextEntryOffset == 0) { + break; + } file_information = reinterpret_cast( reinterpret_cast(file_information) + file_information->NextEntryOffset @@ -189,7 +196,9 @@ class FileWatch { return path; } else { filename = path.filename(); - if (!path.has_parent_path()) { return Path{u8"./"}; } + if (!path.has_parent_path()) { + return Path{u8"./"}; + } return path.parent_path(); } }(); @@ -204,7 +213,9 @@ class FileWatch { nullptr ); // file with attributes to copy - if (directory == INVALID_HANDLE_VALUE) { throw ll::error_info::getWinLastError(); } + if (directory == INVALID_HANDLE_VALUE) { + throw ll::error_info::getWinLastError(); + } return directory; } diff --git a/src/ll/api/event/filesystem/FileActionEvent.h b/src/ll/api/event/filesystem/FileActionEvent.h index 81f6aa6ab3..33cd13034a 100644 --- a/src/ll/api/event/filesystem/FileActionEvent.h +++ b/src/ll/api/event/filesystem/FileActionEvent.h @@ -40,8 +40,7 @@ template class FileActionEvent : public DynamicFileActionEvent { static constexpr auto CustomIdOwn{ FixedString.size()>{ll::reflection::type_name_v} - + FixedString{"|"} + WatchedPath - }; + + FixedString{"|"} + WatchedPath}; public: static constexpr EventId CustomEventId{CustomIdOwn}; diff --git a/src/ll/api/form/CustomForm.cpp b/src/ll/api/form/CustomForm.cpp index 33597220bd..a71eaca8e8 100644 --- a/src/ll/api/form/CustomForm.cpp +++ b/src/ll/api/form/CustomForm.cpp @@ -57,8 +57,12 @@ class Input : public CustomFormElement { {"type", "input"}, {"text", mText } }; - if (!mPlaceholder.empty()) { input["placeholder"] = mPlaceholder; } - if (!mDefault.empty()) { input["default"] = mDefault; } + if (!mPlaceholder.empty()) { + input["placeholder"] = mPlaceholder; + } + if (!mDefault.empty()) { + input["default"] = mDefault; + } return input; } catch (...) { ll::logger.error("Failed to serialize Input"); @@ -150,8 +154,12 @@ class Slider : public CustomFormElement { [[nodiscard]] bool isValid() const { return mMin <= mMax && mStep > 0.0 && mDefault >= mMin && mDefault <= mMax; } void validate() { - if (mMin > mMax) { std::swap(mMin, mMax); } - if (mStep <= 0.0) { mStep = 1.0; } + if (mMin > mMax) { + std::swap(mMin, mMax); + } + if (mStep <= 0.0) { + mStep = 1.0; + } if (mDefault < mMin) { mDefault = mMin; } else if (mDefault > mMax) { @@ -207,7 +215,9 @@ class StepSlider : public CustomFormElement { [[nodiscard]] bool isValid() const { return !mSteps.empty() && mDefault < mSteps.size(); } void validate() { - if (mDefault >= mSteps.size()) { mDefault = mSteps.size() - 1; } + if (mDefault >= mSteps.size()) { + mDefault = mSteps.size() - 1; + } } StepSlider(std::string name, std::string text, std::vector steps, size_t defaultVal = 0) @@ -311,7 +321,9 @@ class CustomForm::CustomFormImpl : public FormImpl { } uint id = handler::addFormHandler(std::make_unique(std::move(callback), mElements)); auto json = serialize(); - if (json.is_null()) { return false; } + if (json.is_null()) { + return false; + } ModalFormRequestPacket(id, json.dump()).sendTo(player); return true; } @@ -328,7 +340,9 @@ class CustomForm::CustomFormImpl : public FormImpl { }; for (auto& e : mElements) { nlohmann::ordered_json element = e->serialize(); - if (!element.empty()) { form["content"].push_back(element); } + if (!element.empty()) { + form["content"].push_back(element); + } } return form; } catch (...) { diff --git a/src/ll/api/form/ModalForm.cpp b/src/ll/api/form/ModalForm.cpp index 57abb6c5dd..84fb47b8b5 100644 --- a/src/ll/api/form/ModalForm.cpp +++ b/src/ll/api/form/ModalForm.cpp @@ -48,7 +48,9 @@ class ModalForm::ModalFormImpl : public FormImpl { } uint id = handler::addFormHandler(std::make_unique(std::move(callback))); auto json = serialize(); - if (json.is_null()) { return false; } + if (json.is_null()) { + return false; + } ModalFormRequestPacket(id, json.dump()).sendTo(player); return true; } diff --git a/src/ll/api/form/SimpleForm.cpp b/src/ll/api/form/SimpleForm.cpp index 0361ba66b6..c7dd031955 100644 --- a/src/ll/api/form/SimpleForm.cpp +++ b/src/ll/api/form/SimpleForm.cpp @@ -22,7 +22,9 @@ class Button { ~Button() = default; void callback(Player& player) { - if (mCallback) { mCallback(player); } + if (mCallback) { + mCallback(player); + } } [[nodiscard]] nlohmann::ordered_json serialize() const { @@ -77,11 +79,15 @@ class SimpleForm::SimpleFormImpl : public FormImpl { } std::vector buttonCallbacks; buttonCallbacks.reserve(mElements.size()); - for (auto& e : mElements) { buttonCallbacks.push_back(e.mCallback); } + for (auto& e : mElements) { + buttonCallbacks.push_back(e.mCallback); + } uint id = handler::addFormHandler(std::make_unique(std::move(callback), buttonCallbacks)); auto json = serialize(); - if (json.is_null()) { return false; } + if (json.is_null()) { + return false; + } ModalFormRequestPacket(id, json.dump()).sendTo(player); return true; } @@ -99,7 +105,9 @@ class SimpleForm::SimpleFormImpl : public FormImpl { }; for (auto& e : mElements) { nlohmann::ordered_json element = e.serialize(); - if (!element.empty()) { form["buttons"].push_back(element); } + if (!element.empty()) { + form["buttons"].push_back(element); + } } return form; } catch (nlohmann::ordered_json::exception const&) { diff --git a/src/ll/api/i18n/I18nAPI.cpp b/src/ll/api/i18n/I18nAPI.cpp index 1f7b09184a..b84d445552 100644 --- a/src/ll/api/i18n/I18nAPI.cpp +++ b/src/ll/api/i18n/I18nAPI.cpp @@ -19,9 +19,9 @@ const std::array GENERAL_LANGUAGES = {"en", "zh"}; bool findTranslation( I18N::LangData const& langData, - std::string_view key, - std::string_view localeName, - std::string_view localeType, + std::string_view key, + std::string_view localeName, + std::string_view localeType, std::string& dest ) { if (auto lang = langData.find(localeName); lang != langData.end()) { // If there is a translation for the language @@ -33,7 +33,9 @@ bool findTranslation( } // Search for the similar language in mLangData for (auto& [name, translations] : langData) { - if (name.length() < 2) { continue; } + if (name.length() < 2) { + continue; + } if (name.substr(0, 2) == localeType) { if (auto it = translations.find(key); it != translations.end()) { dest = it->second; @@ -55,20 +57,28 @@ std::string I18N::get(std::string_view key, std::string localeName) { auto localeType = localeName.substr(0, 2); std::string result; // Try finding the translation in loaded language data - if (findTranslation(mLangData, key, localeName, localeType, result)) { return result; } + if (findTranslation(mLangData, key, localeName, localeType, result)) { + return result; + } // If not found, try falling back to the default language data if (!mDefaultLangData.empty() && findTranslation(mDefaultLangData, key, localeName, localeType, result)) { return result; } // Try finding general languages for (auto& lang : GENERAL_LANGUAGES) { - if (findTranslation(mLangData, key, lang, lang, result)) { return result; } - if (!mDefaultLangData.empty() && findTranslation(mDefaultLangData, key, lang, lang, result)) { return result; } + if (findTranslation(mLangData, key, lang, lang, result)) { + return result; + } + if (!mDefaultLangData.empty() && findTranslation(mDefaultLangData, key, lang, lang, result)) { + return result; + } } // Use the first (dictionary order) language data if (!mLangData.empty()) { auto& lang = mLangData.begin()->second; - if (auto it = lang.find(key); it != lang.end()) { return it->second; } + if (auto it = lang.find(key); it != lang.end()) { + return it->second; + } } // Finally, still not found, return the key return std::string{key}; @@ -98,7 +108,9 @@ void SingleFileI18N::load(std::string const& fileName) { for (auto& [lang, dat] : mLangData) { if (mDefaultLangData.count(lang)) { for (auto& [k, v] : mDefaultLangData[lang]) { - if (!dat.count(k)) { dat[k] = v; } + if (!dat.count(k)) { + dat[k] = v; + } } } } @@ -141,13 +153,17 @@ I18N::SubLangData parseNestedData(nlohmann::json const& j, std::string const& pr void MultiFileI18N::load(std::string const& dirPath) { this->mDirPath = dirPath; if (!fs::exists(dirPath) || fs::is_empty(dirPath)) { - if (this->mDefaultLangData.empty()) { return; } + if (this->mDefaultLangData.empty()) { + return; + } this->mLangData = this->mDefaultLangData; save(); return; } for (auto& f : fs::directory_iterator(dirPath)) { - if (!f.is_regular_file() || f.path().extension() != ".json") { continue; } + if (!f.is_regular_file() || f.path().extension() != ".json") { + continue; + } auto langName = f.path().stem().string(); std::fstream file(f.path().wstring(), std::ios::in); nlohmann::json j; diff --git a/src/ll/api/i18n/I18nAPI.h b/src/ll/api/i18n/I18nAPI.h index 567fadd04f..6edb81aa1c 100644 --- a/src/ll/api/i18n/I18nAPI.h +++ b/src/ll/api/i18n/I18nAPI.h @@ -153,7 +153,9 @@ inline void load(std::string const& path) { template inline std::string tr(S const& formatStr, Args&&... args) { auto res = getInstance()->get(formatStr); - if constexpr (sizeof...(args) != 0) { return fmt::format(fmt::runtime(res), args...); } + if constexpr (sizeof...(args) != 0) { + return fmt::format(fmt::runtime(res), args...); + } return res; } @@ -176,7 +178,9 @@ inline std::string tr(S const& formatStr, Args&&... args) { template [[nodiscard]] inline std::string trl(std::string const& localeName, S const& formatStr, Args&&... args) { auto res = getInstance()->get(formatStr, localeName); - if constexpr (sizeof...(args) != 0) { return fmt::format(fmt::runtime(res), args...); } + if constexpr (sizeof...(args) != 0) { + return fmt::format(fmt::runtime(res), args...); + } return res; } diff --git a/src/ll/api/io/FileUtils.cpp b/src/ll/api/io/FileUtils.cpp index a89be70251..03fbf3dc0f 100644 --- a/src/ll/api/io/FileUtils.cpp +++ b/src/ll/api/io/FileUtils.cpp @@ -22,7 +22,9 @@ std::optional readFile(const fs::path& filePath, bool isBinary) { std::ios_base::openmode mode = std::ios_base::in; if (isBinary) mode |= std::ios_base::binary; fRead.open(filePath, mode); - if (!fRead.is_open()) { return std::nullopt; } + if (!fRead.is_open()) { + return std::nullopt; + } std::string data((std::istreambuf_iterator(fRead)), {}); fRead.close(); return data; @@ -33,7 +35,9 @@ bool writeFile(const fs::path& filePath, std::string_view content, bool isBinary std::ios_base::openmode mode = std::ios_base::out; if (isBinary) mode |= std::ios_base::binary; fWrite.open(filePath, mode); - if (!fWrite.is_open()) { return false; } + if (!fWrite.is_open()) { + return false; + } fWrite << content; fWrite.close(); return true; @@ -50,9 +54,13 @@ static bool getFileVersion( DWORD dwHandle = 0; DWORD dwLen = GetFileVersionInfoSizeW(filePath, &dwHandle); - if (0 >= dwLen) { return false; } + if (0 >= dwLen) { + return false; + } auto* pBlock = new (std::nothrow) wchar_t[dwLen]; - if (nullptr == pBlock) { return false; } + if (nullptr == pBlock) { + return false; + } if (!GetFileVersionInfoW(filePath, dwHandle, dwLen, pBlock)) { delete[] pBlock; return false; diff --git a/src/ll/api/memory/Closure.cpp b/src/ll/api/memory/Closure.cpp index f7cd373d31..7916db0767 100644 --- a/src/ll/api/memory/Closure.cpp +++ b/src/ll/api/memory/Closure.cpp @@ -7,7 +7,9 @@ namespace ll::memory::detail { size_t getVolatileOffset(void* fn) { for (size_t offset = 0; offset < 4096; offset++) { - if (*(uintptr_t*)((uintptr_t)fn + offset) == (uintptr_t)closureMagicNumber) { return offset; } + if (*(uintptr_t*)((uintptr_t)fn + offset) == (uintptr_t)closureMagicNumber) { + return offset; + } } throw std::runtime_error("can't parse closure asm offset"); }; diff --git a/src/ll/api/memory/Hook.h b/src/ll/api/memory/Hook.h index 33ff10c840..c3b8623da9 100644 --- a/src/ll/api/memory/Hook.h +++ b/src/ll/api/memory/Hook.h @@ -25,9 +25,13 @@ ); \ } \ fmt::print("\x1b[96m v resolve [" #IDENTIFIER "] to:\x1b[0m\r\n"); \ - for (auto& str : symbols) { fmt::print(" {} {}\r\n", (&str == &symbols.back()) ? '-' : '|', str); } \ + for (auto& str : symbols) { \ + fmt::print(" {} {}\r\n", (&str == &symbols.back()) ? '-' : '|', str); \ + } \ } \ - } catch (...) { fmt::print("\x1b[91m!!! Exception in resolve: [" #IDENTIFIER "]\x1b[0m\r\n"); } \ + } catch (...) { \ + fmt::print("\x1b[91m!!! Exception in resolve: [" #IDENTIFIER "]\x1b[0m\r\n"); \ + } \ return 0; \ }; \ static inline int debugging = debugger() @@ -138,7 +142,9 @@ struct HookAutoRegister { \ static int hook() { \ target = ll::memory::resolveIdentifier(IDENTIFIER); \ - if (target == nullptr) { return -1; } \ + if (target == nullptr) { \ + return -1; \ + } \ return ll::memory::hook( \ target, \ ll::memory::toFuncPtr(&DEF_TYPE::detour), \ diff --git a/src/ll/api/memory/Memory.cpp b/src/ll/api/memory/Memory.cpp index 70cbe2ad5a..3c85363718 100644 --- a/src/ll/api/memory/Memory.cpp +++ b/src/ll/api/memory/Memory.cpp @@ -64,9 +64,11 @@ FuncPtr resolveSignature(char const* signature) { std::vector lookupSymbol(FuncPtr func) { std::vector symbols; - size_t length; - auto result = pl::symbol_provider::pl_lookup_symbol(func, &length); - for (size_t i = 0; i < length; i++) { symbols.emplace_back(result[i]); } + size_t length; + auto result = pl::symbol_provider::pl_lookup_symbol(func, &length); + for (size_t i = 0; i < length; i++) { + symbols.emplace_back(result[i]); + } if (result) pl::symbol_provider::pl_free_lookup_result(result); return symbols; } diff --git a/src/ll/api/memory/Memory.h b/src/ll/api/memory/Memory.h index ce33f50a97..5190777243 100644 --- a/src/ll/api/memory/Memory.h +++ b/src/ll/api/memory/Memory.h @@ -119,13 +119,17 @@ constexpr auto construct(void* ptr, ptrdiff_t off, Types&&... args) { } [[nodiscard]] inline size_t getMemSizeFromPtr(void* ptr) { - if (!ptr) { return 0; } + if (!ptr) { + return 0; + } return _msize(ptr); } template [[nodiscard]] inline size_t getMemSizeFromPtr(std::unique_ptr& ptr) { - if (!ptr) { return 0; } + if (!ptr) { + return 0; + } return _msize(ptr.get()); } @@ -134,11 +138,17 @@ template