From fe7bd5df8cdf20add7306cda334a1cf9782b52ea Mon Sep 17 00:00:00 2001 From: maj00r Date: Sat, 27 Jun 2026 19:45:02 +0200 Subject: [PATCH] https://sonarcloud.io/project/issues?impactSoftwareQualities=SECURITY&issueStatuses=OPEN%2CCONFIRMED&id=MaSzyna-EU07_maszyna --- audio/audiorenderer.cpp | 37 +++--- audio/audiorenderer.h | 3 +- imgui/imgui.cpp | 228 ++++++++++++++++++++++------------- imgui/imgui_draw.cpp | 65 +++++----- imgui/imgui_impl_opengl3.cpp | 43 +++---- imgui/imgui_widgets.cpp | 24 ++-- input/messaging.cpp | 181 ++++++++++++++++----------- utilities/Logs.cpp | 137 ++++++++++----------- utilities/uart.cpp | 29 ++--- 9 files changed, 424 insertions(+), 323 deletions(-) diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index 20f7a64c..738c256e 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -7,6 +7,8 @@ obtain one at http://mozilla.org/MPL/2.0/. */ +#include + #include "stdafx.h" #include "audio/audiorenderer.h" @@ -506,23 +508,30 @@ openal_renderer::fetch_source() { return newsource; } +bool openal_renderer::logAvailableDevices() +{ + WriteLog("available audio devices:"); + + auto const *devices = ::alcGetString(nullptr, ALC_DEVICE_SPECIFIER); + if (!devices) + { + WriteLog("(none found)"); + return false; + } + + for (auto const* device = devices; *device; device += std::string_view(device).size() + 1) { + WriteLog(device); + } + return true; +} + bool openal_renderer::init_caps() { - if( ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATION_EXT" ) == AL_TRUE ) { - // enumeration supported - WriteLog( "available audio devices:" ); - auto const *devices { ::alcGetString( nullptr, ALC_DEVICE_SPECIFIER ) }; - auto const - *device { devices }, - *next { devices + 1 }; - while( (device) && (*device != '\0') && (next) && (*next != '\0') ) { - WriteLog( { device } ); - auto const len { std::strlen( device ) }; - device += ( len + 1 ); - next += ( len + 2 ); - } - } + if (::alcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT") == AL_TRUE + && !logAvailableDevices()) { + return false; + } // NOTE: default value of audio renderer variable is empty string, meaning argument of NULL i.e. 'preferred' device m_device = ::alcOpenDevice( Global.AudioRenderer.c_str() ); diff --git a/audio/audiorenderer.h b/audio/audiorenderer.h index 763279ce..ca2c4c2c 100644 --- a/audio/audiorenderer.h +++ b/audio/audiorenderer.h @@ -155,7 +155,8 @@ private: // returns an instance of implementation-side part of the sound emitter audio::openal_source fetch_source(); -// members + static bool logAvailableDevices(); + // members ALCdevice * m_device { nullptr }; ALCcontext * m_context { nullptr }; bool m_ready { false }; // renderer is initialized and functional diff --git a/imgui/imgui.cpp b/imgui/imgui.cpp index 93b15ddb..2d413663 100644 --- a/imgui/imgui.cpp +++ b/imgui/imgui.cpp @@ -972,8 +972,10 @@ CODE #endif #include "imgui_internal.h" +#include #include // toupper #include // vsnprintf, sscanf, printf +#include #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include // intptr_t #else @@ -1347,11 +1349,18 @@ int ImStrnicmp(const char* str1, const char* str2, size_t count) void ImStrncpy(char* dst, const char* src, size_t count) { - if (count < 1) - return; - if (count > 1) - strncpy(dst, src, count - 1); - dst[count - 1] = 0; + if (count == 0) + { + return; + } + + auto src_len = std::string_view(src).size(); + auto copy_len = src_len < count - 1 + ? src_len + : count - 1; + + std::memcpy(dst, src, copy_len); + dst[copy_len] = '\0'; } char* ImStrdup(const char* str) @@ -1363,22 +1372,38 @@ char* ImStrdup(const char* str) char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) { - size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1; - size_t src_size = strlen(src) + 1; - if (dst_buf_size < src_size) - { - IM_FREE(dst); - dst = (char*)IM_ALLOC(src_size); - if (p_dst_size) - *p_dst_size = src_size; - } - return (char*)memcpy(dst, (const void*)src, src_size); + if (!src) { + return dst; + } + + size_t src_size = strlen(src) + 1; + size_t dst_size = 0; + + if (dst) { + dst_size = p_dst_size ? *p_dst_size : strlen(dst) + 1; + } + + if (!dst || dst_size < src_size) { + if (dst) { + IM_FREE(dst); + } + dst = static_cast(IM_ALLOC(src_size)); + if (p_dst_size) { + *p_dst_size = src_size; + } + } + + return static_cast(memcpy(dst, src, src_size)); } const char* ImStrchrRange(const char* str, const char* str_end, char c) { - const char* p = (const char*)memchr(str, (int)c, str_end - str); - return p; + if (!str || !str_end || str >= str_end) { + return nullptr; + } + + const auto len = static_cast(str_end - str); + return static_cast(std::memchr(str, c, len)); } int ImStrlenW(const ImWchar* str) @@ -1405,8 +1430,16 @@ const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) { - if (!needle_end) - needle_end = needle + strlen(needle); + if (!needle) + { + return nullptr; + } + + std::string_view needle_view(needle); + if (!needle_end) + { + needle_end = needle + needle_view.size(); + } const char un0 = (char)toupper(*needle); while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) @@ -2107,25 +2140,26 @@ void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector f.b && ImCharIsBlankA(f.e[-1])) - f.e--; - if (f.empty()) - continue; - if (Filters[i].b[0] != '-') - CountGrep += 1; - } + const std::string_view input_view(InputBuf); + ImGuiTextRange input_range(input_view.data(), input_view.data() + input_view.size()); + input_range.split(',', &Filters); + + CountGrep = 0; + for (int i = 0; i < Filters.Size; i++) + { + ImGuiTextRange& f = Filters[i]; + while (f.b < f.e && ImCharIsBlankA(f.b[0])) + f.b++; + while (f.e > f.b && ImCharIsBlankA(f.e[-1])) + f.e--; + if (f.empty()) + continue; + if (f.b[0] != '-') + CountGrep++; + } } - bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (Filters.empty()) @@ -2178,20 +2212,32 @@ char ImGuiTextBuffer::EmptyString[1] = { 0 }; void ImGuiTextBuffer::append(const char* str, const char* str_end) { - int len = str_end ? (int)(str_end - str) : (int)strlen(str); + if (!str) + { + return; + } - // Add zero-terminator the first time - const int write_off = (Buf.Size != 0) ? Buf.Size : 1; - const int needed_sz = write_off + len; - if (write_off + len >= Buf.Capacity) - { - int new_capacity = Buf.Capacity * 2; - Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); - } + const std::string_view sv(str, str_end + ? static_cast(str_end - str) + : std::char_traits::length(str)); - Buf.resize(needed_sz); - memcpy(&Buf[write_off - 1], str, (size_t)len); - Buf[write_off - 1 + len] = 0; + if (sv.empty()) + { + return; + } + + const auto write_off = Buf.empty() + ? 1 + : static_cast(Buf.Size); + const auto needed_sz = write_off + sv.size(); + + if (needed_sz >= static_cast(Buf.Capacity)) { + Buf.reserve(static_cast(std::max(needed_sz, static_cast(Buf.Capacity * 2)))); + } + + Buf.resize(static_cast(needed_sz)); + std::memcpy(Buf.Data + write_off - 1, sv.data(), sv.size()); + Buf[write_off - 1 + sv.size()] = '\0'; } void ImGuiTextBuffer::appendf(const char* fmt, ...) @@ -2385,44 +2431,50 @@ const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; - // Hide anything after a '##' string - const char* text_display_end; - 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; - } + // Hide anything after a '##' string + const char* text_display_end; + if (hide_text_after_hash) + { + text_display_end = FindRenderedTextEnd(text, text_end); + } + else + { + if (!text_end) + { + text_end = text + std::string_view(text).size(); + } + text_display_end = text_end; + } - if (text != text_display_end) - { - window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); - if (g.LogEnabled) - LogRenderedText(&pos, text, text_display_end); - } + if (text != text_display_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_display_end); + } } void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; - if (!text_end) - text_end = text + strlen(text); // FIXME-OPT + if (!text_end) + { + text_end = text + std::string_view(text).size(); + } - if (text != text_end) - { - window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); - if (g.LogEnabled) - LogRenderedText(&pos, text, text_end); - } + if (text != text_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); + if (g.LogEnabled) + { + LogRenderedText(&pos, text, text_end); + } + } } // Default clip_rect uses (pos_min,pos_max) @@ -2682,7 +2734,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) WindowPadding = ImVec2(0.0f, 0.0f); WindowRounding = 0.0f; WindowBorderSize = 0.0f; - NameBufLen = (int)strlen(name) + 1; + NameBufLen = static_cast(std::string_view(name).size()) + 1; MoveId = GetID("#MOVE"); ChildId = 0; Scroll = ImVec2(0.0f, 0.0f); @@ -9446,16 +9498,18 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. if (ini_size == 0) - ini_size = strlen(ini_data); - char* buf = (char*)IM_ALLOC(ini_size + 1); + { + ini_size = std::string_view(ini_data).size(); + } + char* buf = static_cast(IM_ALLOC(ini_size + 1)); char* buf_end = buf + ini_size; memcpy(buf, ini_data, ini_size); buf[ini_size] = 0; - void* entry_data = NULL; - ImGuiSettingsHandler* entry_handler = NULL; + void* entry_data = nullptr; + ImGuiSettingsHandler* entry_handler = nullptr; - char* line_end = NULL; + char* line_end = nullptr; for (char* line = buf; line < buf_end; line = line_end + 1) { // Skip new lines markers, then find end of the line @@ -9474,7 +9528,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) const char* name_end = line_end - 1; const char* type_start = line + 1; char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']'); - const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; + const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : nullptr; if (!type_end || !name_start) { name_start = type_start; // Import legacy entries that have no type @@ -9486,9 +9540,9 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) name_start++; // Skip second '[' } entry_handler = FindSettingsHandler(type_start); - entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL; + entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : nullptr; } - else if (entry_handler != NULL && entry_data != NULL) + else if (entry_handler != nullptr && entry_data != nullptr) { // Let type handler parse the line entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); diff --git a/imgui/imgui_draw.cpp b/imgui/imgui_draw.cpp index 845cd04e..f1c08178 100644 --- a/imgui/imgui_draw.cpp +++ b/imgui/imgui_draw.cpp @@ -33,6 +33,7 @@ Index of this file: #include "imgui_internal.h" #include // vsnprintf, sscanf, printf +#include #if !defined(alloca) #if defined(__GLIBC__) || defined(__sun) || defined(__CYGWIN__) || defined(__APPLE__) || defined(__SWITCH__) #include // alloca (glibc uses . Note that Cygwin may have _WIN32 defined, so the order matters here) @@ -1105,13 +1106,13 @@ void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, if ((col & IM_COL32_A_MASK) == 0) return; - if (text_end == NULL) - text_end = text_begin + strlen(text_begin); + if (text_end == nullptr) + text_end = text_begin + std::string_view(text_begin).size();; if (text_begin == text_end) return; // Pull default font/size from the shared ImDrawListSharedData instance - if (font == NULL) + if (font == nullptr) font = _Data->Font; if (font_size == 0.0f) font_size = _Data->FontSize; @@ -1715,12 +1716,13 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_d ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) { - int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; - void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size); - Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); - ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); - IM_FREE(compressed_ttf); - return font; + const size_t len = std::string_view(compressed_ttf_data_base85).size(); + const int compressed_ttf_size = (static_cast(len) + 4) / 5 * 4; + void* compressed_ttf = IM_ALLOC(static_cast(compressed_ttf_size)); + Decode85(reinterpret_cast(compressed_ttf_data_base85), static_cast(compressed_ttf)); + ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); + IM_FREE(compressed_ttf); + return font; } int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) @@ -2735,7 +2737,9 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const { if (!text_end) - text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. + { + text_end = text_begin + std::string_view(text_begin).size(); + } const float line_height = size; const float scale = size / FontSize; @@ -2744,7 +2748,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons float line_width = 0.0f; const bool word_wrap_enabled = (wrap_width > 0.0f); - const char* word_wrap_eol = NULL; + const char* word_wrap_eol = nullptr; const char* s = text_begin; while (s < text_end) @@ -2765,7 +2769,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons text_size.x = line_width; text_size.y += line_height; line_width = 0.0f; - word_wrap_eol = NULL; + word_wrap_eol = nullptr; // Wrapping skips upcoming blanks while (s < text_end) @@ -2779,7 +2783,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons // Decode and advance source const char* prev_s = s; - unsigned int c = (unsigned int)*s; + auto c = static_cast(*s); if (c < 0x80) { s += 1; @@ -2839,15 +2843,16 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); } } - void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const { if (!text_end) - text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. + { + text_end = text_begin + std::string_view(text_begin).size(); + } // Align to be pixel perfect - pos.x = (float)(int)pos.x + DisplayOffset.x; - pos.y = (float)(int)pos.y + DisplayOffset.y; + pos.x = static_cast(static_cast(pos.x)) + DisplayOffset.x; + pos.y = static_cast(static_cast(pos.y)) + DisplayOffset.y; float x = pos.x; float y = pos.y; if (y > clip_rect.w) @@ -2856,7 +2861,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col const float scale = size / FontSize; const float line_height = FontSize * scale; const bool word_wrap_enabled = (wrap_width > 0.0f); - const char* word_wrap_eol = NULL; + const char* word_wrap_eol = nullptr; // Fast-forward to first visible line const char* s = text_begin; @@ -2876,7 +2881,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col float y_end = y; while (y_end < clip_rect.w && s_end < text_end) { - s_end = (const char*)memchr(s_end, '\n', text_end - s_end); + s_end = static_cast(memchr(s_end, '\n', text_end - s_end)); s_end = s_end ? s_end + 1 : text_end; y_end += line_height; } @@ -2886,8 +2891,8 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col return; // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) - const int vtx_count_max = (int)(text_end - s) * 4; - const int idx_count_max = (int)(text_end - s) * 6; + const int vtx_count_max = static_cast(text_end - s) * 4; + const int idx_count_max = static_cast(text_end - s) * 6; const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; draw_list->PrimReserve(idx_count_max, vtx_count_max); @@ -2911,7 +2916,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col { x = pos.x; y += line_height; - word_wrap_eol = NULL; + word_wrap_eol = nullptr; // Wrapping skips upcoming blanks while (s < text_end) @@ -2924,7 +2929,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col } // Decode and advance source - unsigned int c = (unsigned int)*s; + auto c = static_cast(*s); if (c < 0x80) { s += 1; @@ -2951,7 +2956,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col } float char_width = 0.0f; - if (const ImFontGlyph* glyph = FindGlyph((ImWchar)c)) + if (const ImFontGlyph* glyph = FindGlyph(static_cast(c))) { char_width = glyph->AdvanceX * scale; @@ -3003,8 +3008,12 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here: { - idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2); - idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3); + idx_write[0] = static_cast(vtx_current_idx); + idx_write[1] = static_cast(vtx_current_idx + 1); + idx_write[2] = static_cast(vtx_current_idx + 2); + idx_write[3] = static_cast(vtx_current_idx); + idx_write[4] = static_cast(vtx_current_idx + 2); + idx_write[5] = static_cast(vtx_current_idx + 3); vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1; vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1; vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2; @@ -3021,8 +3030,8 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col } // Give back unused vertices - draw_list->VtxBuffer.resize((int)(vtx_write - draw_list->VtxBuffer.Data)); - draw_list->IdxBuffer.resize((int)(idx_write - draw_list->IdxBuffer.Data)); + draw_list->VtxBuffer.resize(static_cast(vtx_write - draw_list->VtxBuffer.Data)); + draw_list->IdxBuffer.resize(static_cast(idx_write - draw_list->IdxBuffer.Data)); draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); draw_list->_VtxWritePtr = vtx_write; draw_list->_IdxWritePtr = idx_write; diff --git a/imgui/imgui_impl_opengl3.cpp b/imgui/imgui_impl_opengl3.cpp index e4bf631c..554bcc20 100644 --- a/imgui/imgui_impl_opengl3.cpp +++ b/imgui/imgui_impl_opengl3.cpp @@ -84,41 +84,38 @@ static unsigned int g_VboHandle = 0, g_ElementsHandle = 0; static int IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX = 0; // Functions -bool ImGui_ImplOpenGL3_Init(const char* glsl_version) +bool ImGui_ImplOpenGL3_Init(const char* glsl_version) { - // Setup back-end capabilities flags - ImGuiIO& io = ImGui::GetIO(); - io.BackendRendererName = "imgui_impl_opengl3"; + ImGuiIO& io = ImGui::GetIO(); + io.BackendRendererName = "imgui_impl_opengl3"; - if (GLAD_GL_VERSION_3_3 || GLAD_GL_ES_VERSION_3_2) - IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX = 1; + if (GLAD_GL_VERSION_3_3 || GLAD_GL_ES_VERSION_3_2) + IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX = 1; #if IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX - io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; #endif - // Store GLSL version string so we can refer to it later in case we recreate shaders. Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure. #if defined(IMGUI_IMPL_OPENGL_ES2) - if (glsl_version == NULL) - glsl_version = "#version 100"; + if (!glsl_version) glsl_version = "#version 100"; #elif defined(IMGUI_IMPL_OPENGL_ES3) - if (glsl_version == NULL) - glsl_version = "#version 300 es"; + if (!glsl_version) glsl_version = "#version 300 es"; #else - if (glsl_version == NULL) - glsl_version = "#version 130"; + if (!glsl_version) glsl_version = "#version 130"; #endif - IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(g_GlslVersionString)); - strcpy(g_GlslVersionString, glsl_version); - strcat(g_GlslVersionString, "\n"); - // Make a dummy GL call (we don't actually need the result) - // IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code. - // Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above. - GLint current_texture; - glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤t_texture); + const std::string_view v(glsl_version); + const size_t len = v.size(); - return true; + IM_ASSERT(len + 2 < IM_ARRAYSIZE(g_GlslVersionString)); + std::memcpy(g_GlslVersionString, v.data(), len); + g_GlslVersionString[len] = '\n'; + g_GlslVersionString[len + 1] = '\0'; + + GLint current_texture; + glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤t_texture); + + return true; } void ImGui_ImplOpenGL3_Shutdown() diff --git a/imgui/imgui_widgets.cpp b/imgui/imgui_widgets.cpp index d9ca11e5..e5a41239 100644 --- a/imgui/imgui_widgets.cpp +++ b/imgui/imgui_widgets.cpp @@ -28,6 +28,7 @@ Index of this file: */ +#include #ifdef DBG_NEW #undef new #endif @@ -143,8 +144,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) IM_ASSERT(text != NULL); const char* text_begin = text; if (text_end == NULL) - text_end = text + strlen(text); // FIXME-OPT - + text_end = text + std::string_view(text).size(); const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); const float wrap_pos_x = window->DC.TextWrapPos; const bool wrap_enabled = (wrap_pos_x >= 0.0f); @@ -1550,7 +1550,7 @@ static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) { if (idx == items_count) break; - p += strlen(p) + 1; + p += std::string_view(p).size() + 1; items_count++; } if (!*p) @@ -1615,7 +1615,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open while (*p) { - p += strlen(p) + 1; + p += std::string_view(p).size() + 1; items_count++; } bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); @@ -3285,7 +3285,9 @@ void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count) void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) { const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; - const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); + const int new_text_len = new_text_end + ? static_cast(new_text_end - new_text) + : static_cast(std::string_view(new_text).size()); if (new_text_len + BufTextLen >= BufSize) { if (!is_resizable) @@ -3470,7 +3472,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) - const int buf_len = (int)strlen(buf); + const int buf_len = static_cast(std::string_view(buf).size()); state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. memcpy(state->InitialTextA.Data, buf, buf_len + 1); @@ -3738,7 +3740,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (const char* clipboard = GetClipboardText()) { // Filter pasted buffer - const int clipboard_len = (int)strlen(clipboard); + const int clipboard_len = static_cast(std::string_view(clipboard).size()); ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len+1) * sizeof(ImWchar)); int clipboard_filtered_len = 0; for (const char* s = clipboard; *s; ) @@ -3855,7 +3857,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (callback_data.SelectionEnd != utf8_selection_end) { state->Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } if (callback_data.BufDirty) { - IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! + IM_ASSERT(callback_data.BufTextLen == static_cast(std::string_view(callback_data.Buf).size())); // You need to maintain BufTextLen if you change the text! if (callback_data.BufTextLen > backup_current_text_length && is_resizable) state->TextW.resize(state->TextW.Size + (callback_data.BufTextLen - backup_current_text_length)); state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, callback_data.Buf, NULL); @@ -3928,7 +3930,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_displaying_hint) { buf_display = hint; - buf_display_end = hint + strlen(hint); + buf_display_end = hint + std::string_view(hint).size(); } // Render text. We currently only render selection when the widget is active or while scrolling. @@ -4098,7 +4100,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else if (!is_displaying_hint && g.ActiveId == id) buf_display_end = buf_display + state->CurLenA; else if (!is_displaying_hint) - buf_display_end = buf_display + strlen(buf_display); + buf_display_end = buf_display + std::string_view(buf_display).size(); if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) { @@ -6924,7 +6926,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Append name with zero-terminator tab->NameOffset = tab_bar->TabsNames.size(); - tab_bar->TabsNames.append(label, label + strlen(label) + 1); + tab_bar->TabsNames.append(label, label + std::string_view(label).size() + 1); // If we are not reorderable, always reset offset based on submission order. // (We already handled layout and sizing using the previous known order, but sizing is not affected by order!) diff --git a/input/messaging.cpp b/input/messaging.cpp index b3c48f40..3263d75e 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -34,10 +34,9 @@ std::uint32_t const EU07_MESSAGEHEADER { MAKE_ID4( 'E','U','0','7' ) }; void Navigate(std::string const &ClassName, UINT Msg, WPARAM wParam, LPARAM lParam) { #ifdef _WIN32 - // wysłanie komunikatu do sterującego - HWND h = FindWindow(ClassName.c_str(), 0); // można by to zapamiętać - if (h == 0) - h = FindWindow(0, ClassName.c_str()); // można by to zapamiętać + HWND h = FindWindow(ClassName.c_str(), nullptr); + if (h == nullptr) + h = FindWindow(nullptr, ClassName.c_str()); SendMessage(h, Msg, wParam, lParam); #endif } @@ -59,10 +58,10 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) case 2: { // event CommLog( Now() + " " + std::to_string( pRozkaz->iComm ) + " " + - std::string( pRozkaz->cString + 1, (unsigned)( pRozkaz->cString[ 0 ] ) ) + " rcvd" ); + std::string( pRozkaz->cString + 1, static_cast( pRozkaz->cString[ 0 ] ) ) + " rcvd" ); if( Global.iMultiplayer ) { - auto *event = simulation::Events.FindEvent( std::string( pRozkaz->cString + 1, (unsigned)( pRozkaz->cString[ 0 ] ) ) ); + auto *event = simulation::Events.FindEvent( std::string( pRozkaz->cString + 1, static_cast( pRozkaz->cString[ 0 ] ) ) ); if( event != nullptr ) { if( ( typeid( *event ) == typeid( multi_event ) ) || ( typeid( *event ) == typeid( lights_event ) ) @@ -78,13 +77,13 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) case 3: // rozkaz dla AI if (Global.iMultiplayer) { - int i = int(pRozkaz->cString[8]); // długość pierwszego łańcucha (z przodu dwa floaty) + int i = pRozkaz->cString[8]; // długość pierwszego łańcucha (z przodu dwa floaty) CommLog( Now() + " " + std::to_string(pRozkaz->iComm) + " " + - std::string(pRozkaz->cString + 11 + i, (unsigned)(pRozkaz->cString[10 + i])) + + std::string(pRozkaz->cString + 11 + i, static_cast(pRozkaz->cString[10 + i])) + " rcvd"); - // nazwa pojazdu jest druga - auto *vehicle = simulation::Vehicles.find( { pRozkaz->cString + 11 + i, (unsigned)pRozkaz->cString[ 10 + i ] } ); + // nazwa pojazdu jest druga + auto *vehicle = simulation::Vehicles.find( { pRozkaz->cString + 11 + i, static_cast(pRozkaz->cString[ 10 + i ] ) } ); if( ( vehicle != nullptr ) && ( vehicle->Mechanik != nullptr ) ) { vehicle->Mechanik->PutCommand( @@ -92,16 +91,16 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) pRozkaz->fPar[0], pRozkaz->fPar[1], nullptr, stopExt ); // floaty są z przodu - WriteLog("AI command: " + std::string(pRozkaz->cString + 9, i)); + WriteLog("AI command: " + std::string(pRozkaz->cString + 9, static_cast(i))); } } break; case 4: // badanie zajętości toru { - CommLog(Now() + " " + std::to_string(pRozkaz->iComm) + " " + - std::string(pRozkaz->cString + 1, (unsigned)(pRozkaz->cString[0])) + " rcvd"); + CommLog(Now() + " " + std::to_string(pRozkaz->iComm) + " " + + std::string(pRozkaz->cString + 1, static_cast(pRozkaz->cString[0])) + " rcvd"); - auto *track = simulation::Paths.find( std::string( pRozkaz->cString + 1, (unsigned)( pRozkaz->cString[ 0 ] ) ) ); + auto *track = simulation::Paths.find( std::string( pRozkaz->cString + 1, static_cast( pRozkaz->cString[ 0 ] ) ) ); if( ( track != nullptr ) && ( track->IsEmpty() ) ) { WyslijWolny( track->name() ); @@ -134,14 +133,14 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) CommLog( Now() + " " + std::to_string( pRozkaz->iComm ) + " " - + std::string{ pRozkaz->cString + 1, (unsigned)( pRozkaz->cString[ 0 ] ) } + + std::string{ pRozkaz->cString + 1, static_cast(pRozkaz->cString[0]) } + " rcvd" ); if (pRozkaz->cString[0]) { // jeśli długość nazwy jest niezerowa szukamy pierwszego pojazdu o takiej nazwie i odsyłamy parametry ramką #7 auto *vehicle = ( pRozkaz->cString[ 1 ] == '*' ? - simulation::Train->Dynamic() : - simulation::Vehicles.find( std::string{ pRozkaz->cString + 1, (unsigned)pRozkaz->cString[ 0 ] } ) ); + simulation::Train->Dynamic() : + simulation::Vehicles.find( std::string{ pRozkaz->cString + 1, static_cast(pRozkaz->cString[ 0 ] ) } ) ); if( vehicle != nullptr ) { WyslijNamiary( vehicle ); // wysłanie informacji o pojeździe } @@ -182,7 +181,7 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) auto *lookup = ( pRozkaz->cString[ 2 ] == '*' ? simulation::Train->Dynamic() : // nazwa pojazdu użytkownika - simulation::Vehicles.find( std::string( pRozkaz->cString + 2, (unsigned)pRozkaz->cString[ 1 ] ) ) ); // nazwa pojazdu + simulation::Vehicles.find( std::string( pRozkaz->cString + 2, static_cast(pRozkaz->cString[1]) ) ) ); // nazwa pojazdu if( lookup == nullptr ) { break; } // nothing found, nothing to do auto *d { lookup }; while( d != nullptr ) { @@ -206,20 +205,38 @@ void WyslijEvent(const std::string &e, const std::string &d) { // Ra: jeszcze do wyczyszczenia #ifdef _WIN32 - DaneRozkaz r; + DaneRozkaz r{}; r.iSygn = EU07_MESSAGEHEADER; r.iComm = 2; // 2 - event - size_t i = e.length(), j = d.length(); - r.cString[0] = char(i); - strcpy(r.cString + 1, e.c_str()); // zakończony zerem - r.cString[i + 2] = char(j); // licznik po zerze kończącym - strcpy(r.cString + 3 + i, d.c_str()); // zakończony zerem + + const std::string_view ev(e); + const std::string_view data(d); + + const size_t i = ev.size(); + const size_t j = data.size(); + const size_t total_size = 12 + i + j; + + if (total_size > sizeof(r.cString)) { + ErrorLog("Event data too large: " + std::to_string(total_size)); + return; + } + + r.cString[0] = static_cast(i); + std::memcpy(r.cString + 1, ev.data(), i + 1); + + r.cString[i + 2] = static_cast(j); + std::memcpy(r.cString + 3 + i, data.data(), j + 1); + COPYDATASTRUCT cData; - cData.dwData = EU07_MESSAGEHEADER; // sygnatura - cData.cbData = (DWORD)(12 + i + j); // 8+dwa liczniki i dwa zera kończące + cData.dwData = EU07_MESSAGEHEADER; + cData.cbData = static_cast(total_size); cData.lpData = &r; - Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Application.window() ), (LPARAM)&cData ); - CommLog( Now() + " " + std::to_string(r.iComm) + " " + e + " sent" ); + + Navigate("TEU07SRK", WM_COPYDATA, + reinterpret_cast(glfwGetWin32Window(Application.window())), + reinterpret_cast(&cData)); + + CommLog(Now() + " " + std::to_string(r.iComm) + " " + e + " sent"); #endif } @@ -227,19 +244,27 @@ void WyslijUszkodzenia(const std::string &t, char fl) { // wysłanie informacji w postaci pojedynczego tekstu #ifdef _WIN32 - DaneRozkaz r; + DaneRozkaz r{}; r.iSygn = EU07_MESSAGEHEADER; - r.iComm = 13; // numer komunikatu - size_t i = t.length(); - r.cString[0] = char(fl); - r.cString[1] = char(i); - strcpy(r.cString + 2, t.c_str()); // z zerem kończącym - COPYDATASTRUCT cData; - cData.dwData = EU07_MESSAGEHEADER; // sygnatura - cData.cbData = (DWORD)(11 + i); // 8+licznik i zero kończące - cData.lpData = &r; - Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Application.window() ), (LPARAM)&cData ); - CommLog( Now() + " " + std::to_string(r.iComm) + " " + t + " sent"); + r.iComm = 13; + + const std::string_view tv(t); + const size_t i = tv.size(); + + r.cString[0] = fl; + r.cString[1] = static_cast(i); + std::memcpy(r.cString + 2, tv.data(), i + 1); + + COPYDATASTRUCT cData; + cData.dwData = EU07_MESSAGEHEADER; + cData.cbData = static_cast(11 + i); + cData.lpData = &r; + + Navigate("TEU07SRK", WM_COPYDATA, + reinterpret_cast(glfwGetWin32Window(Application.window())), + reinterpret_cast(&cData)); + + CommLog(Now() + " " + std::to_string(r.iComm) + " " + t + " sent"); #endif } @@ -247,32 +272,40 @@ void WyslijString(const std::string &t, int n) { // wysłanie informacji w postaci pojedynczego tekstu #ifdef _WIN32 - DaneRozkaz r; + DaneRozkaz r{}; r.iSygn = EU07_MESSAGEHEADER; - r.iComm = n; // numer komunikatu - size_t i = t.length(); - r.cString[0] = char(i); - strcpy(r.cString + 1, t.c_str()); // z zerem kończącym + r.iComm = n; + + const std::string_view tv(t); + const size_t i = tv.size(); + + r.cString[0] = static_cast(i); + std::memcpy(r.cString + 1, tv.data(), i + 1); + COPYDATASTRUCT cData; - cData.dwData = EU07_MESSAGEHEADER; // sygnatura - cData.cbData = (DWORD)(10 + i); // 8+licznik i zero kończące + cData.dwData = EU07_MESSAGEHEADER; + cData.cbData = static_cast(10 + i); cData.lpData = &r; - Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Application.window() ), (LPARAM)&cData ); - CommLog( Now() + " " + std::to_string(r.iComm) + " " + t + " sent"); + + Navigate("TEU07SRK", WM_COPYDATA, + reinterpret_cast(glfwGetWin32Window(Application.window())), + reinterpret_cast(&cData)); + + CommLog(Now() + " " + std::to_string(r.iComm) + " " + t + " sent"); #endif } void WyslijWolny(const std::string &t) -{ // Ra: jeszcze do wyczyszczenia - WyslijString(t, 4); // tor wolny +{ + WyslijString(t, 4); } void WyslijNamiary(TDynamicObject const *Vehicle) -{ // wysłanie informacji o pojeździe - (float), długość ramki będzie zwiększana w miarę potrzeby +{ #ifdef _WIN32 - DaneRozkaz r; + DaneRozkaz r{}; r.iSygn = EU07_MESSAGEHEADER; r.iComm = 7; // 7 - dane pojazdu int i = 32; @@ -366,28 +399,34 @@ WyslijObsadzone() int i = 0; for( auto *vehicle : vehiclelist ) { if( vehicle->Mechanik ) { - strcpy( r.cString + 64 * i, vehicle->asName.c_str() ); - r.fPar[ 16 * i + 4 ] = vehicle->GetPosition().x; - r.fPar[ 16 * i + 5 ] = vehicle->GetPosition().y; - r.fPar[ 16 * i + 6 ] = vehicle->GetPosition().z; - r.iPar[ 16 * i + 7 ] = static_cast( vehicle->Mechanik->action() ); - strcpy( r.cString + 64 * i + 32, vehicle->GetTrack()->RemoteIsolatedName().c_str() ); - strcpy( r.cString + 64 * i + 48, vehicle->Mechanik->TrainName().c_str() ); + const std::string_view name(vehicle->asName); + const std::string_view track(vehicle->GetTrack()->RemoteIsolatedName()); + const std::string_view train(vehicle->Mechanik->TrainName()); + + std::memcpy(r.cString + 64 * i, name.data(), std::min(name.size() + 1, static_cast(64))); + r.fPar[16 * i + 4] = vehicle->GetPosition().x; + r.fPar[16 * i + 5] = vehicle->GetPosition().y; + r.fPar[16 * i + 6] = vehicle->GetPosition().z; + r.iPar[16 * i + 7] = static_cast(vehicle->Mechanik->action()); + std::memcpy(r.cString + 64 * i + 32, track.data(), std::min(track.size() + 1, static_cast(32))); + std::memcpy(r.cString + 64 * i + 48, train.data(), std::min(train.size() + 1, static_cast(16))); i++; if( i > 30 ) break; } } - while (i <= 30) - { - strcpy(r.cString + 64 * i, "none"); - r.fPar[16 * i + 4] = 1; - r.fPar[16 * i + 5] = 2; - r.fPar[16 * i + 6] = 3; - r.iPar[16 * i + 7] = 0; - strcpy(r.cString + 64 * i + 32, "none"); - strcpy(r.cString + 64 * i + 48, "none"); - i++; - } + + while (i <= 30) + { + const char* none = "none"; + std::memcpy(r.cString + 64 * i, none, 5); + r.fPar[16 * i + 4] = 1; + r.fPar[16 * i + 5] = 2; + r.fPar[16 * i + 6] = 3; + r.iPar[16 * i + 7] = 0; + std::memcpy(r.cString + 64 * i + 32, none, 5); + std::memcpy(r.cString + 64 * i + 48, none, 5); + i++; + } COPYDATASTRUCT cData; cData.dwData = EU07_MESSAGEHEADER; // sygnatura diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index 48d74317..e49d515a 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -76,88 +76,77 @@ std::deque ErrorStack; // lock for log stacks std::mutex logMutex; - void LogService() { - // prevent crash if mutex is not initialized - while (true) - { - try - { - logMutex.lock(); - break; - } - catch (...) {} - } - logMutex.unlock(); + while (!Global.applicationQuitOrder) + { + // --- Obsługa InfoStack --- + while (!InfoStack.empty()) + { + std::string msg; + bool isError; + { + std::lock_guard lock(logMutex); + msg = std::move(InfoStack.front().first); + isError = InfoStack.front().second; + InfoStack.pop_front(); + } - while (!Global.applicationQuitOrder) - { - { - // --- Obsługa InfoStack --- - while (!InfoStack.empty()) - { - logMutex.lock(); - std::string msg = InfoStack.front().first; - bool isError = InfoStack.front().second; - InfoStack.pop_front(); - logMutex.unlock(); + // log to file + if (Global.iWriteLogEnabled & 1) + { + if (!output.is_open()) + { + std::string filename = (Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"); + output.open(filename, std::ios::trunc); + } + output << msg << "\n"; + output.flush(); + } - // log to file - if (Global.iWriteLogEnabled & 1) - { - if (!output.is_open()) - { - std::string filename = (Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"); - output.open(filename, std::ios::trunc); - } - output << msg << "\n"; - output.flush(); - } + // log to scrollback imgui + log_scrollback.emplace_back(std::move(msg)); + if (log_scrollback.size() > 200) + log_scrollback.pop_front(); - // log to scrollback imgui - log_scrollback.emplace_back(msg); - if (log_scrollback.size() > 200) - log_scrollback.pop_front(); + // log to console + if (Global.iWriteLogEnabled & 2) + { + if (isError) + printf("\033[1;37;41m%s\033[0m\n", msg.c_str()); + else + printf("\033[32m%s\033[0m\n", msg.c_str()); + } + } - // log to console - if (Global.iWriteLogEnabled & 2) - { - if (isError) - printf("\033[1;37;41m%s\033[0m\n", msg.c_str()); - else - printf("\033[32m%s\033[0m\n", msg.c_str()); - } - } + // --- Obsługa ErrorStack --- + while (!ErrorStack.empty()) + { + std::string msg; + { + std::lock_guard lock(logMutex); + msg = std::move(ErrorStack.front()); + ErrorStack.pop_front(); + } - // --- Obsługa ErrorStack --- - while (!ErrorStack.empty()) - { - logMutex.lock(); - std::string msg = ErrorStack.front(); - ErrorStack.pop_front(); - logMutex.unlock(); + if (!(Global.iWriteLogEnabled & 1)) + continue; - if (!(Global.iWriteLogEnabled & 1)) - continue; + if (!errors.is_open()) + { + std::string filename = (Global.MultipleLogs ? "logs/errors (" + filename_scenery() + ") " + filename_date() + ".txt" : "errors.txt"); + errors.open(filename, std::ios::trunc); + errors << "EU07.EXE " + Global.asVersion << "\n"; + } - if (!errors.is_open()) - { - std::string filename = (Global.MultipleLogs ? "logs/errors (" + filename_scenery() + ") " + filename_date() + ".txt" : "errors.txt"); - errors.open(filename, std::ios::trunc); - errors << "EU07.EXE " + Global.asVersion << "\n"; - } + errors << msg << "\n"; + errors.flush(); + } - errors << msg << "\n"; - errors.flush(); - } - } - - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - } + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } } - bool ShouldSkipLog(std::string_view str, logtype type) { return str.empty() || @@ -180,8 +169,8 @@ void WriteLog(std::string_view str, logtype type, bool isError) const auto message = FormatLogMessage(str); - std::lock_guard lock(logMutex); - InfoStack.push_back({message, isError}); + std::lock_guard lock(logMutex); + InfoStack.emplace_back(message, isError); } void ErrorLog(std::string_view str, logtype type) @@ -191,8 +180,8 @@ void ErrorLog(std::string_view str, logtype type) const auto message = FormatLogMessage(str); - std::lock_guard lock(logMutex); - ErrorStack.push_back(message); + std::lock_guard lock(logMutex); + ErrorStack.emplace_back(message); } void WriteLog(const char* str, logtype type, bool isError) diff --git a/utilities/uart.cpp b/utilities/uart.cpp index 525453bf..b6f1a0e8 100644 --- a/utilities/uart.cpp +++ b/utilities/uart.cpp @@ -407,14 +407,15 @@ void uart_input::poll() memmove(&buffer[0], &tmp_buffer[4], 16); UartStatus.packets_received++; - if (conf.debug) - { - char buf[buffer.size() * 3 + 1]; - size_t pos = 0; - for (uint8_t b : buffer) - pos += sprintf(&buf[pos], "%02X ", b); - WriteLog("uart: rx: " + std::string(buf)); - } + if (conf.debug) + { + std::string hex; + hex.reserve(buffer.size() * 3); + for (uint8_t b : buffer) { + hex += std::format("{:02X} ", b); + } + WriteLog("uart: rx: " + hex); + } data_pending = false; @@ -635,12 +636,12 @@ void uart_input::poll() if (conf.debug) { - char buf[buffer.size() * 3 + 1]; - buf[ buffer.size() * 3 ] = 0; - size_t pos = 0; - for (uint8_t b : buffer) - pos += sprintf(&buf[pos], "%02X ", b); - WriteLog("uart: tx: " + std::string(buf)); + std::string hex; + hex.reserve(buffer.size() * 3); + for (uint8_t b : buffer) { + hex += std::format("{:02X} ", b); + } + WriteLog("uart: tx: " + hex); } ret = sp_blocking_write(port, (void*)buffer.data(), buffer.size(), 0);