From 87bde6b2aa460fe0996f795a24f0e1fb5e1ae427 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Sun, 22 Sep 2024 10:40:04 +0200 Subject: [PATCH] Use C++20 formatting API rather than fmtlib Other changes: - [crispy] App: Changes log timestamps to print time in local time - Drop Ubuntu 20.04 and Ubuntu 22.04 CI pipline building and tests Signed-off-by: Christian Parpart --- .github/fedora/contour.spec | 2 - .github/workflows/build.yml | 220 +++-------------- cmake/ContourThirdParties.cmake | 7 +- cmake/presets/os-macos.json | 1 + examples/CMakeLists.txt | 2 +- examples/watch-mouse-events.cpp | 9 +- metainfo.xml | 2 +- scripts/check-common.sh | 2 +- scripts/ci-install-run-deps.sh | 44 ++++ scripts/install-deps.ps1 | 20 +- scripts/install-deps.sh | 29 +-- src/contour/Actions.h | 53 ++--- src/contour/CaptureScreen.cpp | 7 +- src/contour/Config.cpp | 29 ++- src/contour/Config.h | 94 ++++---- src/contour/ContourApp.cpp | 66 +++--- src/contour/ContourGuiApp.cpp | 12 +- src/contour/TerminalSession.cpp | 6 +- src/contour/TerminalSession.h | 29 +-- src/contour/display/Blur.cpp | 2 +- src/contour/display/ShaderConfig.cpp | 2 +- src/contour/display/ShaderConfig.h | 4 +- src/contour/display/TerminalDisplay.cpp | 25 +- src/contour/helper.h | 6 +- src/crispy/App.cpp | 29 +-- src/crispy/BufferObject.h | 5 +- src/crispy/CLI.cpp | 29 ++- src/crispy/CLI.h | 23 +- src/crispy/CLI_test.cpp | 4 +- src/crispy/CMakeLists.txt | 4 +- src/crispy/LRUCache_test.cpp | 9 +- src/crispy/StackTrace.cpp | 7 +- src/crispy/StrongHash.h | 8 +- src/crispy/StrongLRUCache.h | 9 +- src/crispy/StrongLRUHashtable.h | 30 +-- src/crispy/StrongLRUHashtable_test.cpp | 2 +- src/crispy/assert.h | 10 +- src/crispy/escape.h | 12 +- src/crispy/file_descriptor.h | 17 +- src/crispy/flags.h | 8 +- src/crispy/interpolated_string_test.cpp | 4 +- src/crispy/logstore.h | 14 +- src/crispy/point.h | 9 +- src/crispy/result_test.cpp | 3 +- src/crispy/ring_test.cpp | 12 +- src/crispy/size.h | 11 +- src/crispy/utils.h | 17 +- src/crispy/utils_test.cpp | 2 +- src/text_shaper/CMakeLists.txt | 1 - src/text_shaper/font.cpp | 8 +- src/text_shaper/font.h | 71 +++--- src/text_shaper/font_locator.h | 27 ++- src/text_shaper/fontconfig_locator.cpp | 6 +- src/text_shaper/open_shaper.cpp | 2 +- src/text_shaper/shaper.h | 19 +- src/vtbackend/CMakeLists.txt | 4 +- src/vtbackend/Capabilities.h | 9 +- src/vtbackend/Capabilities_test.cpp | 4 +- src/vtbackend/CellFlags.h | 7 +- src/vtbackend/Charset.cpp | 234 +++++++++---------- src/vtbackend/Charset.h | 13 +- src/vtbackend/Color.cpp | 12 +- src/vtbackend/Color.h | 26 +-- src/vtbackend/ColorPalette.h | 15 +- src/vtbackend/Functions.cpp | 5 +- src/vtbackend/Functions.h | 34 ++- src/vtbackend/Functions_test.cpp | 6 +- src/vtbackend/Grid.cpp | 11 +- src/vtbackend/Grid.h | 14 +- src/vtbackend/Grid_test.cpp | 30 +-- src/vtbackend/Image.cpp | 6 +- src/vtbackend/Image.h | 51 ++-- src/vtbackend/InputBinding.h | 11 +- src/vtbackend/InputGenerator.cpp | 19 +- src/vtbackend/InputGenerator.h | 44 ++-- src/vtbackend/InputGenerator_test.cpp | 4 +- src/vtbackend/Line.cpp | 2 +- src/vtbackend/Line.h | 4 +- src/vtbackend/Line_test.cpp | 6 +- src/vtbackend/Logger.h | 23 +- src/vtbackend/MatchModes.h | 7 +- src/vtbackend/RenderBuffer.cpp | 3 +- src/vtbackend/RenderBufferBuilder.cpp | 4 +- src/vtbackend/Screen.cpp | 44 ++-- src/vtbackend/Screen.h | 18 +- src/vtbackend/Screen_test.cpp | 112 +++++---- src/vtbackend/Selector.h | 13 +- src/vtbackend/Selector_test.cpp | 14 +- src/vtbackend/Sequence.cpp | 2 +- src/vtbackend/Sequence.h | 2 +- src/vtbackend/SixelParser_test.cpp | 10 +- src/vtbackend/StatusLineBuilder.cpp | 37 +-- src/vtbackend/Terminal.cpp | 23 +- src/vtbackend/Terminal.h | 34 ++- src/vtbackend/Terminal_test.cpp | 18 +- src/vtbackend/VTType.h | 11 +- src/vtbackend/VTWriter.cpp | 4 +- src/vtbackend/VTWriter.h | 11 +- src/vtbackend/ViCommands.cpp | 3 +- src/vtbackend/ViInputHandler.cpp | 14 +- src/vtbackend/ViInputHandler.h | 16 +- src/vtbackend/bench-headless.cpp | 62 +++-- src/vtbackend/cell/CompactCell.h | 8 +- src/vtbackend/doc-tool.cpp | 33 ++- src/vtbackend/primitives.h | 38 +-- src/vtbackend/test_helpers.h | 16 +- src/vtparser/CMakeLists.txt | 1 - src/vtparser/Parser-impl.h | 2 +- src/vtparser/Parser.cpp | 23 +- src/vtparser/Parser.h | 15 +- src/vtparser/Parser_test.cpp | 2 +- src/vtpty/CMakeLists.txt | 2 +- src/vtpty/ImageSize.h | 8 +- src/vtpty/Process.h | 16 +- src/vtpty/Process_unix.cpp | 21 +- src/vtpty/Process_win32.cpp | 5 +- src/vtpty/SshSession.cpp | 54 ++--- src/vtpty/SshSession.h | 31 ++- src/vtrasterizer/BoxDrawingRenderer.cpp | 7 +- src/vtrasterizer/Decorator.h | 7 +- src/vtrasterizer/FontDescriptions.h | 19 +- src/vtrasterizer/GridMetrics.h | 9 +- src/vtrasterizer/ImageRenderer.cpp | 2 +- src/vtrasterizer/Pixmap.h | 7 +- src/vtrasterizer/RenderTarget.h | 17 +- src/vtrasterizer/Renderer.h | 3 +- src/vtrasterizer/TextClusterGrouper_test.cpp | 28 ++- src/vtrasterizer/TextRenderer.cpp | 9 +- src/vtrasterizer/TextureAtlas.h | 44 ++-- vcpkg.json | 3 +- 130 files changed, 1181 insertions(+), 1390 deletions(-) create mode 100755 scripts/ci-install-run-deps.sh diff --git a/.github/fedora/contour.spec b/.github/fedora/contour.spec index b1aa9993ca..1d69b8f6d1 100644 --- a/.github/fedora/contour.spec +++ b/.github/fedora/contour.spec @@ -16,8 +16,6 @@ Source0: %{name}-%{version}.tar.gz BuildRequires: cmake BuildRequires: extra-cmake-modules -# Don't use system-dep of fmt-devel for now as we need a newer one -# BuildRequires: fmt-devel BuildRequires: fontconfig-devel BuildRequires: freetype-devel BuildRequires: gcc-c++ diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b94e73272f..903900bfd4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -572,114 +572,6 @@ jobs: if-no-files-found: error retention-days: 7 # }}} - # {{{ Ubuntu 22.04 CC matrix - ubuntu_2204_cc_matrix: - strategy: - fail-fast: false - matrix: - cxx: [20] - build_type: ["RelWithDebInfo"] - compiler: - [ - "GCC 10", - "Clang 15", - ] - qt_version: [6] - name: "Ubuntu Linux 22.04 (${{ matrix.compiler }}, C++${{ matrix.cxx }}, Qt${{ matrix.qt_version }})" - runs-on: ubuntu-22.04 - outputs: - id: "${{ matrix.compiler }} (C++${{ matrix.cxx }}, ${{ matrix.build_type }}, ${{ matrix.qt_version }})" - steps: - - uses: actions/checkout@v4 - - name: ccache - uses: hendrikmuhs/ccache-action@v1.2 - with: - key: "ccache-ubuntu2204-${{ matrix.compiler }}-${{ matrix.cxx }}-${{ matrix.build_type }}-${{ matrix.qt_version }}" - max-size: 256M - - name: "update APT database" - run: sudo apt -q update - - name: Installing xmllint for ci-set-vars - run: sudo apt -qy install libxml2-utils - - name: set environment variables - id: set_vars - run: ./scripts/ci-set-vars.sh - env: - REPOSITORY: ${{ github.event.repository.name }} - - name: "Set up output var: CC_VERSION" - id: extract_matrix - run: | - CC_VERSION=$( echo "${{ matrix.compiler }}" | awk '{ print $2; }') - echo "CC_VERSION=${CC_VERSION}" >> "$GITHUB_OUTPUT" - - name: "Set up QTVER var" - id: set_qtver - run: | - if [[ ${{ matrix.qt_version }} = "5" ]]; then - echo "QTVER=5" >> "$GITHUB_OUTPUT" - else - echo "QTVER=6" >> "$GITHUB_OUTPUT" - fi - - name: "install dependencies" - run: sudo env QTVER="${{ matrix.qt_version }}" SYSDEP_ASSUME_YES=ON ./scripts/install-deps.sh - - name: "Post-fix embedded dependency permissions." - run: sudo find _deps/sources -exec chown $UID {} \; - - name: Install GCC - if: ${{ startsWith(matrix.compiler, 'GCC') }} - run: sudo apt install -y g++-${{ steps.extract_matrix.outputs.CC_VERSION }} - - name: Install Clang - if: ${{ startsWith(matrix.compiler, 'Clang') }} - run: sudo apt install -y clang-${{ steps.extract_matrix.outputs.CC_VERSION }} #libc++-dev libc++abi-dev - - name: Install Clang-Tidy - if: ${{ startsWith(matrix.compiler, 'Clang') }} - run: sudo apt install -y clang-tidy-${{ steps.extract_matrix.outputs.CC_VERSION }} - - - name: Install CMake - uses: ssrobins/install-cmake@v1 - - name: "create build directory" - run: mkdir build - - name: CMake version - run: cmake --version - - name: "cmake" - run: | - CC_NAME=$(echo "${{ matrix.compiler }}" | awk '{ print tolower($1); }') - CC_VER=$( echo "${{ matrix.compiler }}" | awk '{ print $2; }') - test "${{ matrix.compiler }}" = "GCC 8" && EXTRA_CMAKE_FLAGS="$EXTRA_CMAKE_FLAGS -DPEDANTIC_COMPILER_WERROR=ON" - test "${CC_NAME}" = "gcc" && CC_EXE="g++" - if [[ "${CC_NAME}" = "clang" ]]; then - CC_EXE="clang++" - # CMAKE_CXX_FLAGS="-stdlib=libc++" - # CMAKE_EXE_LINKER_FLAGS="-stdlib=libc++ -lc++abi" - # EXTRA_CMAKE_FLAGS="$EXTRA_CMAKE_FLAGS -DENABLE_TIDY=ON" - # EXTRA_CMAKE_FLAGS="$EXTRA_CMAKE_FLAGS -DPEDANTIC_COMPILER_WERROR=OFF" - fi - cmake \ - $EXTRA_CMAKE_FLAGS \ - -DCMAKE_BUILD_TYPE="${{ matrix.build_type }}" \ - -DCMAKE_CXX_STANDARD=${{ matrix.cxx }} \ - -DCMAKE_CXX_COMPILER="${CC_EXE}-${CC_VER}" \ - -DCMAKE_CXX_FLAGS="${CMAKE_CXX_FLAGS}" \ - -DCMAKE_EXE_LINKER_FLAGS="${CMAKE_EXE_LINKER_FLAGS}" \ - -DCMAKE_INSTALL_PREFIX="/usr" \ - -DCONTOUR_QT_VERSION=${{ matrix.qt_version }} \ - -DLIBUNICODE_UCD_BASE_DIR=$PWD/_ucd \ - --preset linux-debug - - name: "build" - run: cmake --build --preset linux-debug -- -j3 - - name: "tests" - run: cmake --build --preset linux-debug --target test - - name: "Upload unit tests" - if: ${{ matrix.compiler == 'GCC 10' && matrix.cxx == '20' && matrix.qt_version == '6' }} - uses: actions/upload-artifact@v4 - with: - name: contour-ubuntu2204-tests - path: | - build/linux-debug/src/crispy/crispy_test - build/linux-debug/src/vtparser/vtparser_test - build/linux-debug/src/vtbackend/vtbackend_test - build/linux-debug/src/vtbackend/bench-headless - build/linux-debug/src/vtrasterizer/vtrasterizer_test - test/images - retention-days: 1 - # }}} # {{{ Ubuntu 24.04 CC matrix ubuntu_2404_cc_matrix: strategy: @@ -773,10 +665,10 @@ jobs: - name: "tests" run: cmake --build --preset linux-debug --target test - name: "Upload unit tests" - if: ${{ matrix.compiler == 'GCC 10' && matrix.cxx == '20' && matrix.qt_version == '6' }} + if: ${{ matrix.compiler == 'GCC 14' && matrix.cxx == '20' && matrix.qt_version == '6' }} uses: actions/upload-artifact@v4 with: - name: contour-ubuntu2204-tests + name: contour-ubuntu2404-tests path: | build/linux-debug/src/crispy/crispy_test build/linux-debug/src/vtparser/vtparser_test @@ -858,13 +750,13 @@ jobs: if-no-files-found: error retention-days: 7 # }}} - # {{{ Ubuntu 20.04 / 22.04 / 24.04 + # {{{ Ubuntu 24.04 package_for_Ubuntu: name: "Packaging for Ubuntu ${{ matrix.os_version }}" strategy: fail-fast: false matrix: - os_version: ['20.04', '22.04', '24.04'] + os_version: ['24.04'] runs-on: ubuntu-${{ matrix.os_version }} steps: - name: Checkout code @@ -883,15 +775,6 @@ jobs: with: key: "ccache-ubuntu-${{ matrix.os_version }}" max-size: 256M - - name: set QTVER - id: set_qtver - run: | - if [[ ${{ matrix.os_version }} = "20.04" ]]; then - echo "QTVER=5" >> "$GITHUB_OUTPUT" - fi - - name: "Install gcc-10 on 20.04" - if: matrix.os_version == '20.04' - run: sudo apt -y install gcc-10 - name: "install dependencies" run: sudo env QTVER="${{ steps.set_qtver.outputs.QTVER }}" ./scripts/install-deps.sh - name: "Post-fix embedded dependency permissions." @@ -907,15 +790,8 @@ jobs: run: | # TODO: turn on -Werror again, that requires some code changes. CMAKE_CXX_STANDARD=20 - if [[ "${{ matrix.os_version }}" = "20.04" ]]; then - EXTRA_CMAKE_FLAGS="$EXTRA_CMAKE_FLAGS -DCONTOUR_QT_VERSION=5 -DCMAKE_CXX_COMPILER=g++-10" - else - # use Qt6 for 22.04 - EXTRA_CMAKE_FLAGS="$EXTRA_CMAKE_FLAGS -DCONTOUR_QT_VERSION=6" - fi - if [[ "${{ matrix.os_version }}" = "24.04" ]]; then - EXTRA_CMAKE_FLAGS="$EXTRA_CMAKE_FLAGS -DCONTOUR_PACKAGE_TERMINFO=OFF" - fi + EXTRA_CMAKE_FLAGS="$EXTRA_CMAKE_FLAGS -DCONTOUR_QT_VERSION=6" + EXTRA_CMAKE_FLAGS="$EXTRA_CMAKE_FLAGS -DCONTOUR_PACKAGE_TERMINFO=OFF" BUILD_DIR="build" \ CMAKE_BUILD_TYPE=RelWithDebInfo \ EXTRA_CMAKE_FLAGS="$EXTRA_CMAKE_FLAGS \ @@ -953,16 +829,20 @@ jobs: sudo dpkg --install "contour-${{ steps.set_vars.outputs.VERSION_STRING }}-ubuntu${{ matrix.os_version }}-amd64.deb" sudo dpkg --install "contour-dbgsym-${{ steps.set_vars.outputs.VERSION_STRING }}-ubuntu${{ matrix.os_version }}-amd64.ddeb" # }}} - # {{{ Ubuntu 22.04: test via valgrind - test_ubuntu2204_valgrind: + # {{{ Ubuntu 24.04: test via valgrind + test_ubuntu2404_valgrind: name: "Run tests via valgrind" - runs-on: ubuntu-22.04 - needs: [ubuntu_2204_cc_matrix] + runs-on: ubuntu-24.04 + needs: [ubuntu_2404_cc_matrix] steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: | + scripts - name: "download artifact" uses: actions/download-artifact@v4 with: - name: contour-ubuntu2204-tests + name: contour-ubuntu2404-tests - name: "update APT database" run: sudo apt -q update - name: "fix unit test permissions" @@ -970,18 +850,7 @@ jobs: find . -name '*_test' -exec chmod 0755 {} \; find . -name 'bench-headless' -exec chmod 0755 {} \; - name: "install dependencies" - run: | - set -ex - ls -hlR - sudo apt install -y \ - libfontconfig1 \ - libfreetype6 \ - libharfbuzz0b \ - libqt5gui5 \ - libqt5opengl5 \ - libyaml-cpp0.7 \ - ncurses-bin \ - valgrind + run: ./scripts/ci-install-run-deps.sh valgrind - name: "test: crispy (via valgrind)" run: valgrind --error-exitcode=64 ./build/linux-debug/src/crispy/crispy_test - name: "test: vtparser (via valgrind)" @@ -991,8 +860,8 @@ jobs: - name: "test: vtrasterizer (via valgrind)" run: valgrind --error-exitcode=64 ./build/linux-debug/src/vtrasterizer/vtrasterizer_test # }}} - # {{{ Ubuntu 22.04: Test bench-headless - test_ubuntu2204_bench_headless: + # {{{ Ubuntu 24.04: Test bench-headless + test_ubuntu2404_bench_headless: strategy: matrix: test_case: @@ -1001,13 +870,17 @@ jobs: "grid long" ] name: "Run bench-headless" - runs-on: ubuntu-22.04 - needs: [ubuntu_2204_cc_matrix] + runs-on: ubuntu-24.04 + needs: [ubuntu_2404_cc_matrix] steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: | + scripts - name: "download artifact" uses: actions/download-artifact@v4 with: - name: contour-ubuntu2204-tests + name: contour-ubuntu2404-tests - name: "update APT database" run: sudo apt -q update - name: "fix unit test permissions" @@ -1015,46 +888,35 @@ jobs: find . -name '*_test' -exec chmod 0755 {} \; find . -name 'bench-headless' -exec chmod 0755 {} \; - name: "install dependencies" - run: | - set -ex - ls -hlR - sudo apt install -y \ - libfontconfig1 \ - libfreetype6 \ - libharfbuzz0b \ - libqt5gui5 \ - libqt5opengl5 \ - libyaml-cpp0.7 \ - ncurses-bin \ - valgrind + run: ./scripts/ci-install-run-deps.sh valgrind - name: "bench-headless: ${{ matrix.test_case }}" run: valgrind --error-exitcode=64 ./build/linux-debug/src/vtbackend/bench-headless ${{ matrix.test_case }} size 1 # }}} # {{{ Ubuntu check matrix - check_ubuntu2204_matrix_test_matrix: + check_ubuntu2404_matrix_test_matrix: if: ${{ always() }} runs-on: ubuntu-latest - name: "Ubuntu Linux 22.04 post-check" + name: "Ubuntu Linux 24.04 post-check" needs: - package_for_Ubuntu - - ubuntu_2204_cc_matrix - - test_ubuntu2204_valgrind - - test_ubuntu2204_bench_headless + - ubuntu_2404_cc_matrix + - test_ubuntu2404_valgrind + - test_ubuntu2404_bench_headless steps: - name: Print matrix status run: | - echo "Result (CC matrix) : ${{ needs.ubuntu_2204_cc_matrix.result }}" + echo "Result (CC matrix) : ${{ needs.ubuntu_2404_cc_matrix.result }}" echo "Result (packaging matrix) : ${{ needs.package_for_Ubuntu.result }}" - name: Check build matrix status - if: ${{ needs.ubuntu_2204_cc_matrix.result != 'success' && needs.ubuntu_2204_cc_matrix.result != 'skipped' }} + if: ${{ needs.ubuntu_2404_cc_matrix.result != 'success' && needs.ubuntu_2404_cc_matrix.result != 'skipped' }} run: exit 1 - name: Check package_for_Ubuntu matrix status if: ${{ needs.package_for_Ubuntu.result != 'success' && needs.package_for_Ubuntu.result != 'skipped' }} run: exit 1 - - name: "Delete artifact: contour-ubuntu2204-tests" + - name: "Delete artifact: contour-ubuntu2404-tests" uses: geekyeggo/delete-artifact@v2 with: - name: contour-ubuntu2204-tests + name: contour-ubuntu2404-tests # }}} # {{{ GUI: test: contour quick shell exit test_quick_exit: @@ -1063,7 +925,7 @@ jobs: strategy: fail-fast: false matrix: - os_version: ['20.04', '22.04', '24.04'] + os_version: ['24.04'] runs-on: ubuntu-${{ matrix.os_version }} env: # I'm giving up on eliminating all leaks for now. @@ -1233,7 +1095,7 @@ jobs: strategy: fail-fast: false matrix: - os_version: ['20.04', '22.04', '24.04'] + os_version: ['24.04'] runs-on: ubuntu-${{ matrix.os_version}} needs: [package_for_Ubuntu] steps: @@ -1304,14 +1166,6 @@ jobs: REPOSITORY: ${{ github.event.repository.name }} # {{{ fetch release artifacts - - name: "fetch artifact: Ubuntu 20.04" - uses: actions/download-artifact@v4 - with: - name: contour-${{ steps.set_vars.outputs.VERSION_STRING }}-ubuntu20.04-amd64.deb - - name: "fetch artifact: Ubuntu 22.04" - uses: actions/download-artifact@v4 - with: - name: contour-${{ steps.set_vars.outputs.VERSION_STRING }}-ubuntu22.04-amd64.deb - name: "fetch artifact: Ubuntu 24.04" uses: actions/download-artifact@v4 with: diff --git a/cmake/ContourThirdParties.cmake b/cmake/ContourThirdParties.cmake index f255c73ee4..611084ffea 100644 --- a/cmake/ContourThirdParties.cmake +++ b/cmake/ContourThirdParties.cmake @@ -54,9 +54,8 @@ message(STATUS "================================================================ message(STATUS " Contour ThirdParties: ${ContourThirdParties}") set(LIBUNICODE_MINIMAL_VERSION "0.4.0") -set(BOXED_CPP_MINIMAL_VERSION "1.4.2") -set(TERMBENCH_PRO_COMMIT_HASH "96c6bb7897af4110d1b99a93b982f8ec10e71183") -set(FMT_VERSION "10.0.0") +set(BOXED_CPP_MINIMAL_VERSION "1.4.3") +set(TERMBENCH_PRO_COMMIT_HASH "f6c37988e6481b48a8b8acaf1575495e018e9747") set(CATCH_VERSION "3.4.0") set(RANGE_V3_VERSION "0.12.0") set(YAML_CPP_VERSION "0.8.0") @@ -89,7 +88,6 @@ endif() if(CONTOUR_TESTING) HandleThirdparty(Catch2 "gh:catchorg/Catch2@${CATCH_VERSION}") endif() -HandleThirdparty(fmt "gh:fmtlib/fmt#${FMT_VERSION}") HandleThirdparty(range-v3 "gh:ericniebler/range-v3#${RANGE_V3_VERSION}") HandleThirdparty(yaml-cpp "gh:jbeder/yaml-cpp#${YAML_CPP_VERSION}") HandleThirdparty(Freetype "https://download.savannah.gnu.org/releases/freetype/freetype-2.10.0.tar.gz") @@ -137,7 +135,6 @@ macro(ContourThirdPartiesSummary2) message(STATUS "------------------------------------------------------------------------------") message(STATUS "Catch2 ${THIRDPARTY_BUILTIN_Catch2}") message(STATUS "GSL ${THIRDPARTY_BUILTIN_GSL}") - message(STATUS "fmt ${THIRDPARTY_BUILTIN_fmt}") message(STATUS "freetype ${THIRDPARTY_BUILTIN_Freetype}") message(STATUS "harfbuzz ${THIRDPARTY_BUILTIN_HarfBuzz}") message(STATUS "range-v3 ${THIRDPARTY_BUILTIN_range-v3}") diff --git a/cmake/presets/os-macos.json b/cmake/presets/os-macos.json index 9553289651..9cacff7b76 100644 --- a/cmake/presets/os-macos.json +++ b/cmake/presets/os-macos.json @@ -13,6 +13,7 @@ "rhs": "Darwin" }, "cacheVariables": { + "LIBTERMINAL_BUILD_BENCH_HEADLESS": "OFF", "CODE_SIGN_CERTIFICATE_ID": "Developer ID Application: Christian Parpart (6T525MU9UR)", "CMAKE_PREFIX_PATH": "/opt/homebrew/opt/qt" } diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 667bdf1a58..9abb99c7ff 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,6 +1,6 @@ if(LIBTERMINAL_TESTING) if(UNIX) add_executable(watch-mouse-events watch-mouse-events.cpp) - target_link_libraries(watch-mouse-events fmt::fmt-header-only vtbackend) + target_link_libraries(watch-mouse-events vtbackend) endif() endif() diff --git a/examples/watch-mouse-events.cpp b/examples/watch-mouse-events.cpp index 6dd86cdc60..0180ef7021 100644 --- a/examples/watch-mouse-events.cpp +++ b/examples/watch-mouse-events.cpp @@ -8,9 +8,8 @@ #include -#include - #include +#include #include #if defined(__APPLE__) @@ -188,7 +187,7 @@ struct MouseTracker final: public BasicParserEvents checkPassiveMouseTrackingSupport(); while (_running) { - writeToTTY(fmt::format("\rMouse position {}:{}, 0x{:X}, {} ({})\033[K", + writeToTTY(std::format("\rMouse position {}:{}, 0x{:X}, {} ({})\033[K", line, column, mouseButton, @@ -214,7 +213,7 @@ struct MouseTracker final: public BasicParserEvents } }(); - return fmt::format("{}; {} .. {}", mode, selection.from, selection.to); + return std::format("{}; {} .. {}", mode, selection.from, selection.to); } void checkPassiveMouseTrackingSupport() @@ -225,7 +224,7 @@ struct MouseTracker final: public BasicParserEvents auto const state = _decrpm.value().second; auto const supported = state == 1 || state == 2; - fmt::print("Passive mouse tracking: {}\n", supported ? "supported" : "not supported"); + std::cout << std::format("Passive mouse tracking: {}\n", supported ? "supported" : "not supported"); } void writeToTTY(string_view s) noexcept { ::write(STDOUT_FILENO, s.data(), s.size()); } diff --git a/metainfo.xml b/metainfo.xml index c70d69c695..6430b34333 100644 --- a/metainfo.xml +++ b/metainfo.xml @@ -107,7 +107,7 @@
    - +
  • Port to C++20's `std::format()` (#1598)
diff --git a/scripts/check-common.sh b/scripts/check-common.sh index ccb2c7205f..afa5ffbd5d 100755 --- a/scripts/check-common.sh +++ b/scripts/check-common.sh @@ -6,7 +6,7 @@ ErrorCount=0 ## libunicode version match -LIBUNICODE_SHA_PS=$(awk 'match ($0, /"libunicode-[0-9a-f]+"/) { print(substr($0, RSTART+12, RLENGTH-12-1)); }' scripts/install-deps.ps1) +LIBUNICODE_SHA_PS=$(awk 'match ($0, /libunicode_git_sha="[0-9a-f]+/) { print(substr($0, RSTART+20, RLENGTH-20)); }' scripts/install-deps.ps1) LIBUNICODE_SHA_SH=$(awk 'match ($0, /libunicode_git_sha="[0-9a-f]+/) { print(substr($0, RSTART+20, RLENGTH-20)); }' scripts/install-deps.sh) if [[ "${LIBUNICODE_SHA_SH}" != "${LIBUNICODE_SHA_PS}" ]]; then diff --git a/scripts/ci-install-run-deps.sh b/scripts/ci-install-run-deps.sh new file mode 100755 index 0000000000..690a4b4265 --- /dev/null +++ b/scripts/ci-install-run-deps.sh @@ -0,0 +1,44 @@ +#! /bin/bash + +set -ex + +# Installs dependencies for running Contour GUI executable on CI + +sudo apt install -y \ + \ + libfontconfig1 \ + libfreetype6 \ + libharfbuzz0b \ + libssh-4 \ + libyaml-cpp0.8 \ + \ + libqt6core5compat6 \ + libqt6gui6t64 \ + libqt6multimedia6 \ + libqt6multimediaquick6 \ + libqt6multimediawidgets6 \ + libqt6network6t64 \ + libqt6opengl6t64 \ + libqt6openglwidgets6t64 \ + libqt6qml6 \ + libqt6qmlcompiler6 \ + libqt6qmlcore6 \ + libqt6qmllocalstorage6 \ + libqt6qmlmodels6 \ + libqt6qmlworkerscript6 \ + libqt6qmlxmllistmodel6 \ + libqt6quick6 \ + libqt6quickcontrols2-6 \ + libqt6quickcontrols2impl6 \ + libqt6quickdialogs2-6 \ + libqt6quickdialogs2quickimpl6 \ + libqt6quickdialogs2utils6 \ + libqt6quicklayouts6 \ + libqt6quickparticles6 \ + libqt6quickshapes6 \ + libqt6quicktemplates2-6 \ + libqt6quicktest6 \ + libqt6quickwidgets6 \ + libqt6shadertools6 \ + \ + ncurses-bin ${@} diff --git a/scripts/install-deps.ps1 b/scripts/install-deps.ps1 index 81f44e0e39..aaafc29625 100644 --- a/scripts/install-deps.ps1 +++ b/scripts/install-deps.ps1 @@ -10,25 +10,27 @@ class ThirdParty { [string] $Macro } +$libunicode_git_sha="6f8e210d1e50fc0db5c977ca9fd58555d23010ac" + # Take care, order matters, at least as much as dependencies are of concern. $ThirdParties = @( [ThirdParty]@{ - Folder = "libunicode-28aacf5191450775f1f336aba1d6b65673b0ba9f"; - Archive = "libunicode-28aacf5191450775f1f336aba1d6b65673b0ba9f.zip"; - URI = "https://github.com/contour-terminal/libunicode/archive/28aacf5191450775f1f336aba1d6b65673b0ba9f.zip"; + Folder = "libunicode-${libunicode_git_sha}"; + Archive = "libunicode-${libunicode_git_sha}.zip"; + URI = "https://github.com/contour-terminal/libunicode/archive/${libunicode_git_sha}.zip"; Macro = "libunicode" }; [ThirdParty]@{ - Folder = "termbench-pro-7f86c882b2dab88a0cceeffd7e3848f55fa5f6f2"; - Archive = "termbench-pro-7f86c882b2dab88a0cceeffd7e3848f55fa5f6f2.zip"; - URI = "https://github.com/contour-terminal/termbench-pro/archive/7f86c882b2dab88a0cceeffd7e3848f55fa5f6f2.zip"; + Folder = "termbench-pro-f6c37988e6481b48a8b8acaf1575495e018e9747"; + Archive = "termbench-pro-f6c37988e6481b48a8b8acaf1575495e018e9747.zip"; + URI = "https://github.com/contour-terminal/termbench-pro/archive/f6c37988e6481b48a8b8acaf1575495e018e9747.zip"; Macro = "termbench_pro" } [ThirdParty]@{ - Folder = "boxed-cpp-1.4.2"; - Archive = "boxed-cpp-1.4.2.zip"; - URI = "https://github.com/contour-terminal/boxed-cpp/archive/refs/tags/v1.4.2.zip"; + Folder = "boxed-cpp-1.4.3"; + Archive = "boxed-cpp-1.4.3.zip"; + URI = "https://github.com/contour-terminal/boxed-cpp/archive/refs/tags/v1.4.3.zip"; Macro = "boxed_cpp" } ) diff --git a/scripts/install-deps.sh b/scripts/install-deps.sh index 89a13971dd..d8c901ae4d 100755 --- a/scripts/install-deps.sh +++ b/scripts/install-deps.sh @@ -81,15 +81,6 @@ fetch_and_unpack_Catch2() https://github.com/catchorg/Catch2/archive/refs/tags/v3.4.0.tar.gz } -fetch_and_unpack_fmtlib() -{ - fmtlib_version="10.0.0" - fetch_and_unpack \ - fmt-$fmtlib_version \ - fmtlib-$fmtlib_version.tar.gz \ - https://github.com/fmtlib/fmt/archive/refs/tags/$fmtlib_version.tar.gz -} - fetch_and_unpack_gsl() { fetch_and_unpack \ @@ -100,7 +91,7 @@ fetch_and_unpack_gsl() fetch_and_unpack_termbenchpro() { - local termbench_pro_git_sha="7f86c882b2dab88a0cceeffd7e3848f55fa5f6f2" + local termbench_pro_git_sha="f6c37988e6481b48a8b8acaf1575495e018e9747" fetch_and_unpack \ termbench-pro-$termbench_pro_git_sha \ termbench-pro-$termbench_pro_git_sha.tar.gz \ @@ -110,7 +101,7 @@ fetch_and_unpack_termbenchpro() fetch_and_unpack_boxed() { - local boxed_cpp_version="1.4.2" + local boxed_cpp_version="1.4.3" fetch_and_unpack \ boxed-cpp-$boxed_cpp_version \ boxed-cpp-$boxed_cpp_version.tar.gz \ @@ -121,7 +112,7 @@ fetch_and_unpack_boxed() fetch_and_unpack_libunicode() { if test x$LIBUNICODE_SRC_DIR = x; then - local libunicode_git_sha="28aacf5191450775f1f336aba1d6b65673b0ba9f" + local libunicode_git_sha="6f8e210d1e50fc0db5c977ca9fd58555d23010ac" fetch_and_unpack \ libunicode-$libunicode_git_sha \ libunicode-$libunicode_git_sha.tar.gz \ @@ -223,7 +214,6 @@ install_deps_popos() fetch_and_unpack_libunicode fetch_and_unpack_gsl - fetch_and_unpack_fmtlib fetch_and_unpack_range fetch_and_unpack_Catch2 @@ -312,7 +302,6 @@ install_deps_ubuntu() "20.04" | "22.04" | "23.04") # Older Ubuntu's don't have a recent enough fmt / range-v3, so supply it. fetch_and_unpack_range - fetch_and_unpack_fmtlib fetch_and_unpack_Catch2 ;; *) @@ -328,7 +317,6 @@ install_deps_ubuntu() install_deps_FreeBSD() { - fetch_and_unpack_fmtlib fetch_and_unpack_libunicode fetch_and_unpack_Catch2 @@ -362,7 +350,6 @@ install_deps_OpenBSD() { fetch_and_unpack_Catch2 - fetch_and_unpack_fmtlib fetch_and_unpack_gsl fetch_and_unpack_yaml_cpp fetch_and_unpack_range @@ -388,7 +375,6 @@ install_deps_OpenBSD() install_deps_arch() { fetch_and_unpack_libunicode - fetch_and_unpack_fmtlib [ x$PREPARE_ONLY_EMBEDS = xON ] && return packages=" @@ -432,7 +418,6 @@ install_deps_suse() { fetch_and_unpack_libunicode fetch_and_unpack_gsl - fetch_and_unpack_fmtlib echo "SuSE: PREPARE_ONLY_EMBEDS=$PREPARE_ONLY_EMBEDS" [ x$PREPARE_ONLY_EMBEDS = xON ] && return @@ -506,12 +491,6 @@ install_deps_fedora() fetch_and_unpack_libunicode fetch_and_unpack_gsl - if test "$os_version" -ge 39; then - packages="$packages fmt-devel" - else - fetch_and_unpack_fmtlib - fi - [ x$PREPARE_ONLY_EMBEDS = xON ] && return if test x$QTVER = x6; then @@ -593,7 +572,6 @@ main() ;; debian) install_deps_ubuntu - fetch_and_unpack_fmtlib ;; Darwin) install_deps_darwin @@ -606,7 +584,6 @@ main() ;; *) fetch_and_unpack_Catch2 - fetch_and_unpack_fmtlib fetch_and_unpack_gsl fetch_and_unpack_yaml_cpp fetch_and_unpack_range diff --git a/src/contour/Actions.h b/src/contour/Actions.h index 19171daa5b..af2d36d00b 100644 --- a/src/contour/Actions.h +++ b/src/contour/Actions.h @@ -3,8 +3,7 @@ #include -#include - +#include #include #include #include @@ -302,14 +301,14 @@ inline auto getDocumentation() } // namespace contour::actions // {{{ fmtlib custom formatters -#define DECLARE_ACTION_FMT(T) \ - template <> \ - struct fmt::formatter: fmt::formatter \ - { \ - auto format(contour::actions::T const&, format_context& ctx) const -> format_context::iterator \ - { \ - return formatter::format(#T, ctx); \ - } \ +#define DECLARE_ACTION_FMT(T) \ + template <> \ + struct std::formatter: std::formatter \ + { \ + auto format(contour::actions::T const&, auto& ctx) const \ + { \ + return formatter::format(#T, ctx); \ + } \ }; // {{{ declare @@ -368,14 +367,13 @@ DECLARE_ACTION_FMT(WriteScreen) #define HANDLE_ACTION(T) \ if (std::holds_alternative(_action)) \ { \ - name = fmt::format("{}", std::get(_action)); \ + name = std::format("{}", std::get(_action)); \ } template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(contour::actions::Action const& _action, - format_context& ctx) const -> format_context::iterator + auto format(contour::actions::Action const& _action, auto& ctx) const { std::string name = "Unknown action"; // {{{ handle @@ -429,38 +427,33 @@ struct fmt::formatter: fmt::formatter if (std::holds_alternative(_action)) { const auto writeScreenAction = std::get(_action); - name = fmt::format("{}, chars: '{}'", writeScreenAction, writeScreenAction.chars); + name = std::format("{}, chars: '{}'", writeScreenAction, writeScreenAction.chars); } if (std::holds_alternative(_action)) { const auto createSelectionAction = std::get(_action); name = - fmt::format("{}, delimiters: '{}'", createSelectionAction, createSelectionAction.delimiters); + std::format("{}, delimiters: '{}'", createSelectionAction, createSelectionAction.delimiters); } // }}} - return formatter::format(name, ctx); + return formatter::format(name, ctx); } }; template <> -struct fmt::formatter +struct std::formatter: std::formatter { - template - constexpr auto parse(ParseContext& ctx) - { - return ctx.begin(); - } - template - auto format(contour::actions::CopyFormat value, FormatContext& ctx) const + auto format(contour::actions::CopyFormat value, auto& ctx) const { + string_view output; switch (value) { - case contour::actions::CopyFormat::Text: return fmt::format_to(ctx.out(), "Text"); - case contour::actions::CopyFormat::HTML: return fmt::format_to(ctx.out(), "HTML"); - case contour::actions::CopyFormat::PNG: return fmt::format_to(ctx.out(), "PNG"); - case contour::actions::CopyFormat::VT: return fmt::format_to(ctx.out(), "VT"); + case contour::actions::CopyFormat::Text: output = "Text"; break; + case contour::actions::CopyFormat::HTML: output = "HTML"; break; + case contour::actions::CopyFormat::PNG: output = "PNG"; break; + case contour::actions::CopyFormat::VT: output = "VT"; break; } - crispy::unreachable(); + return formatter::format(output, ctx); } }; diff --git a/src/contour/CaptureScreen.cpp b/src/contour/CaptureScreen.cpp index 7cdcd30bfc..2006198f50 100644 --- a/src/contour/CaptureScreen.cpp +++ b/src/contour/CaptureScreen.cpp @@ -8,9 +8,8 @@ #include -#include - #include +#include #include #include #include @@ -301,7 +300,7 @@ bool captureScreen(CaptureSettings const& settings) auto const [numColumns, numLines] = screenSizeOpt.value(); if (settings.verbosityLevel > 0) - cerr << fmt::format("Screen size: {}x{}. Capturing lines {} ({}) to file {}.\r\n", + cerr << std::format("Screen size: {}x{}. Capturing lines {} ({}) to file {}.\r\n", numColumns, numLines, settings.logicalLines ? "logical" : "physical", @@ -318,7 +317,7 @@ bool captureScreen(CaptureSettings const& settings) output = *customOutput; } - if (tty.write(fmt::format("\033[>{};{}t", settings.logicalLines ? '1' : '0', settings.lineCount)) < 0) + if (tty.write(std::format("\033[>{};{}t", settings.logicalLines ? '1' : '0', settings.lineCount)) < 0) { cerr << "Could not request screen capture.\r\n"; return false; diff --git a/src/contour/Config.cpp b/src/contour/Config.cpp index 7b3e95df79..1a34a25d71 100644 --- a/src/contour/Config.cpp +++ b/src/contour/Config.cpp @@ -101,7 +101,7 @@ namespace { if (!fs::is_regular_file(path)) if (auto const ec = createDefaultConfig(path); ec) - throw runtime_error { fmt::format( + throw runtime_error { std::format( "Could not create directory {}. {}", path.parent_path().string(), ec.message()) }; } @@ -146,7 +146,7 @@ namespace #if defined(__APPLE__) // I realized that on Apple the `tic` command sometimes installs // the terminfo files into weird paths. - if (access((prefix / fmt::format("{:02X}", term.at(0)) / term).string().c_str(), R_OK) == 0) + if (access((prefix / std::format("{:02X}", term.at(0)) / term).string().c_str(), R_OK) == 0) return term; #endif } @@ -1380,7 +1380,7 @@ void YAMLConfigReader::defaultSettings(vtpty::Process::ExecInfo& shell) { shell.env["TERMINAL_NAME"] = "contour"; shell.env["TERMINAL_VERSION_TRIPLE"] = - fmt::format("{}.{}.{}", CONTOUR_VERSION_MAJOR, CONTOUR_VERSION_MINOR, CONTOUR_VERSION_PATCH); + std::format("{}.{}.{}", CONTOUR_VERSION_MAJOR, CONTOUR_VERSION_MINOR, CONTOUR_VERSION_PATCH); shell.env["TERMINAL_VERSION_STRING"] = CONTOUR_VERSION_STRING; // {{{ Populate environment variables @@ -1961,26 +1961,23 @@ std::string createString(Config const& c) }; auto const processWithDoc = [&](auto&& docString, auto... val) { - doc.append( - fmt::format(fmt::runtime(writer.process(docString.value, val...)), fmt::arg("comment", "#"))); + doc.append(helper::replaceCommentPlaceholder(writer.process(docString.value, val...))); }; auto const processWordDelimiters = [&]() { auto wordDelimiters = c.wordDelimiters.value(); wordDelimiters = std::regex_replace(wordDelimiters, std::regex("\\\\"), "\\$&"); /* \ -> \\ */ wordDelimiters = std::regex_replace(wordDelimiters, std::regex("\""), "\\$&"); /* " -> \" */ - doc.append( - fmt::format(fmt::runtime(writer.process(documentation::WordDelimiters.value, wordDelimiters)), - fmt::arg("comment", "#"))); + doc.append(helper::replaceCommentPlaceholder( + writer.process(documentation::WordDelimiters.value, wordDelimiters))); }; auto const processExtendedWordDelimiters = [&]() { auto wordDelimiters = c.extendedWordDelimiters.value(); wordDelimiters = std::regex_replace(wordDelimiters, std::regex("\\\\"), "\\$&"); /* \ -> \\ */ wordDelimiters = std::regex_replace(wordDelimiters, std::regex("\""), "\\$&"); /* " -> \" */ - doc.append(fmt::format( - fmt::runtime(writer.process(documentation::ExtendedWordDelimiters.value, wordDelimiters)), - fmt::arg("comment", "#"))); + doc.append(helper::replaceCommentPlaceholder( + writer.process(documentation::ExtendedWordDelimiters.value, wordDelimiters))); }; if (c.platformPlugin.value().empty()) @@ -2025,12 +2022,12 @@ std::string createString(Config const& c) }); // inside profiles: - doc.append(fmt::format(fmt::runtime(c.profiles.documentation), fmt::arg("comment", "#"))); + doc.append(helper::replaceCommentPlaceholder(c.profiles.documentation)); { const auto _ = typename Writer::Offset {}; for (auto&& [name, entry]: c.profiles.value()) { - doc.append(fmt::format(" {}: \n", name)); + doc.append(std::format(" {}: \n", name)); { const auto _ = typename Writer::Offset {}; process(entry.shell); @@ -2152,11 +2149,11 @@ std::string createString(Config const& c) }; } - doc.append(fmt::format(fmt::runtime(c.colorschemes.documentation), fmt::arg("comment", "#"))); + doc.append(helper::replaceCommentPlaceholder(c.colorschemes.documentation)); writer.scoped([&]() { for (auto&& [name, entry]: c.colorschemes.value()) { - doc.append(fmt::format(" {}: \n", name)); + doc.append(std::format(" {}: \n", name)); { const auto _ = typename Writer::Offset {}; processWithDoc(documentation::DefaultColors, @@ -2284,7 +2281,7 @@ std::string createString(Config const& c) } }); - doc.append(fmt::format(fmt::runtime(c.inputMappings.documentation), fmt::arg("comment", "#"))); + doc.append(helper::replaceCommentPlaceholder(c.inputMappings.documentation)); { const auto _ = typename Writer::Offset {}; for (auto&& entry: c.inputMappings.value().keyMappings) diff --git a/src/contour/Config.h b/src/contour/Config.h index b1edf9d3f3..e004b8d16f 100644 --- a/src/contour/Config.h +++ b/src/contour/Config.h @@ -33,8 +33,6 @@ #include #include -#include - #include #include #include @@ -49,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -99,6 +98,11 @@ struct InputMappings namespace helper { + inline std::string replaceCommentPlaceholder(std::string const& docString) + { + return std::regex_replace(docString, std::regex { "\\{comment\\}" }, "#"); + } + inline bool testMatchMode(uint8_t actualModeFlags, vtbackend::MatchModes expected, vtbackend::MatchModes::Flag testFlag) @@ -936,13 +940,14 @@ struct Writer template auto format(T v) { - return fmt::format("{}", v); + return std::format("{}", v); } template [[nodiscard]] std::string format(std::string_view doc, T... args) { - return fmt::format(fmt::runtime(doc), format(args)..., fmt::arg("comment", "#")); + return std::vformat(helper::replaceCommentPlaceholder(std::string(doc)), + std::make_format_args(args...)); } }; @@ -1009,7 +1014,7 @@ struct YAMLConfigWriter: Writer { auto result = std::string { "[" }; - result.append(v | ranges::views::transform([](auto f) { return fmt::format("{}", f); }) + result.append(v | ranges::views::transform([](auto f) { return std::format("{}", f); }) | ranges::views::join(", ") | ranges::to); result.append("]"); return result; @@ -1025,7 +1030,7 @@ struct YAMLConfigWriter: Writer continue; // We assume that only valid enum values resulting into non-empty strings. - auto const element = fmt::format("{}", flag); + auto const element = std::format("{}", flag); if (element.empty()) continue; @@ -1075,12 +1080,12 @@ struct YAMLConfigWriter: Writer [[nodiscard]] std::string static format(vtbackend::CellRGBColor const& v) { if (std::holds_alternative(v)) - return fmt::format("'{}'", v); + return std::format("'{}'", v); - return fmt::format("{}", v); + return std::format("{}", v); } - [[nodiscard]] std::string static format(vtbackend::RGBColor const& v) { return fmt::format("'{}'", v); } + [[nodiscard]] std::string static format(vtbackend::RGBColor const& v) { return std::format("'{}'", v); } [[nodiscard]] std::string format(std::string_view doc, vtbackend::MaxHistoryLineCount v) { @@ -1106,13 +1111,12 @@ struct YAMLConfigWriter: Writer return format(doc, simple->colorScheme); else if (auto* dual = get_if(&v)) { - return format(doc, - fmt::format(fmt::runtime("\n" - " light: {}\n" - " dark: {}\n" - "\n"), - dual->colorSchemeLight, - dual->colorSchemeDark)); + auto const formattedValue = std::format("\n" + " light: {}\n" + " dark: {}\n", + dual->colorSchemeLight, + dual->colorSchemeDark); + return format(doc, formattedValue); } return format(doc, "BAD"); @@ -1165,9 +1169,9 @@ std::string defaultConfigFilePath(); // {{{ fmtlib custom formatter support template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(contour::config::Permission value, format_context& ctx) const + auto format(contour::config::Permission value, auto& ctx) const { string_view name; switch (value) @@ -1181,27 +1185,27 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::Opacity value, format_context& ctx) const + auto format(vtbackend::Opacity value, auto& ctx) const { return formatter::format(static_cast(value) / std::numeric_limits::max(), ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(crispy::strong_hashtable_size value, format_context& ctx) const + auto format(crispy::strong_hashtable_size value, auto& ctx) const { return formatter::format(value.value, ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::StatusDisplayPosition value, format_context& ctx) const + auto format(vtbackend::StatusDisplayPosition value, auto& ctx) const { string_view name; switch (value) @@ -1214,9 +1218,9 @@ struct fmt::formatter: formatter -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::BackgroundImage value, format_context& ctx) const + auto format(vtbackend::BackgroundImage value, auto& ctx) const { if (auto* loc = std::get_if(&value.location)) return formatter::format(loc->string(), ctx); @@ -1225,9 +1229,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::StatusDisplayType value, format_context& ctx) const + auto format(vtbackend::StatusDisplayType value, auto& ctx) const { string_view name; switch (value) @@ -1241,29 +1245,29 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(crispy::lru_capacity value, format_context& ctx) const + auto format(crispy::lru_capacity value, auto& ctx) const { return formatter::format(value.value, ctx); } }; template <> -struct fmt::formatter>>: formatter +struct std::formatter>>: formatter { - auto format(std::set> value, format_context& ctx) const + auto format(std::set> value, auto& ctx) const { auto result = std::string {}; - result.append(value | ranges::views::join(", ") | ranges::to); + result.append(value | ::ranges::views::join(", ") | ::ranges::to); return formatter::format(result, ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(contour::config::SelectionAction value, format_context& ctx) const + auto format(contour::config::SelectionAction value, auto& ctx) const { std::string_view name; switch (value) @@ -1279,9 +1283,9 @@ struct fmt::formatter: formatter -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(contour::config::ScrollBarPosition value, format_context& ctx) const + auto format(contour::config::ScrollBarPosition value, auto& ctx) const { std::string_view name; switch (value) @@ -1295,9 +1299,9 @@ struct fmt::formatter: formatter -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(contour::config::RenderingBackend const& val, fmt::format_context& ctx) const + auto format(contour::config::RenderingBackend const& val, auto& ctx) const { std::string_view name; switch (val) @@ -1311,22 +1315,22 @@ struct fmt::formatter: formatter -struct fmt::formatter: public fmt::formatter +struct std::formatter: public std::formatter { using WindowMargins = contour::config::WindowMargins; - auto format(WindowMargins margins, format_context& ctx) const -> format_context::iterator + auto format(WindowMargins margins, auto& ctx) const { - return formatter::format(fmt::format("{}x+{}y", margins.horizontal, margins.vertical), + return formatter::format(std::format("{}x+{}y", margins.horizontal, margins.vertical), ctx); } }; template -struct fmt::formatter> +struct std::formatter> { - auto format(contour::config::ConfigEntry const& c, fmt::format_context& ctx) const + auto format(contour::config::ConfigEntry const& c, auto& ctx) const { - return fmt::format_to(ctx.out(), "{}", c.value()); + return std::format_to(ctx.out(), "{}", c.value()); } }; // }}} diff --git a/src/contour/ContourApp.cpp b/src/contour/ContourApp.cpp index 9b259d9c34..b102f13c00 100644 --- a/src/contour/ContourApp.cpp +++ b/src/contour/ContourApp.cpp @@ -13,14 +13,12 @@ #include #include -#include -#include - #include #include #include #include +#include #include #include #include @@ -81,7 +79,7 @@ namespace crashLogger(sstr); string const crashLog = sstr.str(); - auto const logFileName = fmt::format( + auto const logFileName = std::format( "contour-crash-{:%Y-%m-%d-%H-%M-%S}-pid-{}.log", std::chrono::system_clock::now(), getpid()); if (chdir(crashLogDir.c_str()) < 0) perror("chdir"); @@ -187,8 +185,8 @@ int ContourApp::documentationVT() std::string info; auto back = std::back_inserter(info); - fmt::format_to(back, "# {}\n", "VT sequences"); - fmt::format_to(back, "{}\n\n", "List of VT sequences supported by Contour Terminal Emulator."); + std::format_to(back, "# {}\n", "VT sequences"); + std::format_to(back, "{}\n\n", "List of VT sequences supported by Contour Terminal Emulator."); for (auto const& [category, headline]: { std::pair { category::C0, "Control Codes"sv }, std::pair { category::ESC, "Escape Sequences"sv }, std::pair { category::CSI, "Control Sequences"sv }, @@ -196,10 +194,10 @@ int ContourApp::documentationVT() std::pair { category::DCS, "Device Control Sequences"sv } }) { - fmt::format_to(back, "## {}\n\n", headline); + std::format_to(back, "## {}\n\n", headline); - fmt::format_to(back, "| Sequence | Code | Description |\n"); - fmt::format_to(back, "|----------|------|-------------|\n"); + std::format_to(back, "| Sequence | Code | Description |\n"); + std::format_to(back, "|----------|------|-------------|\n"); for (auto const& fn: vtbackend::allFunctions()) { if (fn.category != category) @@ -208,13 +206,13 @@ int ContourApp::documentationVT() // This could be much more improved in good looking and informationally. // We can also print short/longer description, minimum required VT level, // colored output for easier reading, and maybe more. - fmt::format_to(back, + std::format_to(back, "| `{:}` | {:} | {:} |\n", - crispy::escapeMarkdown(fmt::format("{}", fn)), + crispy::escapeMarkdown(std::format("{}", fn)), fn.documentation.mnemonic, fn.documentation.comment); } - fmt::format_to(back, "\n"); + std::format_to(back, "\n"); } std::cout << info; @@ -225,24 +223,24 @@ int ContourApp::documentationKeyMapping() { std::string info; auto back = std::back_inserter(info); - fmt::format_to(back, "{}\n\n", "List of supported actions for key mappings."); + std::format_to(back, "{}\n\n", "List of supported actions for key mappings."); - fmt::format_to(back, "| Action | Description |\n"); - fmt::format_to(back, "|--------|-------------|\n"); + std::format_to(back, "| Action | Description |\n"); + std::format_to(back, "|--------|-------------|\n"); for (auto const& [action, description]: contour::actions::getDocumentation()) { - fmt::format_to(back, "| `{:<20}` | {:} |\n", action, description); + std::format_to(back, "| `{:<20}` | {:} |\n", action, description); } - fmt::format_to(back, "\n"); - fmt::format_to(back, "Example of entries inside config file\n"); - fmt::format_to(back, "``` yaml\n"); + std::format_to(back, "\n"); + std::format_to(back, "Example of entries inside config file\n"); + std::format_to(back, "``` yaml\n"); for (auto const& [action, description]: contour::actions::getDocumentation()) { - fmt::format_to(back, " - {{ mods: [Control], key: Enter, action: {:} }}\n", action); + std::format_to(back, " - {{ mods: [Control], key: Enter, action: {:} }}\n", action); } - fmt::format_to(back, "```\n"); - fmt::format_to(back, "\n"); + std::format_to(back, "```\n"); + std::format_to(back, "\n"); std::cout << info; return EXIT_SUCCESS; @@ -261,27 +259,27 @@ int ContourApp::infoVT() pair { category::OSC, "Operating System Commands"sv }, pair { category::DCS, "Device Control Sequences"sv } }) { - fmt::print("{}\n", headline); - fmt::print("{}\n\n", string(headline.size(), '=')); + std::cout << std::format("{}\n", headline); + std::cout << std::format("{}\n\n", string(headline.size(), '=')); for (auto const& fn: vtbackend::allFunctions()) { if (fn.category != category) continue; - auto const level = fn.extension == VTExtension::None ? fmt::format("{}", fn.conformanceLevel) - : fmt::format("{}", fn.extension); + auto const level = fn.extension == VTExtension::None ? std::format("{}", fn.conformanceLevel) + : std::format("{}", fn.extension); // This could be much more improved in good looking and informationally. // We can also print short/longer description, minimum required VT level, // colored output for easier reading, and maybe more. - fmt::print("{:<20} {:<15} {} ({})\n", - fn.documentation.mnemonic, - fmt::format("{}", fn), - fn.documentation.comment, - level); + std::cout << std::format("{:<20} {:<15} {} ({})\n", + fn.documentation.mnemonic, + std::format("{}", fn), + fn.documentation.comment, + level); } - fmt::print("\n"); + std::cout << std::format("\n"); } return EXIT_SUCCESS; @@ -302,7 +300,7 @@ int ContourApp::integrationAction() file.setFileName(":/contour/shell-integration/shell-integration.bash"); else { - std::cerr << fmt::format("Cannot generate shell integration for an unsupported shell, {}.\n", + std::cerr << std::format("Cannot generate shell integration for an unsupported shell, {}.\n", shell); return EXIT_FAILURE; } @@ -362,7 +360,7 @@ int ContourApp::profileAction() { auto const profileName = parameters().get("contour.set.profile.to"); // TODO: guard `profileName` value against invalid input. - cout << fmt::format("\033P$p{}\033\\", profileName); + cout << std::format("\033P$p{}\033\\", profileName); return EXIT_SUCCESS; } diff --git a/src/contour/ContourGuiApp.cpp b/src/contour/ContourGuiApp.cpp index 4282a7f439..fe3f6ce309 100644 --- a/src/contour/ContourGuiApp.cpp +++ b/src/contour/ContourGuiApp.cpp @@ -256,10 +256,10 @@ bool ContourGuiApp::loadConfig(string const& target) end(_config.profiles.value()), ""s, [](string const& acc, auto const& profile) -> string { - return acc.empty() ? profile.first : fmt::format("{}, {}", acc, profile.first); + return acc.empty() ? profile.first : std::format("{}, {}", acc, profile.first); }); configLogger( - fmt::format("No profile with name '{}' found. Available profiles: {}", profileName(), s)); + std::format("No profile with name '{}' found. Available profiles: {}", profileName(), s)); } if (auto const wd = flags.get("contour.terminal.working-directory"); !wd.empty()) @@ -329,11 +329,11 @@ int ContourGuiApp::fontConfigAction() text::font_locator& fontLocator = createFontLocator(fonts.fontLocator); text::font_source_list const fontSources = fontLocator.locate(fontDescription); - fmt::print("Matching fonts using : {}\n", fonts.fontLocator); - fmt::print("Font description : {}\n", fontDescription); - fmt::print("Number of fonts found : {}\n", fontSources.size()); + std::cout << std::format("Matching fonts using : {}\n", fonts.fontLocator); + std::cout << std::format("Font description : {}\n", fontDescription); + std::cout << std::format("Number of fonts found : {}\n", fontSources.size()); for (text::font_source const& fontSource: fontSources) - fmt::print(" {}\n", fontSource); + std::cout << std::format(" {}\n", fontSource); return EXIT_SUCCESS; } diff --git a/src/contour/TerminalSession.cpp b/src/contour/TerminalSession.cpp index 5c7e4e8e9a..5141ee2c23 100644 --- a/src/contour/TerminalSession.cpp +++ b/src/contour/TerminalSession.cpp @@ -66,7 +66,7 @@ namespace { string unhandledExceptionMessage(string_view const& where, exception const& e) { - return fmt::format("{}: Unhandled exception caught ({}). {}", where, typeid(e).name(), e.what()); + return std::format("{}: Unhandled exception caught ({}). {}", where, typeid(e).name(), e.what()); } void setThreadName(char const* name) @@ -616,7 +616,7 @@ void TerminalSession::onClosed() auto constexpr TextLines = array { "Shell terminated too quickly.", "The window will not be closed automatically." }; for (auto const text: TextLines) - _terminal.writeToScreen(fmt::format("\r\n{}{}{}", SGR, EL, text)); + _terminal.writeToScreen(std::format("\r\n{}{}{}", SGR, EL, text)); _terminal.writeToScreen("\r\n"); _terminatedAndWaitingForKeyPress = true; return; @@ -1597,7 +1597,7 @@ bool TerminalSession::reloadConfigWithProfile(string const& profileName) if (!newConfig.profile(profileName)) { - errorLog()(fmt::format("Currently active profile with name '{}' gone.", profileName)); + errorLog()(std::format("Currently active profile with name '{}' gone.", profileName)); ++configFailures; } diff --git a/src/contour/TerminalSession.h b/src/contour/TerminalSession.h index 45a5a72658..b7a6e886d0 100644 --- a/src/contour/TerminalSession.h +++ b/src/contour/TerminalSession.h @@ -12,14 +12,13 @@ #include -#include - #include #include #include #include #include +#include #include #include @@ -472,31 +471,21 @@ class TerminalSession: public QAbstractItemModel, public vtbackend::Terminal::Ev Q_DECLARE_INTERFACE(contour::TerminalSession, "org.contour.TerminalSession") -namespace fmt -{ - template <> -struct formatter +struct std::formatter: std::formatter { - template - constexpr auto parse(ParseContext& ctx) - { - return ctx.begin(); - } - template auto format(contour::GuardedRole value, FormatContext& ctx) const { + std::string_view output; + // clang-format off switch (value) { - // clang-format off - case contour::GuardedRole::ChangeFont: return fmt::format_to(ctx.out(), "Change Font"); - case contour::GuardedRole::CaptureBuffer: return fmt::format_to(ctx.out(), "Capture Buffer"); - case contour::GuardedRole::ShowHostWritableStatusLine: return fmt::format_to(ctx.out(), "show Host Writable Statusline"); - // clang-format on + case contour::GuardedRole::ChangeFont: output = "Change Font"; break; + case contour::GuardedRole::CaptureBuffer: output = "Capture Buffer"; break; + case contour::GuardedRole::ShowHostWritableStatusLine: output = "show Host Writable Statusline"; break; } - crispy::unreachable(); + // clang-format on + return formatter::format(output, ctx); } }; - -} // namespace fmt diff --git a/src/contour/display/Blur.cpp b/src/contour/display/Blur.cpp index 9c7d17cc4b..9cf7c310a7 100644 --- a/src/contour/display/Blur.cpp +++ b/src/contour/display/Blur.cpp @@ -26,7 +26,7 @@ namespace { displayLog()("Blur: Loading shader source {}", shaderFilePath.toStdString()); auto const versionHeader = - QString::fromStdString(fmt::format("#version {}\n", useOpenGLES() ? "300 es" : "330")); + QString::fromStdString(std::format("#version {}\n", useOpenGLES() ? "300 es" : "330")); QFile file(shaderFilePath); file.open(QFile::ReadOnly); diff --git a/src/contour/display/ShaderConfig.cpp b/src/contour/display/ShaderConfig.cpp index 6a7f1001a0..4503c099a6 100644 --- a/src/contour/display/ShaderConfig.cpp +++ b/src/contour/display/ShaderConfig.cpp @@ -71,7 +71,7 @@ ShaderConfig builtinShaderConfig(ShaderClass shaderClass) sharedDefinesFile.open(QFile::ReadOnly); Require(sharedDefinesFile.isOpen()); auto const sharedDefines = sharedDefinesFile.readAll().toStdString() + "\n#line 1\n"; - auto const versionHeader = fmt::format("#version {}\n", useOpenGLES() ? "300 es" : "330"); + auto const versionHeader = std::format("#version {}\n", useOpenGLES() ? "300 es" : "330"); auto const shaderFilePath = ":/contour/display/shaders/" + filename; diff --git a/src/contour/display/ShaderConfig.h b/src/contour/display/ShaderConfig.h index 83bfac1a36..54bda8a65d 100644 --- a/src/contour/display/ShaderConfig.h +++ b/src/contour/display/ShaderConfig.h @@ -3,10 +3,10 @@ #include -#include - #include +#include + #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #include diff --git a/src/contour/display/TerminalDisplay.cpp b/src/contour/display/TerminalDisplay.cpp index 6b7b3fd1a9..af73bb650e 100644 --- a/src/contour/display/TerminalDisplay.cpp +++ b/src/contour/display/TerminalDisplay.cpp @@ -15,9 +15,6 @@ #include #include -#include -#include - #include #include #include @@ -37,7 +34,9 @@ #include #include +#include #include +#include #include #include #include @@ -116,7 +115,7 @@ namespace #if defined(GL_DEBUG_SOURCE_OTHER_ARB) case GL_DEBUG_SOURCE_OTHER_ARB: return "other"s; #endif - default: return fmt::format("{}", _severity); + default: return std::format("{}", _severity); } }(); string const typeName = [&]() { @@ -140,7 +139,7 @@ namespace #if defined(GL_DEBUG_TYPE_OTHER) case GL_DEBUG_TYPE_OTHER: return "other"s; #endif - default: return fmt::format("{}", _severity); + default: return std::format("{}", _severity); } }(); string const debugSeverity = [&]() { @@ -158,7 +157,7 @@ namespace #if defined(GL_DEBUG_SEVERITY_NOTIFICATION) case GL_DEBUG_SEVERITY_NOTIFICATION: return "notification"s; #endif - default: return fmt::format("{}", _severity); + default: return std::format("{}", _severity); } }(); auto const tag = []([[maybe_unused]] GLint _type) { @@ -197,7 +196,7 @@ namespace std::string unhandledExceptionMessage(std::string_view const& where, exception const& e) { - return fmt::format("{}: Unhandled exception caught ({}). {}", where, typeid(e).name(), e.what()); + return std::format("{}: Unhandled exception caught ({}). {}", where, typeid(e).name(), e.what()); } void reportUnhandledException(std::string_view const& where, exception const& e) @@ -274,8 +273,8 @@ void TerminalDisplay::setSession(TerminalSession* newSession) (void const*) this, (void const*) newSession, newSession->profile().ssh.value().hostname.empty() - ? fmt::format("program={}", newSession->profile().shell.value().program) - : fmt::format("{}@{}:{}", + ? std::format("program={}", newSession->profile().shell.value().program) + : std::format("{}@{}:{}", newSession->profile().ssh.value().username, newSession->profile().ssh.value().hostname, newSession->profile().ssh.value().port), @@ -891,9 +890,9 @@ bool TerminalDisplay::event(QEvent* event) } catch (std::exception const& e) { - fmt::print("Unhandled exception for event {}: {}\n", - (unsigned) event->type(), - QMetaEnum::fromType().valueToKey(event->type())); + std::cout << std::format("Unhandled exception for event {}: {}\n", + (unsigned) event->type(), + QMetaEnum::fromType().valueToKey(event->type())); reportUnhandledException(__PRETTY_FUNCTION__, e); return false; } @@ -1085,7 +1084,7 @@ void TerminalDisplay::doDumpStateInternal() // clang-format off auto const targetBaseDir = _session->app().dumpStateAtExit().value_or(crispy::app::instance()->localStateDir() / "dump"); - auto const workDirName = fs::path(fmt::format("contour-dump-{:%Y-%m-%d-%H-%M-%S}", chrono::system_clock::now())); + auto const workDirName = fs::path(std::format("contour-dump-{:%Y-%m-%d-%H-%M-%S}", chrono::system_clock::now())); auto const targetDir = targetBaseDir / workDirName; auto const latestDirName = fs::path("latest"); // clang-format on diff --git a/src/contour/helper.h b/src/contour/helper.h index 07770ae3b1..916fe73e60 100644 --- a/src/contour/helper.h +++ b/src/contour/helper.h @@ -318,10 +318,10 @@ struct RenderStateManager } // namespace contour template <> -struct fmt::formatter: public fmt::formatter +struct std::formatter: std::formatter { using State = contour::RenderState; - static auto format(State state, format_context& ctx) -> format_context::iterator + auto format(State state, auto& ctx) const { string_view name; switch (state) @@ -331,6 +331,6 @@ struct fmt::formatter: public fmt::formatter case State::DirtyIdle: name = "dirty-idle"; break; case State::DirtyPainting: name = "dirty-painting"; break; } - return fmt::formatter {}.format(name, ctx); + return std::formatter::format(name, ctx); } }; diff --git a/src/crispy/App.cpp b/src/crispy/App.cpp index 216efd8bf1..d32c99c717 100644 --- a/src/crispy/App.cpp +++ b/src/crispy/App.cpp @@ -3,13 +3,13 @@ #include #include -#include - #include #include #include +#include #include +#include #include #include #include @@ -199,7 +199,7 @@ int app::licenseAction() int app::versionAction() { - std::cout << fmt::format("{} {}\n\n", _appTitle, _appVersion); + std::cout << std::format("{} {}\n\n", _appTitle, _appVersion); return EXIT_SUCCESS; } @@ -220,9 +220,9 @@ int app::run(int argc, char const* argv[]) } _flags = std::move(flagsOpt.value()); - // std::cout << fmt::format("Flags: {}\n", parameters().values.size()); + // std::cout << std::format("Flags: {}\n", parameters().values.size()); // for (auto const& [k, v]: parameters().values) - // std::cout << fmt::format(" - {}: {}\n", k, v); + // std::cout << std::format(" - {}: {}\n", k, v); for (auto const& [name, handler]: _handlers) if (parameters().get(name)) @@ -233,7 +233,7 @@ int app::run(int argc, char const* argv[]) } catch (exception const& e) { - std::cerr << fmt::format("Unhandled error caught. {}", e.what()) << '\n'; + std::cerr << std::format("Unhandled error caught. {}", e.what()) << '\n'; return EXIT_FAILURE; } } @@ -259,8 +259,8 @@ void app::customizeLogStoreOutput() const auto* const tagStart = "\033[1m"; auto const colorIndex = Colors.at(std::hash {}(msg.get_category().name()) % Colors.size()); - auto const msgStart = fmt::format("\033[38;5;{}m", colorIndex); - auto const resetSGR = fmt::format("\033[m"); + auto const msgStart = std::format("\033[38;5;{}m", colorIndex); + auto const resetSGR = std::format("\033[m"); return { tagStart, msgStart, resetSGR }; }(); @@ -281,11 +281,14 @@ void app::customizeLogStoreOutput() { // clang-format off auto const now = chrono::system_clock::now(); - auto const micros = - duration_cast(now.time_since_epoch()).count() % 1'000'000; + std::time_t const nowTimeT = std::chrono::system_clock::to_time_t(now); + std::tm const* tm = std::localtime(&nowTimeT); + std::stringstream dateTimeStrStream; + dateTimeStrStream << std::put_time(tm, "%Y-%m-%d %H:%M:%S"); + auto const micros = duration_cast(now.time_since_epoch()).count() % 1'000'000; result += sgrTag; - result += fmt::format("[{:%Y-%m-%d %H:%M:%S}.{:06}] [{}]", - chrono::system_clock::now(), + result += std::format("[{}.{:06}] [{}]", + dateTimeStrStream.str(), micros, msg.get_category().name()); result += sgrReset; @@ -321,7 +324,7 @@ void app::customizeLogStoreOutput() else { result += sgrTag; - result += fmt::format("[{}] ", "error"); + result += std::format("[{}] ", "error"); result += sgrReset; } diff --git a/src/crispy/BufferObject.h b/src/crispy/BufferObject.h index 3b8b32b077..d20864b92a 100644 --- a/src/crispy/BufferObject.h +++ b/src/crispy/BufferObject.h @@ -3,8 +3,6 @@ #include -#include - #include #include @@ -12,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -261,7 +260,7 @@ template gsl::span buffer_object::writeAtEnd(gsl::span data) noexcept { assert(_hotEnd + data.size() <= _end); - memcpy(_hotEnd, data.data(), data.size()); + std::memcpy(_hotEnd, data.data(), data.size()); return gsl::span { _hotEnd, data.size() }; } diff --git a/src/crispy/CLI.cpp b/src/crispy/CLI.cpp index 5af0889dc8..6c26e43a00 100644 --- a/src/crispy/CLI.cpp +++ b/src/crispy/CLI.cpp @@ -162,7 +162,7 @@ namespace // {{{ helper if (context.pos >= context.args.size()) throw parser_error("Not enough arguments specified."); - CLI_DEBUG(fmt::format("Consuming token '{}'", currentToken(context))); + CLI_DEBUG(std::format("Consuming token '{}'", currentToken(context))); return context.args.at(context.pos++); } @@ -329,7 +329,7 @@ namespace // {{{ helper void setOption(parse_context& context, string const& key, value value) { - CLI_DEBUG(fmt::format("setOption({}): {}", key, value)); + CLI_DEBUG(std::format("setOption({}): {}", key, value)); context.output.values[key] = std::move(value); } @@ -369,7 +369,7 @@ namespace // {{{ helper for (command const& command: context.currentCommand.back()->children) if (command.select == command_select::Implicit) { - CLI_DEBUG(fmt::format("Select implicit command {}.", command.name)); + CLI_DEBUG(std::format("Select implicit command {}.", command.name)); return &command; } @@ -410,19 +410,19 @@ namespace // {{{ helper if (command const* subcmd = tryLookupCommand(context)) { - CLI_DEBUG(fmt::format("parseCommand: found sub command: {}", subcmd->name)); + CLI_DEBUG(std::format("parseCommand: found sub command: {}", subcmd->name)); consumeToken(context); // Name was already ensured to be right (or is assumed to be right). parseCommand(*subcmd, context); } else if (command const* subcmd = tryImplicitCommand(context)) { - CLI_DEBUG(fmt::format("parseCommand: found implicit sub command: {}", subcmd->name)); + CLI_DEBUG(std::format("parseCommand: found implicit sub command: {}", subcmd->name)); // DO not consume token parseCommand(*subcmd, context); } else if (com.verbatim.has_value()) { - CLI_DEBUG(fmt::format("parseCommand: going verbatim.")); + CLI_DEBUG(std::format("parseCommand: going verbatim.")); if (hasTokensAvailable(context)) { if (currentToken(context) == "--") @@ -452,20 +452,20 @@ namespace // {{{ helper void validate(command const& com, parse_context& context, string const& keyPrefix) { - auto const key = keyPrefix.empty() ? string(com.name) : fmt::format("{}.{}", keyPrefix, com.name); + auto const key = keyPrefix.empty() ? string(com.name) : std::format("{}.{}", keyPrefix, com.name); // Ensure all required fields are provided for those commands that have been provided. for (option const& option: com.options) { - auto const optionKey = fmt::format("{}.{}", key, option.name.longName); + auto const optionKey = std::format("{}.{}", key, option.name.longName); // NOLINTNEXTLINE(readability-container-contains) if (option.presence == presence::Required && !context.output.values.count(optionKey)) - throw invalid_argument(fmt::format("Missing option: {}", optionKey)); + throw invalid_argument(std::format("Missing option: {}", optionKey)); } for (command const& subcmd: com.children) { - auto const commandKey = fmt::format("{}.{}", key, subcmd.name); + auto const commandKey = std::format("{}.{}", key, subcmd.name); if (context.output.get(commandKey)) validate(subcmd, context, key); } @@ -501,9 +501,9 @@ optional parse(command const& command, string_view_list const& args) return nullopt; // auto const& flags = context.output; - // std::cout << fmt::format("Flags: {}\n", flags.values.size()); + // std::cout << std::format("Flags: {}\n", flags.values.size()); // for (auto const & [k, v] : flags.values) - // std::cout << fmt::format(" - {}: {}\n", k, v); + // std::cout << std::format(" - {}: {}\n", k, v); validate(command, context, ""); @@ -550,7 +550,7 @@ namespace // {{{ helpers }(); if (!style.hyperlink) - return fmt::format("{}{}{}", pre, text, post); + return std::format("{}{}{}", pre, text, post); string output; size_t a = 0; @@ -816,9 +816,6 @@ namespace // {{{ helpers help_element::HelpText); // {{{ append default value, if any - // NB: It seems like fmt::format is having problems with - // formatting std::variant<>'s on some systems.' - // auto const defaultValueStr = fmt::format("{}", option.value); auto const defaultValueStr = [&]() -> string { if (holds_alternative(option.v)) return get(option.v) ? "true" : "false"; diff --git a/src/crispy/CLI.h b/src/crispy/CLI.h index 4adc560587..4f45472174 100644 --- a/src/crispy/CLI.h +++ b/src/crispy/CLI.h @@ -3,9 +3,8 @@ #include -#include - #include +#include #include #include #include @@ -226,24 +225,24 @@ namespace about // {{{ type formatters template <> -struct fmt::formatter +struct std::formatter { - static auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } - static auto format(crispy::cli::value const& value, format_context& ctx) -> format_context::iterator + auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } + auto format(crispy::cli::value const& value, auto& ctx) const { if (std::holds_alternative(value)) - return fmt::format_to(ctx.out(), "{}", std::get(value)); + return std::format_to(ctx.out(), "{}", std::get(value)); else if (std::holds_alternative(value)) - return fmt::format_to(ctx.out(), "{}", std::get(value)); + return std::format_to(ctx.out(), "{}", std::get(value)); else if (std::holds_alternative(value)) - return fmt::format_to(ctx.out(), "{}", std::get(value)); + return std::format_to(ctx.out(), "{}", std::get(value)); else if (std::holds_alternative(value)) - return fmt::format_to(ctx.out(), "{}", std::get(value)); + return std::format_to(ctx.out(), "{}", std::get(value)); else if (std::holds_alternative(value)) - return fmt::format_to(ctx.out(), "{}", std::get(value)); + return std::format_to(ctx.out(), "{}", std::get(value)); else - return fmt::format_to(ctx.out(), "?"); - // return fmt::format_to(ctx.out(), "{}..{}", range.from, range.to); + return std::format_to(ctx.out(), "?"); + // return std::format_to(ctx.out(), "{}..{}", range.from, range.to); } }; // }}} namespace fmt diff --git a/src/crispy/CLI_test.cpp b/src/crispy/CLI_test.cpp index a95a892f41..9323e96839 100644 --- a/src/crispy/CLI_test.cpp +++ b/src/crispy/CLI_test.cpp @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include - #include +#include + // TODO API / impl: // // - [ ] int-casts in cli.h are a nightmare. use size_t when applicable then. diff --git a/src/crispy/CMakeLists.txt b/src/crispy/CMakeLists.txt index 32c61b8527..874c1acf8f 100644 --- a/src/crispy/CMakeLists.txt +++ b/src/crispy/CMakeLists.txt @@ -46,7 +46,7 @@ if(MSVC) target_compile_definitions(crispy-core PUBLIC NOMINMAX) endif() -set(CRISPY_CORE_LIBS range-v3::range-v3 fmt::fmt-header-only unicode::unicode Microsoft.GSL::GSL boxed-cpp::boxed-cpp) +set(CRISPY_CORE_LIBS range-v3::range-v3 unicode::unicode Microsoft.GSL::GSL boxed-cpp::boxed-cpp) # if compiler is not MSVC if(NOT MSVC) @@ -137,7 +137,7 @@ if(CRISPY_TESTING) sort_test.cpp times_test.cpp ) -target_link_libraries(crispy_test fmt::fmt-header-only range-v3::range-v3 Catch2::Catch2WithMain crispy::core) +target_link_libraries(crispy_test range-v3::range-v3 Catch2::Catch2WithMain crispy::core) add_test(crispy_test ./crispy_test) endif() message(STATUS "[crispy] Compile unit tests: ${CRISPY_TESTING}") diff --git a/src/crispy/LRUCache_test.cpp b/src/crispy/LRUCache_test.cpp index 31b38e6dff..1c9237bd1b 100644 --- a/src/crispy/LRUCache_test.cpp +++ b/src/crispy/LRUCache_test.cpp @@ -1,10 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include - #include +#include #include #include @@ -16,10 +15,10 @@ using namespace std::string_view_literals; // { // std::ostream& out = std::cout; // -// out << fmt::format("lru_cache({}/{}): {}\n", cache.size(), cache.capacity(), header); +// out << std::format("lru_cache({}/{}): {}\n", cache.size(), cache.capacity(), header); // for (typename crispy::lru_cache::Item const& item: cache) // { -// out << fmt::format("{}: {}\n", item.key, item.value); +// out << std::format("{}: {}\n", item.key, item.value); // } // out << "\n"; // } @@ -33,7 +32,7 @@ static std::string join(std::vector const& list, std::string_view delimiter = if (i) s += delimiter; auto val = list[i]; - s += fmt::format("{}", val); + s += std::format("{}", val); } return s; } diff --git a/src/crispy/StackTrace.cpp b/src/crispy/StackTrace.cpp index 3b239d876e..0fecc7371e 100644 --- a/src/crispy/StackTrace.cpp +++ b/src/crispy/StackTrace.cpp @@ -1,11 +1,10 @@ #include #include -#include - #include #include #include +#include #include #include @@ -209,11 +208,11 @@ vector stack_trace::symbols() const #if defined(CONTOUR_STACKTRACE_ADDR2LINE) auto debugInfo = getDebugInfoForFrame(frame); if (!debugInfo) - output.emplace_back(fmt::format("{}", frame)); + output.emplace_back(std::format("{}", frame)); else output.emplace_back(debugInfo->text); #else - output.emplace_back(fmt::format("{}", frame)); + output.emplace_back(std::format("{}", frame)); #endif } return output; diff --git a/src/crispy/StrongHash.h b/src/crispy/StrongHash.h index 2680d2709c..7a2f4e8e4a 100644 --- a/src/crispy/StrongHash.h +++ b/src/crispy/StrongHash.h @@ -204,7 +204,7 @@ inline std::string to_string(strong_hash const& hash) { uint32_t u32[4]; std::memcpy(u32, &hash, sizeof(hash)); - return fmt::format("{:04X}{:04X}{:04X}{:04X}", u32[0], u32[1], u32[2], u32[3]); + return std::format("{:04X}{:04X}{:04X}{:04X}", u32[0], u32[1], u32[2], u32[3]); } inline std::string to_structured_string(strong_hash const& hash) @@ -218,7 +218,7 @@ inline std::string to_structured_string(strong_hash const& hash) if (!s.empty()) s += '.'; if (u32[i] != 0) - s += fmt::format("{:X}", u32[i]); + s += std::format("{:X}", u32[i]); } return s; } @@ -300,7 +300,7 @@ struct strong_hasher> } // namespace crispy template <> -struct fmt::formatter +struct std::formatter { template constexpr auto parse(ParseContext& ctx) @@ -310,6 +310,6 @@ struct fmt::formatter template auto format(crispy::strong_hash const& hash, FormatContext& ctx) const { - return fmt::format_to(ctx.out(), "{}", to_structured_string(hash)); + return std::format_to(ctx.out(), "{}", to_structured_string(hash)); } }; diff --git a/src/crispy/StrongLRUCache.h b/src/crispy/StrongLRUCache.h index 205f5b2c1d..756fcf863d 100644 --- a/src/crispy/StrongLRUCache.h +++ b/src/crispy/StrongLRUCache.h @@ -240,13 +240,12 @@ void strong_lru_cache::inspect(std::ostream& output) const // {{{ fmt template -struct fmt::formatter> +struct std::formatter> { - static auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } - static auto format(crispy::detail::lru_cache_entry const& entry, - format_context& ctx) -> format_context::iterator + auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } + auto format(crispy::detail::lru_cache_entry const& entry, auto& ctx) const { - return fmt::format_to(ctx.out(), "{}: {}", entry.key, entry.value); + return std::format_to(ctx.out(), "{}: {}", entry.key, entry.value); } }; // }}} diff --git a/src/crispy/StrongLRUHashtable.h b/src/crispy/StrongLRUHashtable.h index 0933c8ed30..9055b9b493 100644 --- a/src/crispy/StrongLRUHashtable.h +++ b/src/crispy/StrongLRUHashtable.h @@ -40,12 +40,12 @@ struct lru_hashtable_stats // {{{ fmt template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(crispy::lru_hashtable_stats stats, format_context& ctx) const -> format_context::iterator + auto format(crispy::lru_hashtable_stats stats, auto& ctx) const { return formatter::format( - fmt::format( + std::format( "{} hits, {} misses, {} evictions, {:.3}% hit rate", stats.hits, stats.misses, @@ -673,12 +673,12 @@ void strong_lru_hashtable::inspect(std::ostream& output) const while (entryIndex != 0) { entry const& entry = _entries[entryIndex]; - // output << fmt::format(" entry[{:03}] : LRU: {} <- -> {}, alt: {}; := {}\n", + // output << std::format(" entry[{:03}] : LRU: {} <- -> {}, alt: {}; := {}\n", // entryIndex, // entry.prevInLRU, // entry.nextInLRU, // entry.nextWithSameHash, - // entry.value.has_value() ? fmt::format("{}", entry.value.value()) : + // entry.value.has_value() ? std::format("{}", entry.value.value()) : // "nullopt"); if (entry.nextWithSameHash) ++hashSlotCollisions; @@ -692,24 +692,24 @@ void strong_lru_hashtable::inspect(std::ostream& output) const if (dr >= 99.99) return "100%"; else - return fmt::format("{:.02}%", dr); + return std::format("{:.02}%", dr); }; - output << fmt::format("=============================================================\n", _name); - output << fmt::format("Hashtale: {}\n", _name); - output << fmt::format("-------------------------------------------------------------\n", _name); - output << fmt::format("hashslot collisions : {} ({})\n", + output << std::format("=============================================================\n", _name); + output << std::format("Hashtale: {}\n", _name); + output << std::format("-------------------------------------------------------------\n", _name); + output << std::format("hashslot collisions : {} ({})\n", hashSlotCollisions, humanReadableUtiliation(hashSlotCollisions, _hashCount.value)); - output << fmt::format("stats : {}\n", _stats); - output << fmt::format("hash table capacity : {} ({} utilization)\n", + output << std::format("stats : {}\n", _stats); + output << std::format("hash table capacity : {} ({} utilization)\n", _hashCount.value, humanReadableUtiliation(_size, _hashCount.value)); - output << fmt::format("entry count : {}\n", _size); - output << fmt::format("entry capacity : {} ({} utilization)\n", + output << std::format("entry count : {}\n", _size); + output << std::format("entry capacity : {} ({} utilization)\n", _capacity.value, humanReadableUtiliation(_size, _capacity.value)); - output << fmt::format("-------------------------------------------------------------\n", _name); + output << std::format("-------------------------------------------------------------\n", _name); } // {{{ helpers diff --git a/src/crispy/StrongLRUHashtable_test.cpp b/src/crispy/StrongLRUHashtable_test.cpp index 21bc7a5007..9af37ec61d 100644 --- a/src/crispy/StrongLRUHashtable_test.cpp +++ b/src/crispy/StrongLRUHashtable_test.cpp @@ -406,7 +406,7 @@ TEST_CASE("strong_lru_hashtable.peek", "") for (int i = 1; i <= 4; ++i) { - INFO(fmt::format("i: {}", i)); + INFO(std::format("i: {}", i)); REQUIRE(cache.peek(h(1)) == 2); REQUIRE(joinHumanReadable(cache.hashes()) == sh(4, 3, 2, 1)); } diff --git a/src/crispy/assert.h b/src/crispy/assert.h index d2fab3f433..cfbd52e8a7 100644 --- a/src/crispy/assert.h +++ b/src/crispy/assert.h @@ -3,10 +3,10 @@ #include -#include - #include +#include #include +#include #include namespace crispy @@ -64,7 +64,7 @@ namespace detail if (fail_handler()) fail_handler()(text, message, file, line); else - fmt::print("[{}:{}] {} {}\n", file, line, message, text); + std::cerr << std::format("[{}:{}] {} {}\n", file, line, message, text); } catch (...) // NOLINT(bugprone-empty-catch) { @@ -85,9 +85,9 @@ inline void set_fail_handler(fail_handler_t handler) /// This method prints an error message and then terminates the program. [[noreturn]] inline void todo(std::string_view message = {}) { - fmt::print("TODO: We have reached some code that is missing an implementation.\n"); + std::cerr << std::format("TODO: We have reached some code that is missing an implementation.\n"); if (!message.empty()) - fmt::print("{}\n", message); + std::cerr << std::format("{}\n", message); std::abort(); } diff --git a/src/crispy/escape.h b/src/crispy/escape.h index 4643979c1b..cca9b09abb 100644 --- a/src/crispy/escape.h +++ b/src/crispy/escape.h @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once -#include - #include #include +#include +#include #include #include #include @@ -31,11 +31,11 @@ inline std::string escape(uint8_t ch, numeric_escape numericEscape = numeric_esc case '"': return "\\\""; default: if (0x20 <= ch && ch < 0x7E) - return fmt::format("{}", static_cast(ch)); + return std::format("{}", static_cast(ch)); else if (numericEscape == numeric_escape::Hex) - return fmt::format("\\x{:02x}", static_cast(ch) & 0xFF); + return std::format("\\x{:02x}", static_cast(ch) & 0xFF); else - return fmt::format("\\{:03o}", static_cast(ch) & 0xFF); + return std::format("\\{:03o}", static_cast(ch) & 0xFF); } } @@ -62,7 +62,7 @@ inline std::string escapeMarkdown(T begin, T end) auto escapeMarkdown = [](uint8_t ch) -> std::string { if (ch == '`') return "``` "; - return fmt::format("{}", static_cast(ch)); + return std::format("{}", static_cast(ch)); }; auto result = std::string {}; for (T cur = begin; cur != end; ++cur) diff --git a/src/crispy/file_descriptor.h b/src/crispy/file_descriptor.h index 101377434d..6684466e1d 100644 --- a/src/crispy/file_descriptor.h +++ b/src/crispy/file_descriptor.h @@ -1,8 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once -#include - +#include #include #if defined(_WIN32) @@ -119,21 +118,21 @@ using file_descriptor = native_handle; #if defined(_WIN32) template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(HANDLE value, format_context& ctx) const -> format_context::iterator + auto format(HANDLE value, auto& ctx) const { - auto str = fmt::format("0x{:X}", (unsigned long long) (value)); - return fmt::formatter::format(str, ctx); + auto str = std::format("0x{:X}", (unsigned long long) (value)); + return std::formatter::format(str, ctx); } }; #endif template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(crispy::file_descriptor const& fd, format_context& ctx) const -> format_context::iterator + auto format(crispy::file_descriptor const& fd, auto& ctx) const { - return fmt::formatter::format(fd.get(), ctx); + return std::formatter::format(fd.get(), ctx); } }; diff --git a/src/crispy/flags.h b/src/crispy/flags.h index 75a4feabb2..01c1e8501f 100644 --- a/src/crispy/flags.h +++ b/src/crispy/flags.h @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once -#include +#include namespace crispy { @@ -142,9 +142,9 @@ class flags } // namespace crispy template -struct fmt::formatter>: public fmt::formatter +struct std::formatter>: public std::formatter { - auto format(crispy::flags const& flags, format_context& ctx) const -> format_context::iterator + auto format(crispy::flags const& flags, auto& ctx) const { std::string result; for (auto i = 0u; i < sizeof(Enum) * 8; ++i) @@ -154,7 +154,7 @@ struct fmt::formatter>: public fmt::formatter continue; // We assume that only valid enum values resulting into non-empty strings. - auto const element = fmt::format("{}", flag); + auto const element = std::format("{}", flag); if (element.empty()) continue; diff --git a/src/crispy/interpolated_string_test.cpp b/src/crispy/interpolated_string_test.cpp index 29b16bfa80..0e7d1d9901 100644 --- a/src/crispy/interpolated_string_test.cpp +++ b/src/crispy/interpolated_string_test.cpp @@ -1,9 +1,9 @@ #include -#include - #include +#include + TEST_CASE("interpolated_string.parse_interpolation") { using crispy::parse_interpolation; diff --git a/src/crispy/logstore.h b/src/crispy/logstore.h index c6dbbd0b5e..3b959f6c2f 100644 --- a/src/crispy/logstore.h +++ b/src/crispy/logstore.h @@ -4,12 +4,11 @@ #include #include -#include - #include #include #include +#include #include #include #include @@ -93,10 +92,10 @@ class message_builder return *this; } - template - message_builder& append(fmt::format_string fmt, T const&... args) + template + message_builder& append(std::string_view fmt, Ts const&... args) { - _buffer += fmt::vformat(fmt, fmt::make_format_args(args...)); + _buffer += std::vformat(fmt, std::make_format_args(args...)); return *this; } @@ -105,10 +104,11 @@ class message_builder _buffer += msg; return *this; } + template message_builder& operator()(std::string_view fmt, Ts const&... args) { - _buffer += fmt::vformat(fmt, fmt::make_format_args(args...)); + _buffer += std::vformat(fmt, std::make_format_args(args...)); return *this; } @@ -330,7 +330,7 @@ inline category::~category() inline std::string category::defaultFormatter(message_builder const& message) { - return fmt::format("[{}:{}:{}]: {}\n", + return std::format("[{}:{}:{}]: {}\n", message.get_category().name(), message.location().file_name(), message.location().line(), diff --git a/src/crispy/point.h b/src/crispy/point.h index 2d22403dd7..fff095c47d 100644 --- a/src/crispy/point.h +++ b/src/crispy/point.h @@ -1,8 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once -#include - +#include #include namespace crispy @@ -87,10 +86,10 @@ constexpr inline bool operator!=(point const& a, point const& b) noexcept } // namespace crispy template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(crispy::point coord, format_context& ctx) const -> format_context::iterator + auto format(crispy::point coord, auto& ctx) const { - return formatter::format(fmt::format("({}, {})", coord.x, coord.y), ctx); + return formatter::format(std::format("({}, {})", coord.x, coord.y), ctx); } }; diff --git a/src/crispy/result_test.cpp b/src/crispy/result_test.cpp index e9f6a10b0f..b68395dd68 100644 --- a/src/crispy/result_test.cpp +++ b/src/crispy/result_test.cpp @@ -1,10 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include - #include +#include #include using crispy::failure; diff --git a/src/crispy/ring_test.cpp b/src/crispy/ring_test.cpp index af8be5291a..81b1d54257 100644 --- a/src/crispy/ring_test.cpp +++ b/src/crispy/ring_test.cpp @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include - #include #include +#include +#include using crispy::fixed_size_ring; using crispy::ring; @@ -16,14 +16,14 @@ namespace template [[maybe_unused]] void dump(ring const& r) { - fmt::print("ring(@{}): {{", r.zero_index()); + std::cout << std::format("ring(@{}): {{", r.zero_index()); for (size_t i = 0; i < r.size(); ++i) { if (i) - fmt::print(", "); - fmt::print("{}", r[i]); + std::cout << std::format(", "); + std::cout << std::format("{}", r[i]); } - fmt::print("}}\n"); + std::cout << std::format("}}\n"); } } // namespace diff --git a/src/crispy/size.h b/src/crispy/size.h index bccad59572..feca490bca 100644 --- a/src/crispy/size.h +++ b/src/crispy/size.h @@ -2,9 +2,8 @@ #include -#include - #include +#include #include namespace crispy @@ -113,11 +112,11 @@ constexpr size operator/(size a, size b) noexcept } // end namespace crispy template <> -struct fmt::formatter +struct std::formatter { - static auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } - static auto format(const crispy::size& value, format_context& ctx) -> format_context::iterator + auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } + auto format(const crispy::size& value, auto& ctx) const { - return fmt::format_to(ctx.out(), "{}x{}", value.width, value.height); + return std::format_to(ctx.out(), "{}x{}", value.width, value.height); } }; diff --git a/src/crispy/utils.h b/src/crispy/utils.h index 47b57ce339..43553845ad 100644 --- a/src/crispy/utils.h +++ b/src/crispy/utils.h @@ -3,13 +3,12 @@ #include #include -#include - #include #include #include #include +#include #include #include #include @@ -99,7 +98,7 @@ std::string joinHumanReadable(std::vector const& list, std::string_view sep = { if (i != 0) result << sep; - result << fmt::format("{}", T(list[i])); + result << std::format("{}", T(list[i])); } return result.str(); } @@ -112,7 +111,7 @@ std::string joinHumanReadableQuoted(std::vector const& list, U sep = ", ") { if (i != 0) result << sep; - result << '"' << crispy::escape(fmt::format("{}", list[i])) << '"'; + result << '"' << crispy::escape(std::format("{}", list[i])) << '"'; } return result.str(); } @@ -366,7 +365,7 @@ std::basic_string toHexString(std::basic_string_view input) std::basic_string output; for (T const ch: input) - output += fmt::format("{:02X}", static_cast(ch)); + output += std::format("{:02X}", static_cast(ch)); return output; } @@ -531,18 +530,18 @@ constexpr T nextPowerOfTwo(T v) noexcept inline std::string humanReadableBytes(uint64_t bytes) { if (bytes <= 1024) - return fmt::format("{} bytes", unsigned(bytes)); + return std::format("{} bytes", unsigned(bytes)); auto const kb = static_cast(bytes) / 1024.0; if (kb <= 1024.0) - return fmt::format("{:.03} KB", kb); + return std::format("{:.03} KB", kb); auto const mb = kb / 1024.0; if (mb <= 1024.0) - return fmt::format("{:.03} MB", mb); + return std::format("{:.03} MB", mb); auto const gb = mb / 1024.0; - return fmt::format("{:.03} GB", gb); + return std::format("{:.03} GB", gb); } template diff --git a/src/crispy/utils_test.cpp b/src/crispy/utils_test.cpp index b5016cad7e..9c462f393e 100644 --- a/src/crispy/utils_test.cpp +++ b/src/crispy/utils_test.cpp @@ -120,7 +120,7 @@ TEST_CASE("fromHexString") struct variable_collector { - auto operator()(string_view name) const { return fmt::format("({})", name); } + auto operator()(string_view name) const { return std::format("({})", name); } }; TEST_CASE("replaceVariables") diff --git a/src/text_shaper/CMakeLists.txt b/src/text_shaper/CMakeLists.txt index 67bf10fcea..ce20f215e4 100644 --- a/src/text_shaper/CMakeLists.txt +++ b/src/text_shaper/CMakeLists.txt @@ -24,7 +24,6 @@ add_library(text_shaper STATIC ${text_shaper_SRC}) set_target_properties(text_shaper PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_EXE}") set(TEXT_SHAPER_LIBS unicode::unicode boxed-cpp::boxed-cpp) -list(APPEND TEXT_SHAPER_LIBS fmt::fmt-header-only) list(APPEND TEXT_SHAPER_LIBS range-v3::range-v3) list(APPEND TEXT_SHAPER_LIBS Microsoft.GSL::GSL) diff --git a/src/text_shaper/font.cpp b/src/text_shaper/font.cpp index 16b1643a9e..081fd0e943 100644 --- a/src/text_shaper/font.cpp +++ b/src/text_shaper/font.cpp @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include +#include using std::string; using std::string_view; @@ -13,10 +13,10 @@ string font_description::toPattern() const { string m; if (weight != font_weight::normal) - m = fmt::format(" {}", weight); + m = std::format(" {}", weight); if (slant != font_slant::normal) - m = fmt::format(" {}", slant); - return fmt::format("{}{}", familyName, m); + m = std::format(" {}", slant); + return std::format("{}{}", familyName, m); } font_description font_description::parse(string_view pattern) diff --git a/src/text_shaper/font.h b/src/text_shaper/font.h index a6b0447eca..9291f3da9e 100644 --- a/src/text_shaper/font.h +++ b/src/text_shaper/font.h @@ -16,9 +16,8 @@ #include #endif -#include - #include +#include #include #include #include @@ -341,18 +340,18 @@ struct hash // {{{ fmt formatter template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::DPI dpi, format_context& ctx) const -> format_context::iterator + auto format(text::DPI dpi, auto& ctx) const { - return formatter::format(fmt::format("{}x{}", dpi.x, dpi.y), ctx); + return formatter::format(std::format("{}x{}", dpi.x, dpi.y), ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(text::font_weight value, format_context& ctx) const -> format_context::iterator + auto format(text::font_weight value, auto& ctx) const { string_view name; switch (value) @@ -375,9 +374,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(text::font_slant value, format_context& ctx) const -> format_context::iterator + auto format(text::font_slant value, auto& ctx) const { string_view name; switch (value) @@ -391,9 +390,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(text::font_spacing value, format_context& ctx) const -> format_context::iterator + auto format(text::font_spacing value, auto& ctx) const { string_view name; switch (value) @@ -406,12 +405,12 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::font_description const& desc, format_context& ctx) const -> format_context::iterator + auto format(text::font_description const& desc, auto& ctx) const { return formatter::format( - fmt::format("(family={} weight={} slant={} spacing={}, strict_spacing={})", + std::format("(family={} weight={} slant={} spacing={}, strict_spacing={})", desc.familyName, desc.weight, desc.slant, @@ -422,11 +421,11 @@ struct fmt::formatter: fmt::formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::font_metrics const& metrics, format_context& ctx) const -> format_context::iterator + auto format(text::font_metrics const& metrics, auto& ctx) const { - return formatter::format(fmt::format("({}, {}, {}, {}, {}, {})", + return formatter::format(std::format("({}, {}, {}, {}, {}, {})", metrics.lineHeight, metrics.advance, metrics.ascender, @@ -438,58 +437,58 @@ struct fmt::formatter: fmt::formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::font_size size, format_context& ctx) const -> format_context::iterator + auto format(text::font_size size, auto& ctx) const { - return formatter::format(fmt::format("{}pt", size.pt), ctx); + return formatter::format(std::format("{}pt", size.pt), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::font_key key, format_context& ctx) const -> format_context::iterator + auto format(text::font_key key, auto& ctx) const { - return formatter::format(fmt::format("{}", key.value), ctx); + return formatter::format(std::format("{}", key.value), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::glyph_index value, format_context& ctx) const -> format_context::iterator + auto format(text::glyph_index value, auto& ctx) const { - return formatter::format(fmt::format("{}", value.value), ctx); + return formatter::format(std::format("{}", value.value), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::glyph_key const& key, format_context& ctx) const -> format_context::iterator + auto format(text::glyph_key const& key, auto& ctx) const { #if defined(GLYPH_KEY_DEBUG) return formatter::format( - fmt::format("({}, {}:{}, \"{}\")", + std::format("({}, {}:{}, \"{}\")", key.size, key.font, key.index, unicode::convert_to(std::u32string_view(key.text.data(), key.text.size()))), ctx); #else - return formatter::format(fmt::format("({}, {}, {})", key.font, key.size, key.index), + return formatter::format(std::format("({}, {}, {})", key.font, key.size, key.index), ctx); #endif } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::font_feature value, format_context& ctx) const -> format_context::iterator + auto format(text::font_feature value, auto& ctx) const { - return formatter::format(fmt::format("{}{}{}{}{}", + return formatter::format(std::format("{}{}{}{}{}", value.enabled ? '+' : '-', value.name[0], value.name[1], @@ -500,9 +499,9 @@ struct fmt::formatter: fmt::formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::render_mode value, format_context& ctx) const -> format_context::iterator + auto format(text::render_mode value, auto& ctx) const { string_view name; switch (value) @@ -513,7 +512,7 @@ struct fmt::formatter: fmt::formatter case text::render_mode::lcd: name = "LCD"; break; case text::render_mode::color: name = "Color"; break; } - return fmt::formatter::format(name, ctx); + return std::formatter::format(name, ctx); } }; // }}} diff --git a/src/text_shaper/font_locator.h b/src/text_shaper/font_locator.h index ee5095dc7b..a2dbcee700 100644 --- a/src/text_shaper/font_locator.h +++ b/src/text_shaper/font_locator.h @@ -3,11 +3,10 @@ #include -#include - #include #include +#include #include #include #include @@ -74,36 +73,36 @@ class font_locator } // namespace text template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::font_path spec, format_context& ctx) const -> format_context::iterator + auto format(text::font_path spec, auto& ctx) const { - auto weightMod = spec.weight ? fmt::format(" {}", spec.weight.value()) : ""; - auto slantMod = spec.slant ? fmt::format(" {}", spec.slant.value()) : ""; - return formatter::format(fmt::format("path {}{}{}", spec.value, weightMod, slantMod), + auto weightMod = spec.weight ? std::format(" {}", spec.weight.value()) : ""; + auto slantMod = spec.slant ? std::format(" {}", spec.slant.value()) : ""; + return formatter::format(std::format("path {}{}{}", spec.value, weightMod, slantMod), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::font_memory_ref ref, format_context& ctx) const -> format_context::iterator + auto format(text::font_memory_ref ref, auto& ctx) const { - return formatter::format(fmt::format("in-memory: {}", ref.identifier), ctx); + return formatter::format(std::format("in-memory: {}", ref.identifier), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::font_source source, format_context& ctx) const -> format_context::iterator + auto format(text::font_source source, auto& ctx) const { std::string text; if (std::holds_alternative(source)) - text = fmt::format("{}", std::get(source)); + text = std::format("{}", std::get(source)); else if (std::holds_alternative(source)) - text = fmt::format("{}", std::get(source)); + text = std::format("{}", std::get(source)); return formatter::format(text, ctx); } }; diff --git a/src/text_shaper/fontconfig_locator.cpp b/src/text_shaper/fontconfig_locator.cpp index 4b992ea949..db3a4b9b81 100644 --- a/src/text_shaper/fontconfig_locator.cpp +++ b/src/text_shaper/fontconfig_locator.cpp @@ -36,7 +36,7 @@ namespace case FC_DUAL: return "dual"; case FC_MONO: return "mono"; case FC_CHARCELL: return "charcell"; - default: return fmt::format("({})", value); + default: return std::format("({})", value); } } @@ -256,8 +256,8 @@ font_source_list fontconfig_locator::locate(font_description const& description) locatorLog()("Font {} (ttc index {}, weight {}, slant {}, spacing {}) in chain: {}", output.size(), ttcIndex, - weight.has_value() ? fmt::format("{}", *weight) : "NONE", - slant.has_value() ? fmt::format("{}", *slant) : "NONE", + weight.has_value() ? std::format("{}", *weight) : "NONE", + slant.has_value() ? std::format("{}", *slant) : "NONE", spacing, (char const*) file); }; diff --git a/src/text_shaper/open_shaper.cpp b/src/text_shaper/open_shaper.cpp index 8a3e467ae1..67c02ee698 100644 --- a/src/text_shaper/open_shaper.cpp +++ b/src/text_shaper/open_shaper.cpp @@ -92,7 +92,7 @@ struct hash { auto fnv = crispy::fnv(); return size_t( - fnv(fnv(fd.path), to_string(fd.size.pt), fmt::format("{}", fd.weight))); // SSO should kick in. + fnv(fnv(fd.path), to_string(fd.size.pt), std::format("{}", fd.weight))); // SSO should kick in. } }; } // namespace std diff --git a/src/text_shaper/shaper.h b/src/text_shaper/shaper.h index 50d865a5a2..b0197a844f 100644 --- a/src/text_shaper/shaper.h +++ b/src/text_shaper/shaper.h @@ -12,12 +12,11 @@ #include #include -#include - #include #include #include +#include #include #include #include @@ -157,9 +156,9 @@ class shaper // {{{ fmtlib support template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::bitmap_format value, format_context& ctx) const -> format_context::iterator + auto format(text::bitmap_format value, auto& ctx) const { string_view name; switch (value) @@ -173,11 +172,11 @@ struct fmt::formatter: fmt::formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::glyph_position const& gpos, format_context& ctx) const -> format_context::iterator + auto format(text::glyph_position const& gpos, auto& ctx) const { - return formatter::format(fmt::format("({}+{}+{}|{}+{})", + return formatter::format(std::format("({}+{}+{}|{}+{})", gpos.glyph.index.value, gpos.offset.x, gpos.offset.y, @@ -188,11 +187,11 @@ struct fmt::formatter: fmt::formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(text::rasterized_glyph const& glyph, format_context& ctx) const -> format_context::iterator + auto format(text::rasterized_glyph const& glyph, auto& ctx) const { - return formatter::format(fmt::format("rasterized_glyph({}, {}+{}, {})", + return formatter::format(std::format("rasterized_glyph({}, {}+{}, {})", glyph.index.value, glyph.bitmapSize, glyph.position, diff --git a/src/vtbackend/CMakeLists.txt b/src/vtbackend/CMakeLists.txt index f4abfccf1e..8899089fdb 100644 --- a/src/vtbackend/CMakeLists.txt +++ b/src/vtbackend/CMakeLists.txt @@ -97,7 +97,6 @@ target_link_libraries(vtbackend PUBLIC Microsoft.GSL::GSL Threads::Threads crispy::core - fmt::fmt-header-only range-v3::range-v3 unicode::unicode vtparser @@ -132,7 +131,7 @@ if(LIBTERMINAL_TESTING) SixelParser_test.cpp ViCommands_test.cpp ) - target_link_libraries(vtbackend_test fmt::fmt-header-only Catch2::Catch2WithMain vtbackend) + target_link_libraries(vtbackend_test Catch2::Catch2WithMain vtbackend) add_test(vtbackend_test ./vtbackend_test) if (LIBTERMINAL_BUILD_BENCH_HEADLESS) @@ -146,7 +145,6 @@ if(LIBTERMINAL_TESTING) ) target_link_libraries(bench-headless - fmt::fmt-header-only termbench::termbench vtbackend ) diff --git a/src/vtbackend/Capabilities.h b/src/vtbackend/Capabilities.h index f31adc7970..5564c670a0 100644 --- a/src/vtbackend/Capabilities.h +++ b/src/vtbackend/Capabilities.h @@ -1,9 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once -#include - #include +#include #include #include #include @@ -20,7 +19,7 @@ struct Code [[nodiscard]] std::string hex() const { - return fmt::format("{:02X}{:02X}", unsigned((code >> 8) & 0xFF), unsigned(code & 0xFF)); + return std::format("{:02X}{:02X}", unsigned((code >> 8) & 0xFF), unsigned(code & 0xFF)); } constexpr Code() noexcept = default; @@ -105,9 +104,9 @@ class StaticDatabase: public Database } // namespace vtbackend::capabilities template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::capabilities::Code value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::capabilities::Code value, auto& ctx) const { return formatter::format(value.hex(), ctx); } diff --git a/src/vtbackend/Capabilities_test.cpp b/src/vtbackend/Capabilities_test.cpp index ecf54cff47..fff49aeb7b 100644 --- a/src/vtbackend/Capabilities_test.cpp +++ b/src/vtbackend/Capabilities_test.cpp @@ -3,10 +3,10 @@ #include -#include - #include +#include + using namespace std::string_view_literals; using crispy::fromHexString; diff --git a/src/vtbackend/CellFlags.h b/src/vtbackend/CellFlags.h index b16daaeef0..ab9f8a34b7 100644 --- a/src/vtbackend/CellFlags.h +++ b/src/vtbackend/CellFlags.h @@ -3,9 +3,8 @@ #include -#include - #include +#include namespace vtbackend { @@ -40,9 +39,9 @@ using CellFlags = crispy::flags; // {{{ template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(const vtbackend::CellFlag value, format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::CellFlag value, auto& ctx) const { string_view s; diff --git a/src/vtbackend/Charset.cpp b/src/vtbackend/Charset.cpp index 95aebc6595..59c869c892 100644 --- a/src/vtbackend/Charset.cpp +++ b/src/vtbackend/Charset.cpp @@ -9,7 +9,7 @@ constexpr CharsetMap usasciiCharset() noexcept CharsetMap result {}; for (char ch = 0; ch < 127; ++ch) - result[static_cast(ch)] = static_cast(ch); + result[static_cast(ch)] = static_cast(ch); return result; } @@ -30,14 +30,14 @@ constexpr CharsetMap createGermanCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('@')] = 0x00A7; // U'§'; - result[static_cast('[')] = 0x00C4; // U'Ä'; - result[static_cast('\\')] = 0x00D6; // U'Ö'; - result[static_cast(']')] = 0x00DC; // U'Ü'; - result[static_cast('{')] = 0x00E4; // U'ä'; - result[static_cast('|')] = 0x00F6; // U'ö'; - result[static_cast('}')] = 0x00FC; // U'ü'; - result[static_cast('~')] = 0x00DF; // U'ß'; + result[static_cast('@')] = 0x00A7; // U'§'; + result[static_cast('[')] = 0x00C4; // U'Ä'; + result[static_cast('\\')] = 0x00D6; // U'Ö'; + result[static_cast(']')] = 0x00DC; // U'Ü'; + result[static_cast('{')] = 0x00E4; // U'ä'; + result[static_cast('|')] = 0x00F6; // U'ö'; + result[static_cast('}')] = 0x00FC; // U'ü'; + result[static_cast('~')] = 0x00DF; // U'ß'; return result; } @@ -49,37 +49,37 @@ constexpr CharsetMap createSpecialCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('`')] = 0x25c6; // '◆' - result[static_cast('a')] = 0x2592; // '▒' - result[static_cast('b')] = 0x2409; // '␉' - result[static_cast('c')] = 0x240c; // '␌' - result[static_cast('d')] = 0x240d; // '␍' - result[static_cast('e')] = 0x240a; // '␊' - result[static_cast('f')] = 0x00b0; // '°' - result[static_cast('g')] = 0x00b1; // '±' - result[static_cast('h')] = 0x2424; // '␤' - result[static_cast('i')] = 0x240b; // '␋' - result[static_cast('j')] = 0x2518; // '┘' - result[static_cast('k')] = 0x2510; // '┐' - result[static_cast('l')] = 0x250c; // '┌' - result[static_cast('m')] = 0x2514; // '└' - result[static_cast('n')] = 0x253c; // '┼' - result[static_cast('o')] = 0x23ba; // '⎺' - result[static_cast('p')] = 0x23bb; // '⎻' - result[static_cast('q')] = 0x2500; // '─' - result[static_cast('r')] = 0x23bc; // '⎼' - result[static_cast('s')] = 0x23bd; // '⎽' - result[static_cast('t')] = 0x251c; // '├' - result[static_cast('u')] = 0x2524; // '┤' - result[static_cast('v')] = 0x2534; // '┴' - result[static_cast('w')] = 0x252c; // '┬' - result[static_cast('x')] = 0x2502; // '│' - result[static_cast('y')] = 0x2264; // '≤' - result[static_cast('z')] = 0x2265; // '≥' - result[static_cast('{')] = 0x03c0; // 'π' - result[static_cast('|')] = 0x2260; // '≠' - result[static_cast('}')] = 0x00a3; // '£' - result[static_cast('~')] = 0x00b7; // '·' + result[static_cast('`')] = 0x25c6; // '◆' + result[static_cast('a')] = 0x2592; // '▒' + result[static_cast('b')] = 0x2409; // '␉' + result[static_cast('c')] = 0x240c; // '␌' + result[static_cast('d')] = 0x240d; // '␍' + result[static_cast('e')] = 0x240a; // '␊' + result[static_cast('f')] = 0x00b0; // '°' + result[static_cast('g')] = 0x00b1; // '±' + result[static_cast('h')] = 0x2424; // '␤' + result[static_cast('i')] = 0x240b; // '␋' + result[static_cast('j')] = 0x2518; // '┘' + result[static_cast('k')] = 0x2510; // '┐' + result[static_cast('l')] = 0x250c; // '┌' + result[static_cast('m')] = 0x2514; // '└' + result[static_cast('n')] = 0x253c; // '┼' + result[static_cast('o')] = 0x23ba; // '⎺' + result[static_cast('p')] = 0x23bb; // '⎻' + result[static_cast('q')] = 0x2500; // '─' + result[static_cast('r')] = 0x23bc; // '⎼' + result[static_cast('s')] = 0x23bd; // '⎽' + result[static_cast('t')] = 0x251c; // '├' + result[static_cast('u')] = 0x2524; // '┤' + result[static_cast('v')] = 0x2534; // '┴' + result[static_cast('w')] = 0x252c; // '┬' + result[static_cast('x')] = 0x2502; // '│' + result[static_cast('y')] = 0x2264; // '≤' + result[static_cast('z')] = 0x2265; // '≥' + result[static_cast('{')] = 0x03c0; // 'π' + result[static_cast('|')] = 0x2260; // '≠' + result[static_cast('}')] = 0x00a3; // '£' + result[static_cast('~')] = 0x00b7; // '·' return result; } @@ -91,15 +91,15 @@ constexpr CharsetMap createDutchCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('#')] = 0x00A3; // U'£'; - result[static_cast('@')] = 0x00BE; // U'¾'; - // TODO: result[static_cast('[')] = U'ij'; - result[static_cast('\\')] = 0x00BD; // U'½'; - result[static_cast(']')] = 0x007C; // U'|'; - result[static_cast('{')] = 0x00A8; // U'¨'; - result[static_cast('|')] = 0x0066; // U'f'; - result[static_cast('}')] = 0x00BC; // U'¼'; - result[static_cast('~')] = 0x00B4; // U'´'; + result[static_cast('#')] = 0x00A3; // U'£'; + result[static_cast('@')] = 0x00BE; // U'¾'; + // TODO: result[static_cast('[')] = U'ij'; + result[static_cast('\\')] = 0x00BD; // U'½'; + result[static_cast(']')] = 0x007C; // U'|'; + result[static_cast('{')] = 0x00A8; // U'¨'; + result[static_cast('|')] = 0x0066; // U'f'; + result[static_cast('}')] = 0x00BC; // U'¼'; + result[static_cast('~')] = 0x00B4; // U'´'; return result; } @@ -111,15 +111,15 @@ constexpr CharsetMap createFinnishCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('[')] = 0x00C4; // U'Ä'; - result[static_cast('\\')] = 0x00D6; // U'Ö'; - result[static_cast(']')] = 0x00C5; // U'Å'; - result[static_cast('^')] = 0x00DC; // U'Ü'; - result[static_cast('`')] = 0x00E9; // U'é'; - result[static_cast('{')] = 0x00E4; // U'ä'; - result[static_cast('|')] = 0x00F6; // U'ö'; - result[static_cast('}')] = 0x00E5; // U'å'; - result[static_cast('~')] = 0x00FC; // U'ü'; + result[static_cast('[')] = 0x00C4; // U'Ä'; + result[static_cast('\\')] = 0x00D6; // U'Ö'; + result[static_cast(']')] = 0x00C5; // U'Å'; + result[static_cast('^')] = 0x00DC; // U'Ü'; + result[static_cast('`')] = 0x00E9; // U'é'; + result[static_cast('{')] = 0x00E4; // U'ä'; + result[static_cast('|')] = 0x00F6; // U'ö'; + result[static_cast('}')] = 0x00E5; // U'å'; + result[static_cast('~')] = 0x00FC; // U'ü'; return result; } @@ -130,15 +130,15 @@ constexpr CharsetMap createFrenchCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('#')] = 0x00A3; // U'£'; - result[static_cast('@')] = 0x00E0; // U'à'; - result[static_cast('[')] = 0x00B0; // U'°'; - result[static_cast('\\')] = 0x00E7; // U'ç'; - result[static_cast(']')] = 0x00A7; // U'§'; - result[static_cast('{')] = 0x00E9; // U'é'; - result[static_cast('|')] = 0x00F9; // U'ù'; - result[static_cast('}')] = 0x00E8; // U'è'; - result[static_cast('~')] = 0x00A8; // U'¨'; + result[static_cast('#')] = 0x00A3; // U'£'; + result[static_cast('@')] = 0x00E0; // U'à'; + result[static_cast('[')] = 0x00B0; // U'°'; + result[static_cast('\\')] = 0x00E7; // U'ç'; + result[static_cast(']')] = 0x00A7; // U'§'; + result[static_cast('{')] = 0x00E9; // U'é'; + result[static_cast('|')] = 0x00F9; // U'ù'; + result[static_cast('}')] = 0x00E8; // U'è'; + result[static_cast('~')] = 0x00A8; // U'¨'; return result; } @@ -149,16 +149,16 @@ constexpr CharsetMap createFrenchCanadianCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('@')] = 0x00E0; // U'à'; - result[static_cast('[')] = 0x00E2; // U'â'; - result[static_cast('\\')] = 0x00E7; // U'ç'; - result[static_cast(']')] = 0x00EA; // U'ê'; - result[static_cast('^')] = 0x00EE; // U'î'; - result[static_cast('`')] = 0x00F4; // U'ô'; - result[static_cast('{')] = 0x00E9; // U'é'; - result[static_cast('|')] = 0x00F9; // U'ù'; - result[static_cast('}')] = 0x00E8; // U'è'; - result[static_cast('~')] = 0x00FB; // U'û'; + result[static_cast('@')] = 0x00E0; // U'à'; + result[static_cast('[')] = 0x00E2; // U'â'; + result[static_cast('\\')] = 0x00E7; // U'ç'; + result[static_cast(']')] = 0x00EA; // U'ê'; + result[static_cast('^')] = 0x00EE; // U'î'; + result[static_cast('`')] = 0x00F4; // U'ô'; + result[static_cast('{')] = 0x00E9; // U'é'; + result[static_cast('|')] = 0x00F9; // U'ù'; + result[static_cast('}')] = 0x00E8; // U'è'; + result[static_cast('~')] = 0x00FB; // U'û'; return result; } @@ -170,16 +170,16 @@ constexpr CharsetMap createNorwegianDanishCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('@')] = 0x00C4; // U'Ä'; - result[static_cast('[')] = 0x00C6; // U'Æ'; - result[static_cast('\\')] = 0x00D8; // U'Ø'; - result[static_cast(']')] = 0x00C5; // U'Å'; - result[static_cast('^')] = 0x00DC; // U'Ü'; - result[static_cast('`')] = 0x00E4; // U'ä'; - result[static_cast('{')] = 0x00E6; // U'æ'; - result[static_cast('|')] = 0x00F8; // U'ø'; - result[static_cast('}')] = 0x00E5; // U'å'; - result[static_cast('~')] = 0x00FC; // U'ü'; + result[static_cast('@')] = 0x00C4; // U'Ä'; + result[static_cast('[')] = 0x00C6; // U'Æ'; + result[static_cast('\\')] = 0x00D8; // U'Ø'; + result[static_cast(']')] = 0x00C5; // U'Å'; + result[static_cast('^')] = 0x00DC; // U'Ü'; + result[static_cast('`')] = 0x00E4; // U'ä'; + result[static_cast('{')] = 0x00E6; // U'æ'; + result[static_cast('|')] = 0x00F8; // U'ø'; + result[static_cast('}')] = 0x00E5; // U'å'; + result[static_cast('~')] = 0x00FC; // U'ü'; return result; } @@ -190,14 +190,14 @@ constexpr CharsetMap createSpanishCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('#')] = 0x00A3; // U'£'; - result[static_cast('@')] = 0x00A7; // U'§'; - result[static_cast('[')] = 0x00A1; // U'¡'; - result[static_cast('\\')] = 0x00D1; // U'Ñ'; - result[static_cast(']')] = 0x00BF; // U'¿'; - result[static_cast('{')] = 0x00B0; // U'°'; - result[static_cast('|')] = 0x00F1; // U'ñ'; - result[static_cast('}')] = 0x00E7; // U'ç'; + result[static_cast('#')] = 0x00A3; // U'£'; + result[static_cast('@')] = 0x00A7; // U'§'; + result[static_cast('[')] = 0x00A1; // U'¡'; + result[static_cast('\\')] = 0x00D1; // U'Ñ'; + result[static_cast(']')] = 0x00BF; // U'¿'; + result[static_cast('{')] = 0x00B0; // U'°'; + result[static_cast('|')] = 0x00F1; // U'ñ'; + result[static_cast('}')] = 0x00E7; // U'ç'; return result; } @@ -209,16 +209,16 @@ constexpr CharsetMap createSwedishCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('@')] = 0x00C9; // U'É'; - result[static_cast('[')] = 0x00C4; // U'Ä'; - result[static_cast('\\')] = 0x00D6; // U'Ö'; - result[static_cast(']')] = 0x00C5; // U'Å'; - result[static_cast('^')] = 0x00DC; // U'Ü'; - result[static_cast('`')] = 0x00E9; // U'é'; - result[static_cast('{')] = 0x00E4; // U'ä'; - result[static_cast('|')] = 0x00F6; // U'ö'; - result[static_cast('}')] = 0x00E5; // U'å'; - result[static_cast('~')] = 0x00FC; // U'ü'; + result[static_cast('@')] = 0x00C9; // U'É'; + result[static_cast('[')] = 0x00C4; // U'Ä'; + result[static_cast('\\')] = 0x00D6; // U'Ö'; + result[static_cast(']')] = 0x00C5; // U'Å'; + result[static_cast('^')] = 0x00DC; // U'Ü'; + result[static_cast('`')] = 0x00E9; // U'é'; + result[static_cast('{')] = 0x00E4; // U'ä'; + result[static_cast('|')] = 0x00F6; // U'ö'; + result[static_cast('}')] = 0x00E5; // U'å'; + result[static_cast('~')] = 0x00FC; // U'ü'; return result; } @@ -229,18 +229,18 @@ constexpr CharsetMap createSwissCharset() noexcept { auto result = usasciiCharset(); - result[static_cast('#')] = 0x00F9; // U'ù'; - result[static_cast('@')] = 0x00E0; // U'à'; - result[static_cast('[')] = 0x00E9; // U'é'; - result[static_cast('\\')] = 0x00E7; // U'ç'; - result[static_cast(']')] = 0x00EA; // U'ê'; - result[static_cast('^')] = 0x00EE; // U'î'; - result[static_cast('_')] = 0x00E8; // U'è'; - result[static_cast('`')] = 0x00F4; // U'ô'; - result[static_cast('{')] = 0x00E4; // U'ä'; - result[static_cast('|')] = 0x00F6; // U'ö'; - result[static_cast('}')] = 0x00FC; // U'ü'; - result[static_cast('~')] = 0x00FB; // U'û'; + result[static_cast('#')] = 0x00F9; // U'ù'; + result[static_cast('@')] = 0x00E0; // U'à'; + result[static_cast('[')] = 0x00E9; // U'é'; + result[static_cast('\\')] = 0x00E7; // U'ç'; + result[static_cast(']')] = 0x00EA; // U'ê'; + result[static_cast('^')] = 0x00EE; // U'î'; + result[static_cast('_')] = 0x00E8; // U'è'; + result[static_cast('`')] = 0x00F4; // U'ô'; + result[static_cast('{')] = 0x00E4; // U'ä'; + result[static_cast('|')] = 0x00F6; // U'ö'; + result[static_cast('}')] = 0x00FC; // U'ü'; + result[static_cast('~')] = 0x00FB; // U'û'; return result; } diff --git a/src/vtbackend/Charset.h b/src/vtbackend/Charset.h index 2c9693b894..7aaaaa17b4 100644 --- a/src/vtbackend/Charset.h +++ b/src/vtbackend/Charset.h @@ -1,16 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once -#include - #include +#include namespace vtbackend { using CharsetMap = std::array; -enum class CharsetId : uint8_t +enum class CharsetId : std::uint8_t { Special, // Special Character and Line Drawing Set @@ -27,7 +26,7 @@ enum class CharsetId : uint8_t USASCII }; -enum class CharsetTable : uint8_t +enum class CharsetTable : std::uint8_t { G0 = 0, G1 = 1, @@ -75,7 +74,7 @@ class CharsetMapping [[nodiscard]] char32_t map(CharsetTable table, char code) const noexcept { - return (*_tables[static_cast(table)])[static_cast(code)]; + return (*_tables[static_cast(table)])[static_cast(code)]; } constexpr void singleShift(CharsetTable table) noexcept { _tableForNextGraphic = table; } @@ -88,7 +87,7 @@ class CharsetMapping [[nodiscard]] bool isSelected(CharsetTable table, CharsetId id) const noexcept { - return _tables[static_cast(table)] == charsetMap(id); + return _tables[static_cast(table)] == charsetMap(id); } [[nodiscard]] bool isSelected(CharsetId id) const noexcept @@ -99,7 +98,7 @@ class CharsetMapping // Selects a given designated character set into the table G0, G1, G2, or G3. void select(CharsetTable table, CharsetId id) noexcept { - _tables[static_cast(table)] = charsetMap(id); + _tables[static_cast(table)] = charsetMap(id); } private: diff --git a/src/vtbackend/Color.cpp b/src/vtbackend/Color.cpp index d95aee0188..45eb78f304 100644 --- a/src/vtbackend/Color.cpp +++ b/src/vtbackend/Color.cpp @@ -14,7 +14,7 @@ string to_string(Color color) using Type = ColorType; switch (color.type()) { - case Type::Indexed: return fmt::format("{}", color.index()); + case Type::Indexed: return std::format("{}", color.index()); case Type::Bright: switch (color.index()) { @@ -44,7 +44,7 @@ string to_string(Color color) default: return "?"; } case Type::RGB: - return fmt::format("'#{:02X}{:02X}{:02X}'", color.rgb().red, color.rgb().green, color.rgb().blue); + return std::format("'#{:02X}{:02X}{:02X}'", color.rgb().red, color.rgb().green, color.rgb().blue); case Type::Undefined: break; } return "?"; @@ -64,7 +64,7 @@ string to_string(IndexedColor color) case IndexedColor::White: return "white"; case IndexedColor::Default: return "DEFAULT"; } - return fmt::format("IndexedColor:{}", static_cast(color)); + return std::format("IndexedColor:{}", static_cast(color)); } string to_string(BrightColor color) @@ -80,7 +80,7 @@ string to_string(BrightColor color) case BrightColor::Cyan: return "bright-cyan"; case BrightColor::White: return "bright-white"; } - return fmt::format("BrightColor:{}", static_cast(color)); + return std::format("BrightColor:{}", static_cast(color)); } RGBColor::RGBColor(std::string const& hexCode): RGBColor() @@ -121,12 +121,12 @@ RGBAColor& RGBAColor::operator=(string const& hexCode) string to_string(RGBColor c) { - return fmt::format("'#{:02X}{:02X}{:02X}'", c.red, c.green, c.blue); + return std::format("'#{:02X}{:02X}{:02X}'", c.red, c.green, c.blue); } string to_string(RGBAColor c) { - return fmt::format("'#{:02X}{:02X}{:02X}{:02X}'", c.red(), c.green(), c.blue(), c.alpha()); + return std::format("'#{:02X}{:02X}{:02X}{:02X}'", c.red(), c.green(), c.blue(), c.alpha()); } optional parseColor(string_view const& value) diff --git a/src/vtbackend/Color.h b/src/vtbackend/Color.h index fb87651080..c2fbe038ff 100644 --- a/src/vtbackend/Color.h +++ b/src/vtbackend/Color.h @@ -3,11 +3,10 @@ #include -#include - #include #include #include +#include #include #include #include @@ -401,37 +400,36 @@ std::optional parseColor(std::string_view const& value); // {{{ fmtlib custom formatter template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::Color value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::Color value, auto& ctx) const { return formatter::format(to_string(value), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::RGBColor value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::RGBColor value, auto& ctx) const { return formatter::format(to_string(value), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - template - auto format(vtbackend::RGBAColor value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::RGBAColor value, auto& ctx) const { return formatter::format(to_string(value), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::CellRGBColor value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::CellRGBColor value, auto& ctx) const { if (std::holds_alternative(value)) return formatter::format("CellForeground", ctx); @@ -443,11 +441,11 @@ struct fmt::formatter: fmt::formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::RGBColorPair value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::RGBColorPair value, auto& ctx) const { - return formatter::format(fmt::format("{}/{}", value.foreground, value.background), ctx); + return formatter::format(std::format("{}/{}", value.foreground, value.background), ctx); } }; // }}} diff --git a/src/vtbackend/ColorPalette.h b/src/vtbackend/ColorPalette.h index e3195b5a85..30b326705a 100644 --- a/src/vtbackend/ColorPalette.h +++ b/src/vtbackend/ColorPalette.h @@ -6,12 +6,11 @@ #include -#include - #include #include #include #include +#include #include namespace vtbackend @@ -153,9 +152,9 @@ RGBColor apply(ColorPalette const& colorPalette, Color color, ColorTarget target // {{{ fmtlib custom formatter support template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::ColorPreference value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ColorPreference value, auto& ctx) const { string_view name; switch (value) @@ -168,9 +167,9 @@ struct fmt::formatter: fmt::formatter -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::ColorMode value, fmt::format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ColorMode value, auto& ctx) const { string_view name; switch (value) @@ -184,9 +183,9 @@ struct fmt::formatter: fmt::formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::ColorTarget value, fmt::format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ColorTarget value, auto& ctx) const { string_view name; switch (value) diff --git a/src/vtbackend/Functions.cpp b/src/vtbackend/Functions.cpp index 27ee9eaf92..25ec09ac44 100644 --- a/src/vtbackend/Functions.cpp +++ b/src/vtbackend/Functions.cpp @@ -8,10 +8,9 @@ #include #include -#include - #include #include +#include #include #include #include @@ -41,7 +40,7 @@ Function const* select(FunctionSelector const& selector, auto const i = (a + b) / 2; auto const& fui = availableDefinitions[i]; auto const rel = compare(selector, fui); - // std::cout << fmt::format(" - a:{:>2} b:{:>2} i:{} rel:{} I: {}\n", a, b, i, rel < 0 ? '<' : rel > 0 + // std::cout << std::format(" - a:{:>2} b:{:>2} i:{} rel:{} I: {}\n", a, b, i, rel < 0 ? '<' : rel > 0 // ? '>' : '=', I); if (rel > 0) a = i + 1; diff --git a/src/vtbackend/Functions.h b/src/vtbackend/Functions.h index fa29f81f7b..cd554af1ce 100644 --- a/src/vtbackend/Functions.h +++ b/src/vtbackend/Functions.h @@ -7,12 +7,11 @@ #include #include -#include - #include #include #include +#include #include #include @@ -203,7 +202,7 @@ struct Function if constexpr (sizeof...(Args) > 0) { result.reserve(sizeof...(Args) * 4); - ((result += fmt::format("{};", std::forward(parameters))), ...); + ((result += std::format("{};", std::forward(parameters))), ...); result.pop_back(); // remove trailing ';' } if (intermediate) @@ -927,10 +926,9 @@ struct std::hash // {{{ fmtlib support template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(const vtbackend::FunctionCategory value, - format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::FunctionCategory value, auto& ctx) const { using vtbackend::FunctionCategory; string_view name; @@ -962,43 +960,43 @@ struct fmt::formatter: fmt::formatter -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(const vtbackend::Function f, format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::Function f, auto& ctx) const { std::string value; switch (f.category) { case vtbackend::FunctionCategory::C0: - value = fmt::format("{}", crispy::escape(static_cast(f.finalSymbol))); + value = std::format("{}", crispy::escape(static_cast(f.finalSymbol))); break; case vtbackend::FunctionCategory::ESC: - value = fmt::format("{} {} {}", + value = std::format("{} {} {}", f.category, f.intermediate ? f.intermediate : ' ', f.finalSymbol ? f.finalSymbol : ' '); break; case vtbackend::FunctionCategory::OSC: - value = fmt::format("{} {}", f.category, f.maximumParameters); + value = std::format("{} {}", f.category, f.maximumParameters); break; case vtbackend::FunctionCategory::DCS: case vtbackend::FunctionCategory::CSI: if (f.minimumParameters == f.maximumParameters) - value = fmt::format("{} {} {} {} {}", + value = std::format("{} {} {} {} {}", f.category, f.leader ? f.leader : ' ', f.minimumParameters, f.intermediate ? f.intermediate : ' ', f.finalSymbol); else if (f.maximumParameters == vtbackend::ArgsMax) - value = fmt::format("{} {} {}.. {} {}", + value = std::format("{} {} {}.. {} {}", f.category, f.leader ? f.leader : ' ', f.minimumParameters, f.intermediate ? f.intermediate : ' ', f.finalSymbol); else - value = fmt::format("{} {} {}..{} {} {}", + value = std::format("{} {} {}..{} {} {}", f.category, f.leader ? f.leader : ' ', f.minimumParameters, @@ -1012,19 +1010,19 @@ struct fmt::formatter: fmt::formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(const vtbackend::FunctionSelector f, format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::FunctionSelector f, auto& ctx) const { std::string value; // clang-format off switch (f.category) { case vtbackend::FunctionCategory::OSC: - value = fmt::format("{} {}", f.category, f.argc); + value = std::format("{} {}", f.category, f.argc); break; default: - value = fmt::format("{} {} {} {} {}", + value = std::format("{} {} {} {} {}", f.category, f.leader ? f.leader : ' ', f.argc, diff --git a/src/vtbackend/Functions_test.cpp b/src/vtbackend/Functions_test.cpp index ba87346c23..f54e6289e7 100644 --- a/src/vtbackend/Functions_test.cpp +++ b/src/vtbackend/Functions_test.cpp @@ -1,16 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include - #include +#include + namespace vtbackend { // purely for proper diagnostic printing in Catch2 inline std::ostream& operator<<(std::ostream& os, Function const& f) { - return os << fmt::format("{}", f); + return os << std::format("{}", f); } } // namespace vtbackend diff --git a/src/vtbackend/Grid.cpp b/src/vtbackend/Grid.cpp index 06997fc780..a4907304db 100644 --- a/src/vtbackend/Grid.cpp +++ b/src/vtbackend/Grid.cpp @@ -5,9 +5,8 @@ #include #include -#include - #include +#include #include using std::max; @@ -750,13 +749,13 @@ CellLocation Grid::resize(PageSize newSize, CellLocation currentCursorPos, for (int i = -*historyLineCount(); i < *_pageSize.lines; ++i) { auto& line = _lines[i]; - // logLogicalLine(line.flags(), fmt::format("Line[{:>2}]: next line: \"{}\"", i, + // logLogicalLine(line.flags(), std::format("Line[{:>2}]: next line: \"{}\"", i, // line.toUtf8())); Require(line.size() >= _pageSize.columns); if (line.wrapped()) { - // logLogicalLine(line.flags(), fmt::format(" - appending: \"{}\"", + // logLogicalLine(line.flags(), std::format(" - appending: \"{}\"", // line.toUtf8Trimmed())); appendToLogicalLine(line.trim_blank_right()); } @@ -993,7 +992,7 @@ void Grid::appendNewLines(LineCount count, GraphicsAttributes attr) template std::ostream& dumpGrid(std::ostream& os, Grid const& grid) { - os << fmt::format( + os << std::format( "main page lines: scrollback cur {} max {}, main page lines {}, used lines {}, zero index {}\n", grid.historyLineCount(), grid.maxHistoryLineCount(), @@ -1006,7 +1005,7 @@ std::ostream& dumpGrid(std::ostream& os, Grid const& grid) { vtbackend::Line const& lineAttribs = grid.lineAt(LineOffset(lineOffset)); - os << fmt::format("[{:>2}] \"{}\" | {}\n", + os << std::format("[{:>2}] \"{}\" | {}\n", lineOffset, grid.lineText(LineOffset::cast_from(lineOffset)), lineAttribs.flags()); diff --git a/src/vtbackend/Grid.h b/src/vtbackend/Grid.h index 3127b44368..52b2fb8625 100644 --- a/src/vtbackend/Grid.h +++ b/src/vtbackend/Grid.h @@ -911,22 +911,20 @@ template // {{{ fmt formatter template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(const vtbackend::Margin::Horizontal range, - format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::Margin::Horizontal range, auto& ctx) const { - return formatter::format(fmt::format("{}..{}", range.from, range.to), ctx); + return formatter::format(std::format("{}..{}", range.from, range.to), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(const vtbackend::Margin::Vertical range, - format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::Margin::Vertical range, auto& ctx) const { - return formatter::format(fmt::format("{}..{}", range.from, range.to), ctx); + return formatter::format(std::format("{}..{}", range.from, range.to), ctx); } }; diff --git a/src/vtbackend/Grid_test.cpp b/src/vtbackend/Grid_test.cpp index 2a9d0386d9..ac304997d9 100644 --- a/src/vtbackend/Grid_test.cpp +++ b/src/vtbackend/Grid_test.cpp @@ -5,10 +5,10 @@ #include -#include - #include +#include + using namespace vtbackend; using namespace std::string_literals; using namespace std::string_view_literals; @@ -22,7 +22,7 @@ namespace { void logGridText(Grid const& grid, string const& headline = "") { - UNSCOPED_INFO(fmt::format("Grid.dump(hist {}, max hist {}, size {}, ZI {}): {}", + UNSCOPED_INFO(std::format("Grid.dump(hist {}, max hist {}, size {}, ZI {}): {}", grid.historyLineCount(), grid.maxHistoryLineCount(), grid.pageSize(), @@ -32,7 +32,7 @@ void logGridText(Grid const& grid, string const& headline = "") for (int line = -grid.historyLineCount().as(); line < grid.pageSize().lines.as(); ++line) { UNSCOPED_INFO( - fmt::format("{:>2}: \"{}\" {}\n", + std::format("{:>2}: \"{}\" {}\n", line, grid.lineText(LineOffset::cast_from(line - grid.historyLineCount().as())), grid.lineAt(LineOffset::cast_from(line)).flags())); @@ -41,13 +41,13 @@ void logGridText(Grid const& grid, string const& headline = "") [[maybe_unused]] void logGridTextAlways(Grid const& grid, string const& headline = "") { - fmt::print("Grid.dump(hist {}, max hist {}, size {}, ZI {}): {}\n", - grid.historyLineCount(), - grid.maxHistoryLineCount(), - grid.pageSize(), - grid.zero_index(), - headline); - fmt::print("{}\n", dumpGrid(grid)); + std::cout << std::format("Grid.dump(hist {}, max hist {}, size {}, ZI {}): {}\n", + grid.historyLineCount(), + grid.maxHistoryLineCount(), + grid.pageSize(), + grid.zero_index(), + headline); + std::cout << std::format("{}\n", dumpGrid(grid)); } Grid setupGrid(PageSize pageSize, @@ -68,7 +68,7 @@ Grid setupGrid(PageSize pageSize, grid.setLineText(LineOffset::cast_from(cursor - 1), line); logGridText(grid, - fmt::format("setup grid at {}x{}x{}: line {}", + std::format("setup grid at {}x{}x{}: line {}", pageSize.columns, pageSize.lines, maxHistoryLineCount, @@ -76,7 +76,7 @@ Grid setupGrid(PageSize pageSize, } logGridText(grid, - fmt::format("setup grid at {}x{}x{}", + std::format("setup grid at {}x{}x{}", grid.pageSize().columns, grid.pageSize().lines, grid.maxHistoryLineCount())); @@ -529,7 +529,7 @@ TEST_CASE("resize_reflow_shrink", "[grid]") CHECK(grid.lineText(LineOffset(0)) == "abcd"); CHECK(grid.lineText(LineOffset(1)) == "e "); - // fmt::print("Starting logicalLines test\n"); + // std::cout << std::format("Starting logicalLines test\n"); auto ll = grid.logicalLines(); auto li = ll.begin(); auto le = ll.end(); @@ -540,7 +540,7 @@ TEST_CASE("resize_reflow_shrink", "[grid]") CHECK(li == le); // 3x2 - fmt::print("Starting resize to 3x2\n"); + std::cout << std::format("Starting resize to 3x2\n"); (void) grid.resize(PageSize { LineCount(2), ColumnCount(3) }, CellLocation { {}, {} }, false); logGridText(grid, "after resize 3x2"); diff --git a/src/vtbackend/Image.cpp b/src/vtbackend/Image.cpp index 024dcc1039..d388a23d08 100644 --- a/src/vtbackend/Image.cpp +++ b/src/vtbackend/Image.cpp @@ -65,7 +65,7 @@ Image::Data RasterizedImage::fragment(CellLocation pos) const min(unbox(_image->height()) - unbox(pixelOffset.line), unbox(_cellSize.height)); // auto const availableSize = Size{availableWidth, availableHeight}; - // std::cout << fmt::format( + // std::cout << std::format( // "RasterizedImage.fragment({}): pixelOffset={}, cellSize={}/{}\n", // pos, // pixelOffset, @@ -76,7 +76,7 @@ Image::Data RasterizedImage::fragment(CellLocation pos) const // auto const fitsWidth = pixelOffset.column + _cellSize.width < _image.get().width(); // auto const fitsHeight = pixelOffset.line + _cellSize.height < _image.get().height(); // if (!fitsWidth || !fitsHeight) - // std::cout << fmt::format("ImageFragment: out of bounds{}{} ({}x{}); {}\n", + // std::cout << std::format("ImageFragment: out of bounds{}{} ({}x{}); {}\n", // fitsWidth ? "" : " (width)", // fitsHeight ? "" : " (height)", // availableWidth, @@ -161,7 +161,7 @@ void ImagePool::clear() void ImagePool::inspect(ostream& os) const { os << "Image pool:\n"; - os << fmt::format("global image stats: {}\n", ImageStats::get()); + os << std::format("global image stats: {}\n", ImageStats::get()); _imageNameToImageCache.inspect(os); } diff --git a/src/vtbackend/Image.h b/src/vtbackend/Image.h index ecc15c611f..dcb2e15b4f 100644 --- a/src/vtbackend/Image.h +++ b/src/vtbackend/Image.h @@ -7,9 +7,8 @@ #include #include -#include - #include +#include #include #include #include @@ -260,9 +259,9 @@ class ImagePool // {{{ fmtlib support template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::ImageFormat value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ImageFormat value, auto& ctx) const { string_view name; switch (value) @@ -275,22 +274,21 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::ImageStats stats, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ImageStats stats, auto& ctx) const { return formatter::format( - fmt::format( + std::format( "{} instances, {} raster, {} fragments", stats.instances, stats.rasterized, stats.fragments), ctx); } }; template <> -struct fmt::formatter>: fmt::formatter +struct std::formatter>: std::formatter { - auto format(std::shared_ptr const& image, - format_context& ctx) const -> format_context::iterator + auto format(std::shared_ptr const& image, auto& ctx) const { std::string text; if (!image) @@ -298,19 +296,20 @@ struct fmt::formatter>: fmt::formatter", + text = std::format("Image<#{}, {}, size={}x{}>", imageRef.weak_from_this().use_count(), imageRef.id(), - imageRef.size()); + imageRef.size().width.value, + imageRef.size().height.value); } return formatter::format(text, ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::ImageResize value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ImageResize value, auto& ctx) const { string_view name; switch (value) @@ -325,9 +324,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::ImageAlignment value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ImageAlignment value, auto& ctx) const { string_view name; switch (value) @@ -347,29 +346,31 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::RasterizedImage const& image, - format_context& ctx) const -> format_context::iterator + auto format(vtbackend::RasterizedImage const& image, auto& ctx) const { - return formatter::format(fmt::format("RasterizedImage<{}, {}, {}, {}, {}>", + return formatter::format(std::format("RasterizedImage<{}, {}, {}, {}, {}>", image.weak_from_this().use_count(), image.cellSpan(), image.resizePolicy(), image.alignmentPolicy(), - image.imagePointer()), + image.imagePointer()->id().value), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(const vtbackend::ImageFragment& fragment, - format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::ImageFragment& fragment, auto& ctx) const { return formatter::format( - fmt::format("ImageFragment", fragment.offset(), fragment.rasterizedImage()), ctx); + std::format("ImageFragment", + fragment.offset().line.value, + fragment.offset().column.value, + fragment.rasterizedImage().imagePointer()->id().value), + ctx); } }; // }}} diff --git a/src/vtbackend/InputBinding.h b/src/vtbackend/InputBinding.h index 93fb7ea60e..8597a3d345 100644 --- a/src/vtbackend/InputBinding.h +++ b/src/vtbackend/InputBinding.h @@ -4,7 +4,7 @@ #include #include -#include +#include namespace vtbackend { @@ -58,12 +58,11 @@ bool operator<(InputBinding const& a, InputBinding const& b) noexcep } // namespace vtbackend template -struct fmt::formatter> +struct std::formatter> { - static auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } - static auto format(vtbackend::InputBinding const& binding, - format_context& ctx) -> format_context::iterator + auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } + auto format(vtbackend::InputBinding const& binding, auto& ctx) const { - return fmt::format_to(ctx.out(), "{} {} {}", binding.modes, binding.modifiers, binding.input); + return std::format_to(ctx.out(), "{} {} {}", binding.modes, binding.modifiers, binding.input); } }; diff --git a/src/vtbackend/InputGenerator.cpp b/src/vtbackend/InputGenerator.cpp index fe3fd7ea62..56f153c914 100644 --- a/src/vtbackend/InputGenerator.cpp +++ b/src/vtbackend/InputGenerator.cpp @@ -8,9 +8,8 @@ #include -#include - #include +#include #include #include #include @@ -26,17 +25,17 @@ namespace vtbackend string to_string(Modifiers modifiers) { - return fmt::format("{}", modifiers); + return std::format("{}", modifiers); } string to_string(Key key) { - return fmt::format("{}", key); + return std::format("{}", key); } string to_string(MouseButton button) { - return fmt::format("{}", button); + return std::format("{}", button); } // {{{ StandardKeyboardInputGenerator @@ -279,7 +278,7 @@ std::string ExtendedKeyboardInputGenerator::encodeModifiers(Modifiers modifiers, KeyboardEventType eventType) const { if (enabled(KeyboardEventFlag::ReportEventTypes)) - return fmt::format("{}:{}", modifiers.value(), encodeEventType(eventType)); + return std::format("{}:{}", modifiers.value(), encodeEventType(eventType)); if (modifiers.value() != 0) return std::to_string(1 + modifiers.value()); @@ -293,7 +292,7 @@ std::string ExtendedKeyboardInputGenerator::encodeCharacter(char32_t ch, { // The codepoint is always the lower-case form // TODO: use libunicode for down-shifting - auto unshiftedKey = ch < 0x80 ? fmt::format("{}", std::tolower(static_cast(ch))) : ""s; + auto unshiftedKey = ch < 0x80 ? std::format("{}", std::tolower(static_cast(ch))) : ""s; auto result = std::move(unshiftedKey); @@ -496,9 +495,9 @@ bool ExtendedKeyboardInputGenerator::generateKey(Key key, Modifiers modifiers, K auto const [code, function] = mapKey(key); auto const encodedModifiers = encodeModifiers(modifiers, eventType); - auto controlSequence = fmt::format("\033[{}", code); + auto controlSequence = std::format("\033[{}", code); if (!encodedModifiers.empty()) - controlSequence += fmt::format(";{}", encodedModifiers); + controlSequence += std::format(";{}", encodedModifiers); controlSequence += function; append(controlSequence); @@ -719,7 +718,7 @@ bool InputGenerator::generateMouse(MouseEventType eventType, if (!_mouseProtocol.has_value()) return false; - // std::cout << fmt::format("generateMouse({}/{}): button:{}, modifier:{}, at:{}, type:{}\n", + // std::cout << std::format("generateMouse({}/{}): button:{}, modifier:{}, at:{}, type:{}\n", // _mouseTransport, *_mouseProtocol, // button, modifier, pos, eventType); diff --git a/src/vtbackend/InputGenerator.h b/src/vtbackend/InputGenerator.h index 787af9eed0..0c5016c0c3 100644 --- a/src/vtbackend/InputGenerator.h +++ b/src/vtbackend/InputGenerator.h @@ -9,8 +9,7 @@ #include -#include - +#include #include #include #include @@ -286,9 +285,9 @@ class StandardKeyboardInputGenerator: public KeyboardInputGenerator void append(std::string_view sequence) { _pendingSequence += sequence; } template - void append(fmt::format_string const& text, Args... args) + void append(std::string_view const& text, Args... args) { - append(fmt::vformat(text, fmt::make_format_args(args...))); + append(std::vformat(text, std::make_format_args(args...))); } KeyMode _cursorKeysMode = KeyMode::Normal; @@ -552,9 +551,9 @@ inline std::string to_string(InputGenerator::MouseEventType value) // {{{ fmtlib custom formatter support template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::KeyboardEventType value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::KeyboardEventType value, auto& ctx) const { string_view name; switch (value) @@ -568,9 +567,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::KeyboardEventFlag value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::KeyboardEventFlag value, auto& ctx) const { string_view name; switch (value) @@ -589,9 +588,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::MouseProtocol value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::MouseProtocol value, auto& ctx) const { string_view name; switch (value) @@ -607,9 +606,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::Modifier value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::Modifier value, auto& ctx) const { std::string_view name; switch (value) @@ -629,10 +628,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::InputGenerator::MouseWheelMode value, - format_context& ctx) const -> format_context::iterator + auto format(vtbackend::InputGenerator::MouseWheelMode value, auto& ctx) const { string_view name; switch (value) @@ -650,9 +648,9 @@ struct fmt::formatter: formatter -struct fmt::formatter: public formatter +struct std::formatter: public formatter { - auto format(vtbackend::KeyMode value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::KeyMode value, auto& ctx) const { string_view name; switch (value) @@ -665,9 +663,9 @@ struct fmt::formatter: public formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::MouseButton value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::MouseButton value, auto& ctx) const { string_view name; switch (value) @@ -686,9 +684,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::MouseTransport value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::MouseTransport value, auto& ctx) const { string_view name; switch (value) @@ -704,9 +702,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::Key value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::Key value, auto& ctx) const { string_view name; switch (value) diff --git a/src/vtbackend/InputGenerator_test.cpp b/src/vtbackend/InputGenerator_test.cpp index e6a997ec20..e64491e8fd 100644 --- a/src/vtbackend/InputGenerator_test.cpp +++ b/src/vtbackend/InputGenerator_test.cpp @@ -166,7 +166,7 @@ TEST_CASE("InputGenerator.Modifier+ArrowKeys", "[terminal,input]") { auto input = InputGenerator {}; input.generate(mapping.key, mapping.modifiers, KeyboardEventType::Press); - INFO(fmt::format("Testing {}+{} => {}", mapping.modifiers, mapping.key, escape(mapping.expected))); + INFO(std::format("Testing {}+{} => {}", mapping.modifiers, mapping.key, escape(mapping.expected))); REQUIRE(escape(input.peek()) == escape(mapping.expected)); } } @@ -175,7 +175,7 @@ TEST_CASE("InputGenerator.all(Ctrl + A..Z)", "[terminal,input]") { for (char ch = 'A'; ch <= 'Z'; ++ch) { - INFO(fmt::format("Testing Ctrl+{}", ch)); + INFO(std::format("Testing Ctrl+{}", ch)); auto input = InputGenerator {}; input.generate(static_cast(ch), Modifier::Control, KeyboardEventType::Press); auto const c0 = string(1, static_cast(ch - 'A' + 1)); diff --git a/src/vtbackend/Line.cpp b/src/vtbackend/Line.cpp index b1fb8f73f8..33b1a0a4c8 100644 --- a/src/vtbackend/Line.cpp +++ b/src/vtbackend/Line.cpp @@ -58,7 +58,7 @@ typename Line::InflatedBuffer Line::reflow(ColumnCount newColumnCoun #if 0 if (removedColumns.size() > 0 && std::ranges::any_of(removedColumns, [](Cell const& x) { if (!x.empty()) - fmt::print("non-empty cell in reflow: {}\n", x.toUtf8()); + std::cout << std::format("non-empty cell in reflow: {}\n", x.toUtf8()); return !x.empty(); })) printf("Wrapping around\n"); diff --git a/src/vtbackend/Line.h b/src/vtbackend/Line.h index 7343b39a64..bef7af8c98 100644 --- a/src/vtbackend/Line.h +++ b/src/vtbackend/Line.h @@ -463,9 +463,9 @@ inline typename Line::InflatedBuffer const& Line::inflatedBuffer() c } // namespace vtbackend template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(const vtbackend::LineFlags flags, format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::LineFlags flags, auto& ctx) const { static const std::array, 3> nameMap = { std::pair { vtbackend::LineFlag::Wrappable, std::string_view("Wrappable") }, diff --git a/src/vtbackend/Line_test.cpp b/src/vtbackend/Line_test.cpp index 5c82b0210b..60b1d2b620 100644 --- a/src/vtbackend/Line_test.cpp +++ b/src/vtbackend/Line_test.cpp @@ -100,7 +100,7 @@ TEST_CASE("Line.inflate", "[Line]") for (size_t i = 0; i < inflated.size(); ++i) { auto const& cell = inflated[i]; - INFO(fmt::format("column {} codepoint {}", i, (char) cell.codepoint(0))); + INFO(std::format("column {} codepoint {}", i, (char) cell.codepoint(0))); CHECK(cell.foregroundColor() == sgr.foregroundColor); CHECK(cell.backgroundColor() == sgr.backgroundColor); CHECK(cell.underlineColor() == sgr.underlineColor); @@ -136,7 +136,7 @@ TEST_CASE("Line.inflate.Unicode", "[Line]") for (size_t i = 0, k = 0; i < inflated.size();) { auto const& cell = inflated[i]; - INFO(fmt::format("column {}, k {}, codepoint U+{:X}", i, k, (unsigned) cell.codepoint(0))); + INFO(std::format("column {}, k {}, codepoint U+{:X}", i, k, (unsigned) cell.codepoint(0))); REQUIRE(cell.codepointCount() == 1); REQUIRE(cell.codepoint(0) == TestTextUtf32[k]); REQUIRE(cell.foregroundColor() == sgr.foregroundColor); @@ -144,7 +144,7 @@ TEST_CASE("Line.inflate.Unicode", "[Line]") REQUIRE(cell.underlineColor() == sgr.underlineColor); for (int n = 1; n < cell.width(); ++n) { - INFO(fmt::format("column.sub: {}\n", n)); + INFO(std::format("column.sub: {}\n", n)); auto const& fillCell = inflated.at(i + static_cast(n)); REQUIRE(fillCell.codepointCount() == 0); REQUIRE(fillCell.foregroundColor() == sgr.foregroundColor); diff --git a/src/vtbackend/Logger.h b/src/vtbackend/Logger.h index c731a4465e..a32da74acb 100644 --- a/src/vtbackend/Logger.h +++ b/src/vtbackend/Logger.h @@ -2,8 +2,7 @@ #include -#include - +#include #include #include #include @@ -60,34 +59,34 @@ using Logger = std::function; } // namespace vtbackend template <> -struct fmt::formatter +struct std::formatter { - static auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } - static auto format(const vtbackend::LogEvent& ev, format_context& ctx) -> format_context::iterator + auto parse(format_parse_context& ctx) -> format_parse_context::iterator { return ctx.begin(); } + auto format(const vtbackend::LogEvent& ev, auto& ctx) const { using namespace vtbackend; return std::visit( overloaded { [&](ParserErrorEvent const& v) { - return fmt::format_to(ctx.out(), "Parser Error. {}", v.reason); + return std::format_to(ctx.out(), "Parser Error. {}", v.reason); }, [&](TraceInputEvent const& v) { - return fmt::format_to(ctx.out(), "Trace Input: {}", v.message); + return std::format_to(ctx.out(), "Trace Input: {}", v.message); }, [&](RawInputEvent const& v) { - return fmt::format_to(ctx.out(), "Raw Input: \"{}\"", v.sequence); + return std::format_to(ctx.out(), "Raw Input: \"{}\"", v.sequence); }, [&](RawOutputEvent const& v) { - return fmt::format_to(ctx.out(), "Raw Output: \"{}\"", v.sequence); + return std::format_to(ctx.out(), "Raw Output: \"{}\"", v.sequence); }, [&](InvalidOutputEvent const& v) { - return fmt::format_to(ctx.out(), "Invalid output sequence: {}. {}", v.sequence, v.reason); + return std::format_to(ctx.out(), "Invalid output sequence: {}. {}", v.sequence, v.reason); }, [&](UnsupportedOutputEvent const& v) { - return fmt::format_to(ctx.out(), "Unsupported output sequence: {}.", v.sequence); + return std::format_to(ctx.out(), "Unsupported output sequence: {}.", v.sequence); }, [&](TraceOutputEvent const& v) { - return fmt::format_to(ctx.out(), "Trace output sequence: {}", v.sequence); + return std::format_to(ctx.out(), "Trace output sequence: {}", v.sequence); }, }, ev); diff --git a/src/vtbackend/MatchModes.h b/src/vtbackend/MatchModes.h index 588356a12a..4018430a97 100644 --- a/src/vtbackend/MatchModes.h +++ b/src/vtbackend/MatchModes.h @@ -1,9 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once -#include - #include +#include namespace vtbackend { @@ -108,9 +107,9 @@ constexpr bool operator!=(MatchModes a, MatchModes b) noexcept // {{{ fmtlib support template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::MatchModes m, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::MatchModes m, auto& ctx) const { std::string s; auto const advance = [&](vtbackend::MatchModes::Flag cond, std::string_view text) { diff --git a/src/vtbackend/RenderBuffer.cpp b/src/vtbackend/RenderBuffer.cpp index dc07aff937..d858c748c2 100644 --- a/src/vtbackend/RenderBuffer.cpp +++ b/src/vtbackend/RenderBuffer.cpp @@ -1,8 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include - +#include #include namespace vtbackend diff --git a/src/vtbackend/RenderBufferBuilder.cpp b/src/vtbackend/RenderBufferBuilder.cpp index cfa1958aa7..9331f82020 100644 --- a/src/vtbackend/RenderBufferBuilder.cpp +++ b/src/vtbackend/RenderBufferBuilder.cpp @@ -323,7 +323,7 @@ template void RenderBufferBuilder::renderTrivialLine(TrivialLineBuffer const& lineBuffer, LineOffset lineOffset) { // if (lineBuffer.text.size()) - // fmt::print("Rendering trivial line {:2} 0..{}/{} ({} bytes): \"{}\"\n", + // std::cout << std::format("Rendering trivial line {:2} 0..{}/{} ({} bytes): \"{}\"\n", // lineOffset.value, // lineBuffer.usedColumns, // lineBuffer.displayWidth, @@ -515,7 +515,7 @@ ColumnCount RenderBufferBuilder::renderUtf8Text(CellLocation screenPositio textAttributes.foregroundColor, textAttributes.backgroundColor); auto const width = graphemeClusterWidth(graphemeCluster); - // fmt::print(" start {}, count {}, bytes {}, grapheme cluster \"{}\"\n", + // std::cout << std::format(" start {}, count {}, bytes {}, grapheme cluster \"{}\"\n", // columnOffset, // width, // unicode::convert_to(u32string_view(graphemeCluster)).size(), diff --git a/src/vtbackend/Screen.cpp b/src/vtbackend/Screen.cpp index 662b79c665..d085dbaa47 100644 --- a/src/vtbackend/Screen.cpp +++ b/src/vtbackend/Screen.cpp @@ -308,7 +308,7 @@ void Screen::verifyState() const [[maybe_unused]] auto const clampedCursorPos = clampToScreen(_cursor.position); if (_cursor.position != clampedCursorPos) { - fail(fmt::format("Cursor {} does not match clamp to screen {}.", _cursor.position, clampedCursorPos)); + fail(std::format("Cursor {} does not match clamp to screen {}.", _cursor.position, clampedCursorPos)); // FIXME: the above triggers on tmux vertical screen split (cursor.column off-by-one) } @@ -2014,7 +2014,7 @@ void Screen::requestStatusString(RequestStatusString value) auto const c1TransmittionMode = ControlTransmissionMode::S7C1T; auto const c1t = c1TransmittionMode == ControlTransmissionMode::S7C1T ? 1 : 0; - return fmt::format("{};{}\"p", level, c1t); + return std::format("{};{}\"p", level, c1t); } case RequestStatusString::DECSCUSR: // Set cursor style (DECSCUSR), VT520 { @@ -2029,28 +2029,28 @@ void Screen::requestStatusString(RequestStatusString value) } return 1; }(); - return fmt::format("{} q", shape + blinkingOrSteady); + return std::format("{} q", shape + blinkingOrSteady); } case RequestStatusString::DECSLPP: // Ps >= 2 4 -> Resize to Ps lines (DECSLPP), VT340 and VT420. // xterm adapts this by resizing its window. if (*pageSize().lines >= 24) - return fmt::format("{}t", pageSize().lines); + return std::format("{}t", pageSize().lines); errorLog()("Requesting device status for {} not with line count < 24 is undefined."); return nullopt; case RequestStatusString::DECSTBM: - return fmt::format("{};{}r", 1 + *margin().vertical.from, *margin().vertical.to); + return std::format("{};{}r", 1 + *margin().vertical.from, *margin().vertical.to); case RequestStatusString::DECSLRM: - return fmt::format("{};{}s", 1 + *margin().horizontal.from, *margin().horizontal.to); + return std::format("{};{}s", 1 + *margin().horizontal.from, *margin().horizontal.to); case RequestStatusString::DECSCPP: // EXTENSION: Usually DECSCPP only knows about 80 and 132, but we take any. - return fmt::format("{}|$", pageSize().columns); - case RequestStatusString::DECSNLS: return fmt::format("{}*|", pageSize().lines); + return std::format("{}|$", pageSize().columns); + case RequestStatusString::DECSNLS: return std::format("{}*|", pageSize().lines); case RequestStatusString::SGR: - return fmt::format("0;{}m", vtSequenceParameterString(_cursor.graphicsRendition)); + return std::format("0;{}m", vtSequenceParameterString(_cursor.graphicsRendition)); case RequestStatusString::DECSCA: { auto const isProtected = _cursor.graphicsRendition.flags & CellFlag::CharacterProtected; - return fmt::format("{}\"q", isProtected ? 1 : 2); + return std::format("{}\"q", isProtected ? 1 : 2); } case RequestStatusString::DECSASD: switch (_terminal->activeStatusDisplay()) @@ -2107,7 +2107,7 @@ namespace { std::string output; for (char const ch: value) - output += fmt::format("{:02X}", unsigned(ch)); + output += std::format("{:02X}", unsigned(ch)); return output; } } // namespace @@ -2119,7 +2119,7 @@ void Screen::requestCapability(std::string_view name) reply("\033P1+r{}\033\\", toHexString(name)); else if (auto const value = numericCapability(name); value != Database::Npos) { - auto hexValue = fmt::format("{:X}", value); + auto hexValue = std::format("{:X}", value); if (hexValue.size() % 2) hexValue.insert(hexValue.begin(), '0'); reply("\033P1+r{}={}\033\\", toHexString(name), hexValue); @@ -2137,7 +2137,7 @@ void Screen::requestCapability(capabilities::Code code) reply("\033P1+r{}\033\\", code.hex()); else if (auto const value = numericCapability(code); value >= 0) { - auto hexValue = fmt::format("{:X}", value); + auto hexValue = std::format("{:X}", value); if (hexValue.size() % 2) hexValue.insert(hexValue.begin(), '0'); reply("\033P1+r{}={}\033\\", code.hex(), hexValue); @@ -2217,7 +2217,7 @@ void Screen::inspect(std::string const& message, std::ostream& os) const }; auto const gridInfoLine = [&](Grid const& grid) { - return fmt::format("main page lines: scrollback cur {} max {}, main page lines {}, used lines " + return std::format("main page lines: scrollback cur {} max {}, main page lines {}, used lines " "{}, zero index {}\n", grid.historyLineCount(), grid.maxHistoryLineCount(), @@ -2233,20 +2233,20 @@ void Screen::inspect(std::string const& message, std::ostream& os) const hline(); } - os << fmt::format("Rendered screen at the time of failure\n"); - os << fmt::format("main page size : {}\n", _settings->pageSize); - os << fmt::format("history line count : {} (max {})\n", + os << std::format("Rendered screen at the time of failure\n"); + os << std::format("main page size : {}\n", _settings->pageSize); + os << std::format("history line count : {} (max {})\n", _terminal->primaryScreen().historyLineCount(), _terminal->maxHistoryLineCount()); - os << fmt::format("cursor position : {}\n", _cursor.position); - os << fmt::format("vertical margins : {}\n", margin().vertical); - os << fmt::format("horizontal margins : {}\n", margin().horizontal); + os << std::format("cursor position : {}\n", _cursor.position); + os << std::format("vertical margins : {}\n", margin().vertical); + os << std::format("horizontal margins : {}\n", margin().horizontal); os << gridInfoLine(grid()); hline(); os << screenshot([this](LineOffset lineNo) -> string { // auto const absoluteLine = _grid.toAbsoluteLine(lineNo); - return fmt::format("{} {:>4}: {}", + return std::format("{} {:>4}: {}", _grid.lineAt(lineNo).isTrivialBuffer() ? "|" : ":", lineNo.value, _grid.lineAt(lineNo).flags()); @@ -3264,7 +3264,7 @@ void Screen::processSequence(Sequence const& seq) } #endif - // std::cerr << fmt::format("\t{} \t; {}\n", seq, + // std::cerr << std::format("\t{} \t; {}\n", seq, // seq.functionDefinition() ? seq.functionDefinition()->comment : ""sv); _terminal->incrementInstructionCounter(); diff --git a/src/vtbackend/Screen.h b/src/vtbackend/Screen.h index 728bb0265a..08ebaa6a9d 100644 --- a/src/vtbackend/Screen.h +++ b/src/vtbackend/Screen.h @@ -22,12 +22,11 @@ #include #include -#include - #include #include #include +#include #include #include #include @@ -110,7 +109,7 @@ inline std::string setDynamicColorValue( auto const r = static_cast(static_cast(color.red) / 255.0f * 0xFFFF); auto const g = static_cast(static_cast(color.green) / 255.0f * 0xFFFF); auto const b = static_cast(static_cast(color.blue) / 255.0f * 0xFFFF); - return fmt::format("rgb:{:04X}/{:04X}/{:04X}", r, g, b); + return std::format("rgb:{:04X}/{:04X}/{:04X}", r, g, b); } enum class ApplyResult : uint8_t @@ -598,9 +597,9 @@ class Screen final: public ScreenBase, public capabilities::StaticDatabase void reply(std::string_view text); template - void reply(fmt::format_string message, Ts const&... args) + void reply(std::string_view message, Ts const&... args) { - reply(fmt::vformat(message, fmt::make_format_args(args...))); + reply(std::vformat(message, std::make_format_args(args...))); } private: @@ -683,10 +682,9 @@ inline bool Screen::isContiguousToCurrentLine(std::string_view continuatio // {{{ fmt formatter template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::RequestStatusString value, - format_context& ctx) const noexcept -> format_context::iterator + auto format(vtbackend::RequestStatusString value, auto& ctx) const { string_view name; switch (value) @@ -708,7 +706,7 @@ struct fmt::formatter: formatter -struct fmt::formatter +struct std::formatter { template constexpr auto parse(ParseContext& ctx) @@ -718,7 +716,7 @@ struct fmt::formatter template auto format(vtbackend::Sequence const& seq, FormatContext& ctx) const { - return fmt::format_to(ctx.out(), "{}", seq.text()); + return std::format_to(ctx.out(), "{}", seq.text()); } }; // }}} diff --git a/src/vtbackend/Screen_test.cpp b/src/vtbackend/Screen_test.cpp index ea582de959..81341da883 100644 --- a/src/vtbackend/Screen_test.cpp +++ b/src/vtbackend/Screen_test.cpp @@ -718,14 +718,14 @@ TEST_CASE("Linefeed", "[screen]") SECTION("with scroll-up") { INFO("init:"); - INFO(fmt::format(" line 1: '{}'", screen.grid().lineText(LineOffset(0)))); - INFO(fmt::format(" line 2: '{}'", screen.grid().lineText(LineOffset(1)))); + INFO(std::format(" line 1: '{}'", screen.grid().lineText(LineOffset(0)))); + INFO(std::format(" line 2: '{}'", screen.grid().lineText(LineOffset(1)))); mock.writeToScreen("1\r\n2"); INFO("after writing '1\\n2':"); - INFO(fmt::format(" line 1: '{}'", screen.grid().lineText(LineOffset(0)))); - INFO(fmt::format(" line 2: '{}'", screen.grid().lineText(LineOffset(1)))); + INFO(std::format(" line 1: '{}'", screen.grid().lineText(LineOffset(0)))); + INFO(std::format(" line 2: '{}'", screen.grid().lineText(LineOffset(1)))); REQUIRE("1 " == screen.grid().lineText(LineOffset(0))); REQUIRE("2 " == screen.grid().lineText(LineOffset(1))); @@ -733,8 +733,8 @@ TEST_CASE("Linefeed", "[screen]") mock.writeToScreen("\r\n3"); // line 3 INFO("After writing '\\n3':"); - INFO(fmt::format(" line 1: '{}'", screen.grid().lineText(LineOffset(0)))); - INFO(fmt::format(" line 2: '{}'", screen.grid().lineText(LineOffset(1)))); + INFO(std::format(" line 1: '{}'", screen.grid().lineText(LineOffset(0)))); + INFO(std::format(" line 2: '{}'", screen.grid().lineText(LineOffset(1)))); REQUIRE("2 " == screen.grid().lineText(LineOffset(0))); REQUIRE("3 " == screen.grid().lineText(LineOffset(1))); @@ -1158,14 +1158,13 @@ TEST_CASE("DECSEL-0", "[screen]") // Erasing from the cursor position forwards to the end of the current line. for (auto const param: { "0"sv, ""sv }) { - INFO(fmt::format("param: \"{}\"", param)); + INFO(std::format("param: \"{}\"", param)); auto mock = MockTerm { PageSize { LineCount(2), ColumnCount(6) } }; auto& screen = mock.terminal.primaryScreen(); - mock.writeToScreen( - fmt::format("AB{on}CDE{off}F", fmt::arg("on", "\033[1\"q"), fmt::arg("off", "\033[2\"q"))); + mock.writeToScreen(std::format("AB{}CDE{}F", "\033[1\"q", "\033[2\"q")); REQUIRE("ABCDEF" == screen.grid().lineText(LineOffset(0))); mock.writeToScreen("\033[1;2H"); - mock.writeToScreen(fmt::format("\033[?{}K", param)); + mock.writeToScreen(std::format("\033[?{}K", param)); REQUIRE("A CDE " == screen.grid().lineText(LineOffset(0))); } } @@ -1175,8 +1174,7 @@ TEST_CASE("DECSEL-1", "[screen]") // Erasing from the cursor position backwards to the beginning of the current line. auto mock = MockTerm { PageSize { LineCount(2), ColumnCount(6) } }; auto& screen = mock.terminal.primaryScreen(); - mock.writeToScreen( - fmt::format("A{on}BCD{off}EF", fmt::arg("on", "\033[1\"q"), fmt::arg("off", "\033[2\"q"))); + mock.writeToScreen(std::format("A{}BCD{}EF", "\033[1\"q", "\033[2\"q")); REQUIRE("ABCDEF" == screen.grid().lineText(LineOffset(0))); mock.writeToScreen("\033[1;5H"); @@ -1191,15 +1189,13 @@ TEST_CASE("DECSEL-2", "[screen]") mock.writeToScreen("ABCD"); REQUIRE("ABCD" == screen.grid().lineText(LineOffset(0))); - mock.writeToScreen( - fmt::format("\ra{on}bc{off}d\r", fmt::arg("on", "\033[1\"q"), fmt::arg("off", "\033[2\"q"))); + mock.writeToScreen(std::format("\ra{}bc{}d\r", "\033[1\"q", "\033[2\"q")); REQUIRE("abcd" == screen.grid().lineText(LineOffset(0))); mock.writeToScreen("\033[?2K"); REQUIRE(" bc " == screen.grid().lineText(LineOffset(0))); - mock.writeToScreen(fmt::format( - "\r{on}A{off}BC{on}D", fmt::arg("on", "\033[1\"q"), fmt::arg("off", "\033[2\"q"))); // DECSCA 2 + mock.writeToScreen(std::format("\r{0}A{1}BC{0}D", "\033[1\"q", "\033[2\"q")); // DECSCA 2 REQUIRE("ABCD" == screen.grid().lineText(LineOffset(0))); mock.writeToScreen("\033[?2K"); REQUIRE("A D" == screen.grid().lineText(LineOffset(0))); @@ -1214,16 +1210,16 @@ TEST_CASE("DECSED-0", "[screen]") auto mock = MockTerm { PageSize { LineCount(3), ColumnCount(3) } }; auto& screen = mock.terminal.primaryScreen(); - mock.writeToScreen(fmt::format("{on}A{off}B{on}C{off}\r\n" - "D{on}E{off}F\r\n" - "{on}G{off}H{on}I{off}", - fmt::arg("on", "\033[1\"q"), - fmt::arg("off", "\033[2\"q"))); + mock.writeToScreen(std::format("{0}A{1}B{0}C{1}\r\n" + "D{0}E{1}F\r\n" + "{0}G{1}H{0}I{1}", + "\033[1\"q", + "\033[2\"q")); REQUIRE(e(mainPageText(screen)) == "ABC\\nDEF\\nGHI\\n"); mock.writeToScreen("\033[2;2H"); - mock.writeToScreen(fmt::format("\033[?{}J", param)); + mock.writeToScreen(std::format("\033[?{}J", param)); REQUIRE(e(mainPageText(screen)) == "ABC\\nDE \\nG I\\n"); } } @@ -1233,11 +1229,11 @@ TEST_CASE("DECSED-1", "[screen]") auto mock = MockTerm { PageSize { LineCount(3), ColumnCount(3) } }; auto& screen = mock.terminal.primaryScreen(); - mock.writeToScreen(fmt::format("{on}A{off}B{on}C{off}\r\n" - "D{on}E{off}F\r\n" - "{on}G{off}H{on}I{off}", - fmt::arg("on", "\033[1\"q"), - fmt::arg("off", "\033[2\"q"))); + mock.writeToScreen(std::format("{0}A{1}B{0}C{1}\r\n" + "D{0}E{1}F\r\n" + "{0}G{1}H{0}I{1}", + "\033[1\"q", + "\033[2\"q")); REQUIRE(e(mainPageText(screen)) == "ABC\\nDEF\\nGHI\\n"); @@ -1251,11 +1247,11 @@ TEST_CASE("DECSED-2", "[screen]") auto mock = MockTerm { PageSize { LineCount(3), ColumnCount(3) } }; auto& screen = mock.terminal.primaryScreen(); - mock.writeToScreen(fmt::format("{on}A{off}B{on}C{off}\r\n" - "D{on}E{off}F\r\n" - "{on}G{off}H{on}I{off}", - fmt::arg("on", "\033[1\"q"), - fmt::arg("off", "\033[2\"q"))); + mock.writeToScreen(std::format("{0}A{1}B{0}C{1}\r\n" + "D{0}E{1}F\r\n" + "{0}G{1}H{0}I{1}", + "\033[1\"q", + "\033[2\"q")); REQUIRE(e(mainPageText(screen)) == "ABC\\nDEF\\nGHI\\n"); @@ -1271,11 +1267,11 @@ TEST_CASE("DECSERA-all-defaults", "[screen]") auto mock = MockTerm { PageSize { LineCount(3), ColumnCount(3) } }; auto& screen = mock.terminal.primaryScreen(); - mock.writeToScreen(fmt::format("{on}A{off}B{on}C{off}\r\n" - "D{on}E{off}F\r\n" - "{on}G{off}H{on}I{off}", - fmt::arg("on", "\033[1\"q"), - fmt::arg("off", "\033[2\"q"))); + mock.writeToScreen(std::format("{0}A{1}B{0}C{1}\r\n" + "D{0}E{1}F\r\n" + "{0}G{1}H{0}I{1}", + "\033[1\"q", + "\033[2\"q")); REQUIRE(e(mainPageText(screen)) == "ABC\\nDEF\\nGHI\\n"); @@ -1288,11 +1284,11 @@ TEST_CASE("DECSERA", "[screen]") auto mock = MockTerm { PageSize { LineCount(3), ColumnCount(3) } }; auto& screen = mock.terminal.primaryScreen(); - mock.writeToScreen(fmt::format("{on}A{off}B{on}C{off}\r\n" - "D{on}E{off}F\r\n" - "{on}G{off}H{on}I{off}", - fmt::arg("on", "\033[1\"q"), - fmt::arg("off", "\033[2\"q"))); + mock.writeToScreen(std::format("{0}A{1}B{0}C{1}\r\n" + "D{0}E{1}F\r\n" + "{0}G{1}H{0}I{1}", + "\033[1\"q", + "\033[2\"q")); REQUIRE(e(mainPageText(screen)) == "ABC\\nDEF\\nGHI\\n"); @@ -2563,7 +2559,7 @@ TEST_CASE("RequestMode", "[screen]") mock.terminal.setMode(AnsiMode::Insert, true); // IRM screen.requestAnsiMode((unsigned) AnsiMode::Insert); REQUIRE(e(mock.terminal.peekInput()) - == e(fmt::format("\033[{};1$y", toAnsiModeNum(AnsiMode::Insert)))); + == e(std::format("\033[{};1$y", toAnsiModeNum(AnsiMode::Insert)))); } SECTION("ANSI modes: disabled") @@ -2571,7 +2567,7 @@ TEST_CASE("RequestMode", "[screen]") mock.terminal.setMode(AnsiMode::Insert, false); // IRM screen.requestAnsiMode((unsigned) AnsiMode::Insert); REQUIRE(e(mock.terminal.peekInput()) - == e(fmt::format("\033[{};2$y", toAnsiModeNum(AnsiMode::Insert)))); + == e(std::format("\033[{};2$y", toAnsiModeNum(AnsiMode::Insert)))); } SECTION("ANSI modes: unknown") @@ -2579,7 +2575,7 @@ TEST_CASE("RequestMode", "[screen]") auto const m = static_cast(1234); mock.terminal.setMode(m, true); // DECOM screen.requestAnsiMode((unsigned) m); - REQUIRE(e(mock.terminal.peekInput()) == e(fmt::format("\033[{};0$y", toAnsiModeNum(m)))); + REQUIRE(e(mock.terminal.peekInput()) == e(std::format("\033[{};0$y", toAnsiModeNum(m)))); } SECTION("DEC modes: enabled") @@ -2587,7 +2583,7 @@ TEST_CASE("RequestMode", "[screen]") mock.terminal.setMode(DECMode::Origin, true); // DECOM screen.requestDECMode((int) DECMode::Origin); REQUIRE(e(mock.terminal.peekInput()) - == e(fmt::format("\033[?{};1$y", toDECModeNum(DECMode::Origin)))); + == e(std::format("\033[?{};1$y", toDECModeNum(DECMode::Origin)))); } SECTION("DEC modes: disabled") @@ -2595,7 +2591,7 @@ TEST_CASE("RequestMode", "[screen]") mock.terminal.setMode(DECMode::Origin, false); // DECOM screen.requestDECMode((int) DECMode::Origin); REQUIRE(e(mock.terminal.peekInput()) - == e(fmt::format("\033[?{};2$y", toDECModeNum(DECMode::Origin)))); + == e(std::format("\033[?{};2$y", toDECModeNum(DECMode::Origin)))); } SECTION("DEC modes: unknown") @@ -2603,7 +2599,7 @@ TEST_CASE("RequestMode", "[screen]") auto const m = static_cast(1234); mock.terminal.setMode(m, true); // DECOM screen.requestDECMode(static_cast(m)); - REQUIRE(e(mock.terminal.peekInput()) == e(fmt::format("\033[?{};0$y", toDECModeNum(m)))); + REQUIRE(e(mock.terminal.peekInput()) == e(std::format("\033[?{};0$y", toDECModeNum(m)))); } } @@ -2957,12 +2953,12 @@ TEST_CASE("searchReverse", "[screen]") auto& screen = mock.terminal.primaryScreen(); auto const cursorPosition = screen.cursor().position; - INFO(fmt::format("cursor pos {}", cursorPosition)); + INFO(std::format("cursor pos {}", cursorPosition)); // for (bool const inflate: { false, true }) for (bool const inflate: { true }) { - INFO(fmt::format("Perform tests via {}", inflate ? "inflated buffer" : "trivial buffer")); + INFO(std::format("Perform tests via {}", inflate ? "inflated buffer" : "trivial buffer")); if (inflate) for (auto lineOffset = LineOffset(-3); lineOffset < LineOffset(3); ++lineOffset) (void) screen.grid().lineAt(lineOffset).inflatedBuffer(); @@ -3277,9 +3273,9 @@ TEST_CASE("OSC.4") TEST_CASE("XTGETTCAP") { auto mock = MockTerm { PageSize { LineCount(2), ColumnCount(2) } }; - auto const queryStr = fmt::format("\033P+q{:02X}{:02X}{:02X}\033\\", 'R', 'G', 'B'); + auto const queryStr = std::format("\033P+q{:02X}{:02X}{:02X}\033\\", 'R', 'G', 'B'); mock.writeToScreen(queryStr); - INFO(fmt::format("Reply data: {}", mock.terminal.peekInput())); + INFO(std::format("Reply data: {}", mock.terminal.peekInput())); // "\033P1+r8/8/8\033\\" // TODO: CHECK(...) } @@ -3449,7 +3445,7 @@ TEST_CASE("DECCRA.DownLeft.intersecting", "[screen]") // copy up by one line (4 to 3), 2 lines // copy left by one column (3 to 2), 2 columns - auto const deccraSeq = fmt::format( + auto const deccraSeq = std::format( "\033[{};{};{};{};{};{};{};{}$v", STop, SLeft, SBottom, SRightt, Page, TTop, TLeftt, Page); mock.writeToScreen(deccraSeq); @@ -3480,7 +3476,7 @@ TEST_CASE("DECCRA.Right.intersecting", "[screen]") auto constexpr SBottomRight = CellLocation { LineOffset(3), ColumnOffset(3) }; auto constexpr TTopLeft = CellLocation { LineOffset(1), ColumnOffset(2) }; - auto const deccraSeq = fmt::format("\033[{};{};{};{};{};{};{};{}$v", + auto const deccraSeq = std::format("\033[{};{};{};{};{};{};{};{}$v", STopLeft.line + 1, STopLeft.column + 1, SBottomRight.line + 1, @@ -3518,7 +3514,7 @@ TEST_CASE("DECCRA.Left.intersecting", "[screen]") auto constexpr SBottomRight = CellLocation { LineOffset(2), ColumnOffset(5) }; auto constexpr TTopLeft = CellLocation { LineOffset(1), ColumnOffset(2) }; - auto const deccraSeq = fmt::format("\033[{};{};{};{};{};{};{};{}$v", + auto const deccraSeq = std::format("\033[{};{};{};{};{};{};{};{}$v", STopLeft.line + 1, STopLeft.column + 1, SBottomRight.line + 1, @@ -3594,10 +3590,10 @@ TEST_CASE("Sixel.AutoScroll-1", "[screen]") for (auto line = LineOffset(-1); line < boxed_cast(pageSize.lines); ++line) { - INFO(fmt::format("line {}", line)); + INFO(std::format("line {}", line)); for (auto column = ColumnOffset(0); column < boxed_cast(pageSize.columns); ++column) { - INFO(fmt::format("column {}", column)); + INFO(std::format("column {}", column)); auto const& cell = mock.terminal.primaryScreen().at(line, column); if (line <= LineOffset(9) && column <= ColumnOffset(9)) { @@ -3705,7 +3701,7 @@ TEST_CASE("LS1 and LS0", "[screen]") mock.writeToScreen(text); mock.terminal.tick(1s); mock.terminal.ensureFreshRenderBuffer(); - logScreenText(mock.terminal.primaryScreen(), fmt::format("writeTickAndRender: {}", e(text))); + logScreenText(mock.terminal.primaryScreen(), std::format("writeTickAndRender: {}", e(text))); }; REQUIRE(mock.terminal.primaryScreen().cursor().charsets.isSelected(CharsetTable::G0, CharsetId::USASCII)); diff --git a/src/vtbackend/Selector.h b/src/vtbackend/Selector.h index 76c303a8b4..77de9c8827 100644 --- a/src/vtbackend/Selector.h +++ b/src/vtbackend/Selector.h @@ -8,8 +8,7 @@ #include #include -#include - +#include #include #include #include @@ -183,10 +182,10 @@ void renderSelection(Selection const& selection, Renderer&& render) // {{{ fmtlib custom formatter support template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { using State = vtbackend::Selection::State; - auto format(State state, format_context& ctx) const -> format_context::iterator + auto format(State state, auto& ctx) const { string_view name; switch (state) @@ -200,12 +199,12 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(const vtbackend::Selection& selector, format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::Selection& selector, auto& ctx) const { return formatter::format( - fmt::format( + std::format( "{}({} from {} to {})", [](auto const* selector) -> std::string_view { if (dynamic_cast(selector)) diff --git a/src/vtbackend/Selector_test.cpp b/src/vtbackend/Selector_test.cpp index 829cb67df8..890a9e99ff 100644 --- a/src/vtbackend/Selector_test.cpp +++ b/src/vtbackend/Selector_test.cpp @@ -46,13 +46,13 @@ namespace template [[maybe_unused]] void logScreenTextAlways(Screen const& screen, string const& headline = "") { - fmt::print("{}: ZI={} cursor={} HM={}..{}\n", - headline.empty() ? "screen dump"s : headline, - screen.grid().zero_index(), - screen.realCursorPosition(), - screen.margin().horizontal.from, - screen.margin().horizontal.to); - fmt::print("{}\n", dumpGrid(screen.grid())); + std::cout << std::format("{}: ZI={} cursor={} HM={}..{}\n", + headline.empty() ? "screen dump"s : headline, + screen.grid().zero_index(), + screen.realCursorPosition(), + screen.margin().horizontal.from, + screen.margin().horizontal.to); + std::cout << std::format("{}\n", dumpGrid(screen.grid())); } template diff --git a/src/vtbackend/Sequence.cpp b/src/vtbackend/Sequence.cpp index 4f6f5682c3..ca5456adbb 100644 --- a/src/vtbackend/Sequence.cpp +++ b/src/vtbackend/Sequence.cpp @@ -61,7 +61,7 @@ string Sequence::text() const return sstr.str(); } - sstr << fmt::format("{}", _category); + sstr << std::format("{}", _category); if (_leaderSymbol) sstr << ' ' << _leaderSymbol; diff --git a/src/vtbackend/Sequence.h b/src/vtbackend/Sequence.h index 03e96084f4..da82fd662c 100644 --- a/src/vtbackend/Sequence.h +++ b/src/vtbackend/Sequence.h @@ -64,7 +64,7 @@ class SequenceParameters [[nodiscard]] std::string subParameterBitString() const { - return fmt::format("{:016b}: ", _subParameterTest); + return std::format("{:016b}: ", _subParameterTest); } [[nodiscard]] constexpr gsl::span range() noexcept diff --git a/src/vtbackend/SixelParser_test.cpp b/src/vtbackend/SixelParser_test.cpp index 400690ca20..4cccc7d9ea 100644 --- a/src/vtbackend/SixelParser_test.cpp +++ b/src/vtbackend/SixelParser_test.cpp @@ -69,7 +69,7 @@ TEST_CASE("SixelParser.ground_111111", "[sixel]") { auto const& actualColor = ib.at(CellLocation { LineOffset(y), ColumnOffset(x) }); auto const pinned = x == 0 && y >= 0 && y <= 5; - INFO(fmt::format("x={}, y={}, {}", x, y, pinned ? "pinned" : "")); + INFO(std::format("x={}, y={}, {}", x, y, pinned ? "pinned" : "")); if (pinned) CHECK(actualColor.rgb() == PinColor); else @@ -98,7 +98,7 @@ TEST_CASE("SixelParser.ground_000001", "[sixel]") { for (int y = 0; y < ib.size().height.as(); ++y) { - INFO(fmt::format("x={}, y={}", x, y)); + INFO(std::format("x={}, y={}", x, y)); auto const& actualColor = ib.at(CellLocation { LineOffset(y), ColumnOffset(x) }); auto const pinned = x == 0 && y == 0; if (pinned) @@ -129,7 +129,7 @@ TEST_CASE("SixelParser.ground_010101", "[sixel]") { for (int y = 0; y < ib.size().height.as(); ++y) { - INFO(fmt::format("x={}, y={}", x, y)); + INFO(std::format("x={}, y={}", x, y)); auto const& actualColor = ib.at(CellLocation { LineOffset(y), ColumnOffset(x) }); auto const pinned = x == 0 && (y < 6 && y % 2 == 0); if (pinned) @@ -160,7 +160,7 @@ TEST_CASE("SixelParser.ground_101010", "[sixel]") { for (int y = 0; y < ib.size().height.as(); ++y) { - INFO(fmt::format("x={}, y={}", x, y)); + INFO(std::format("x={}, y={}", x, y)); auto const& actualColor = ib.at(CellLocation { LineOffset(y), ColumnOffset(x) }); auto const pinned = x == 0 && (y < 6 && y % 2 != 0); if (pinned) @@ -269,7 +269,7 @@ TEST_CASE("SixelParser.setAndUseColor", "[sixel]") auto const& expectedColor = x < 5 && y < 6 ? PinColors.at(static_cast(x ? x : 4)) : DefaultColor; auto const& actualColor = ib.at(CellLocation { LineOffset(y), ColumnOffset(x) }); - // INFO(fmt::format("at {}, expect {}, actual {}", + // INFO(std::format("at {}, expect {}, actual {}", // CellLocation { LineOffset(y), ColumnOffset(x) }, // expectedColor, // actualColor)); diff --git a/src/vtbackend/StatusLineBuilder.cpp b/src/vtbackend/StatusLineBuilder.cpp index e4a76cdcbc..cd05dedd62 100644 --- a/src/vtbackend/StatusLineBuilder.cpp +++ b/src/vtbackend/StatusLineBuilder.cpp @@ -8,14 +8,13 @@ #include -#include -#include - #include #include #include +#include #include +#include using namespace std::string_view_literals; @@ -198,13 +197,13 @@ struct VTSerializer return; if (styles.foregroundColor) - result += fmt::format("\033[38:2:{}:{}:{}m", + result += std::format("\033[38:2:{}:{}:{}m", styles.foregroundColor->red, styles.foregroundColor->green, styles.foregroundColor->blue); if (styles.backgroundColor) - result += fmt::format("\033[48:2:{}:{}:{}m", + result += std::format("\033[48:2:{}:{}:{}m", styles.backgroundColor->red, styles.backgroundColor->green, styles.backgroundColor->blue); @@ -277,7 +276,7 @@ struct VTSerializer { auto const currentMousePosition = vt.currentMousePosition(); auto const cellFlags = vt.currentScreen().cellFlagsAt(currentMousePosition); - return fmt::format("{}", cellFlags); + return std::format("{}", cellFlags); } std::string visit(StatusLineDefinitions::CellTextUtf32 const&) @@ -290,7 +289,7 @@ struct VTSerializer auto const cellText32 = unicode::convert_to(std::string_view(cellText)); return ranges::views::transform( - cellText32, [](char32_t ch) { return fmt::format("U+{:04X}", static_cast(ch)); }) + cellText32, [](char32_t ch) { return std::format("U+{:04X}", static_cast(ch)); }) | ranges::views::join(" ") | ranges::to; } @@ -305,7 +304,17 @@ struct VTSerializer std::string visit(StatusLineDefinitions::Clock const&) { crispy::ignore_unused(this); - return fmt::format("{:%H:%M}", fmt::localtime(std::time(nullptr))); + + // TODO: Find a more convinient way; The following is printing the time in UTC, + // but we need it in local time. + // return std::format("{:%H:%M}", std::chrono::system_clock::now()); + + auto now = std::chrono::system_clock::now(); + std::time_t const nowTimeT = std::chrono::system_clock::to_time_t(now); + std::tm const* tm = std::localtime(&nowTimeT); + std::stringstream out; + out << std::put_time(tm, "%H:%M"); + return out.str(); } std::string visit(StatusLineDefinitions::HistoryLineCount const&) @@ -317,19 +326,19 @@ struct VTSerializer { auto const pct = double(vt.viewport().scrollOffset()) / double(vt.primaryScreen().historyLineCount()); - return fmt::format("{}/{} {:3}%", + return std::format("{}/{} {:3}%", vt.viewport().scrollOffset(), vt.primaryScreen().historyLineCount(), int(pct * 100)); } else - return fmt::format("{}", vt.primaryScreen().historyLineCount()); + return std::format("{}", vt.primaryScreen().historyLineCount()); } std::string visit(StatusLineDefinitions::Hyperlink const&) { if (auto const hyperlink = vt.currentScreen().hyperlinkAt(vt.currentMousePosition())) - return fmt::format("{}", hyperlink->uri); + return std::format("{}", hyperlink->uri); return {}; } @@ -354,7 +363,7 @@ struct VTSerializer result += "TRACING"; if (!vt.traceHandler().pendingSequences().empty()) - result += fmt::format(" (#{}): {}", + result += std::format(" (#{}): {}", vt.traceHandler().pendingSequences().size(), vt.traceHandler().pendingSequences().front()); return result; @@ -371,7 +380,7 @@ struct VTSerializer std::string visit(StatusLineDefinitions::SearchPrompt const&) { if (vt.inputHandler().isEditingSearch()) - return fmt::format("Search: {}█", + return std::format("Search: {}█", unicode::convert_to(std::u32string_view(vt.search().pattern))); return {}; @@ -406,7 +415,7 @@ struct VTSerializer return item.text; } - std::string visit(StatusLineDefinitions::VTType const&) { return fmt::format("{}", vt.terminalId()); } + std::string visit(StatusLineDefinitions::VTType const&) { return std::format("{}", vt.terminalId()); } // }}} }; diff --git a/src/vtbackend/Terminal.cpp b/src/vtbackend/Terminal.cpp index f6682626c6..558db56ca3 100644 --- a/src/vtbackend/Terminal.cpp +++ b/src/vtbackend/Terminal.cpp @@ -19,14 +19,13 @@ #include -#include - #include #include #include #include +#include #include #include #include @@ -2383,7 +2382,7 @@ void Terminal::pushColorPalette(size_t slot) void Terminal::reportColorPaletteStack() { // XTREPORTCOLORS - reply(fmt::format("\033[{};{}#Q", _savedColorPalettes.size(), _lastSavedColorPalette)); + reply(std::format("\033[{};{}#Q", _savedColorPalettes.size(), _lastSavedColorPalette)); } void Terminal::popColorPalette(size_t slot) @@ -2451,22 +2450,22 @@ void TraceHandler::flushOne(PendingSequence const& pendingSequence) if (auto const* seq = std::get_if(&pendingSequence)) { if (auto const* functionDefinition = seq->functionDefinition(_terminal->activeSequences())) - fmt::print("\t{:<20} ; {:<18} ; {}\n", - seq->text(), - functionDefinition->documentation.mnemonic, - functionDefinition->documentation.comment); + std::cout << std::format("\t{:<20} ; {:<18} ; {}\n", + seq->text(), + functionDefinition->documentation.mnemonic, + functionDefinition->documentation.comment); else - fmt::print("\t{:<20}\n", seq->text()); + std::cout << std::format("\t{:<20}\n", seq->text()); _terminal->activeDisplay().processSequence(*seq); } else if (auto const* codepoint = std::get_if(&pendingSequence)) { - fmt::print("\t'{}'\n", unicode::convert_to(*codepoint)); + std::cout << std::format("\t'{}'\n", unicode::convert_to(*codepoint)); _terminal->activeDisplay().writeText(*codepoint); } else if (auto const* codepoints = std::get_if(&pendingSequence)) { - fmt::print("\t\"{}\" ; {} cells\n", codepoints->text, codepoints->cellCount); + std::cout << std::format("\t\"{}\" ; {} cells\n", codepoints->text, codepoints->cellCount); _terminal->activeDisplay().writeText(codepoints->text, codepoints->cellCount); } } @@ -2483,7 +2482,7 @@ std::string to_string(AnsiMode mode) case AnsiMode::AutomaticNewLine: return "AutomaticNewLine"; } - return fmt::format("({})", static_cast(mode)); + return std::format("({})", static_cast(mode)); } std::string to_string(DECMode mode) @@ -2530,7 +2529,7 @@ std::string to_string(DECMode mode) case DECMode::SixelCursorNextToGraphic: return "SixelCursorNextToGraphic"; case DECMode::ReportColorPaletteUpdated: return "ReportColorPaletteUpdated"; } - return fmt::format("({})", static_cast(mode)); + return std::format("({})", static_cast(mode)); } } // namespace vtbackend diff --git a/src/vtbackend/Terminal.h b/src/vtbackend/Terminal.h index 0abbf98f07..79a2af5654 100644 --- a/src/vtbackend/Terminal.h +++ b/src/vtbackend/Terminal.h @@ -29,8 +29,6 @@ #include #include -#include - #include #include @@ -38,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -768,12 +767,12 @@ class Terminal void reply(std::string_view text); template - void reply(fmt::format_string message, Ts const&... args) + void reply(std::string_view message, Ts const&... args) { #if defined(__APPLE__) || defined(_MSC_VER) - reply(fmt::vformat(message, fmt::make_format_args(args...))); + reply(std::vformat(message, std::make_format_args(args...))); #else - reply(fmt::vformat(message, fmt::make_format_args(args...))); + reply(std::vformat(message, std::make_format_args(args...))); #endif } @@ -1197,18 +1196,17 @@ class Terminal // {{{ fmt formatter specializations template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::TraceHandler::PendingSequence const& pendingSequence, - format_context& ctx) const -> format_context::iterator + auto format(vtbackend::TraceHandler::PendingSequence const& pendingSequence, auto& ctx) const { std::string value; if (auto const* p = std::get_if(&pendingSequence)) - value = fmt::format("{}", p->text()); + value = std::format("{}", p->text()); else if (auto const* p = std::get_if(&pendingSequence)) - value = fmt::format("\"{}\"", crispy::escape(p->text)); + value = std::format("\"{}\"", crispy::escape(p->text)); else if (auto const* p = std::get_if(&pendingSequence)) - value = fmt::format("'{}'", unicode::convert_to(*p)); + value = std::format("'{}'", unicode::convert_to(*p)); else crispy::unreachable(); @@ -1217,25 +1215,25 @@ struct fmt::formatter: fmt::formatter< }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::AnsiMode mode, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::AnsiMode mode, auto& ctx) const { return formatter::format(to_string(mode), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::DECMode mode, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::DECMode mode, auto& ctx) const { return formatter::format(to_string(mode), ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { template auto format(vtbackend::DynamicColorName value, FormatContext& ctx) const @@ -1257,9 +1255,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::ExecutionMode value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ExecutionMode value, auto& ctx) const { string_view name; switch (value) diff --git a/src/vtbackend/Terminal_test.cpp b/src/vtbackend/Terminal_test.cpp index 051648c108..98468b15d0 100644 --- a/src/vtbackend/Terminal_test.cpp +++ b/src/vtbackend/Terminal_test.cpp @@ -108,12 +108,8 @@ TEST_CASE("Terminal.DECCARA", "[terminal]") auto const left = 3; auto const bottom = 4; auto const right = 5; - mock.writeToScreen(fmt::format("\033[{top};{left};{bottom};{right};{sgr}$r", - fmt::arg("top", top), - fmt::arg("left", left), - fmt::arg("bottom", bottom), - fmt::arg("right", right), - fmt::arg("sgr", "1;38:2::171:178:191;4"))); + mock.writeToScreen( + std::format("\033[{};{};{};{};{}$r", top, left, bottom, right, "1;38:2::171:178:191;4")); mock.terminal.tick(ClockBase + chrono::seconds(2)); mock.terminal.ensureFreshRenderBuffer(); @@ -128,8 +124,8 @@ TEST_CASE("Terminal.DECCARA", "[terminal]") // clang-format off auto const& someCell = mock.terminal.primaryScreen().at(LineOffset(line - 1), ColumnOffset(column - 1)); auto const rgb = someCell.foregroundColor().rgb(); - auto const colorDec = fmt::format("{}/{}/{}", unsigned(rgb.red), unsigned(rgb.green), unsigned(rgb.blue)); - INFO(fmt::format("at line {} column {}, flags {}", line, column, someCell.flags())); + auto const colorDec = std::format("{}/{}/{}", unsigned(rgb.red), unsigned(rgb.green), unsigned(rgb.blue)); + INFO(std::format("at line {} column {}, flags {}", line, column, someCell.flags())); CHECK(colorDec == "171/178/191"); CHECK(someCell.isFlagEnabled(vtbackend::CellFlag::Bold)); CHECK(someCell.isFlagEnabled(vtbackend::CellFlag::Underline)); @@ -154,8 +150,8 @@ TEST_CASE("Terminal.CaptureScreenBuffer") // fill screen buffer (5 lines into history + full 5 lines page buffer) for (int i = 1; i <= 10; ++i) { - mock.writeToScreen(fmt::format("\r\n{}", i)); - logScreenText(mock.terminal, fmt::format("write i {}", i)); + mock.writeToScreen(std::format("\r\n{}", i)); + logScreenText(mock.terminal, std::format("write i {}", i)); } mock.terminal.tick(ClockBase + chrono::seconds(1)); @@ -164,7 +160,7 @@ TEST_CASE("Terminal.CaptureScreenBuffer") REQUIRE("6\n7\n8\n9\n10" == actualScreen1); logScreenText(mock.terminal, "fini"); - mock.writeToScreen(fmt::format("\033[>{};{}t", NoLogicalLines, NumberOfLinesToCapture)); + mock.writeToScreen(std::format("\033[>{};{}t", NoLogicalLines, NumberOfLinesToCapture)); mock.terminal.flushInput(); logScreenText(mock.terminal, "after flush"); diff --git a/src/vtbackend/VTType.h b/src/vtbackend/VTType.h index ae8f95ca38..8ff611f544 100644 --- a/src/vtbackend/VTType.h +++ b/src/vtbackend/VTType.h @@ -3,8 +3,7 @@ #include -#include - +#include #include namespace vtbackend @@ -80,9 +79,9 @@ std::string to_params(DeviceAttributes v); // {{{ fmtlib support template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(const vtbackend::VTType id, format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::VTType id, auto& ctx) const { string_view name; switch (id) @@ -102,9 +101,9 @@ struct fmt::formatter: fmt::formatter } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(const vtbackend::VTExtension id, format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::VTExtension id, auto& ctx) const { string_view name; switch (id) diff --git a/src/vtbackend/VTWriter.cpp b/src/vtbackend/VTWriter.cpp index 0130b61432..3a7e84f656 100644 --- a/src/vtbackend/VTWriter.cpp +++ b/src/vtbackend/VTWriter.cpp @@ -68,11 +68,11 @@ string VTWriter::sgrFlush(vector const& sgr) end(sgr), string {}, [](auto a, auto b) { - return a.empty() ? fmt::format("{}", b) : fmt::format("{};{}", a, b); + return a.empty() ? std::format("{}", b) : std::format("{};{}", a, b); }) : string(); - return fmt::format("\033[{}m", params); + return std::format("\033[{}m", params); } void VTWriter::sgrAddExplicit(unsigned n) diff --git a/src/vtbackend/VTWriter.h b/src/vtbackend/VTWriter.h index 9fc54b4ef9..b54916749c 100644 --- a/src/vtbackend/VTWriter.h +++ b/src/vtbackend/VTWriter.h @@ -8,8 +8,7 @@ #include -#include - +#include #include #include #include @@ -37,7 +36,7 @@ class VTWriter void write(Line const& line); template - void write(fmt::format_string fmt, T const&... args); + void write(std::format_string fmt, T const&... args); void write(std::string_view s); void write(char32_t v); @@ -73,12 +72,12 @@ class VTWriter }; template -inline void VTWriter::write(fmt::format_string fmt, Ts const&... args) +inline void VTWriter::write(std::format_string fmt, Ts const&... args) { #if defined(__APPLE__) - write(fmt::vformat(fmt, fmt::make_format_args(args...))); + write(std::vformat(fmt, std::make_format_args(args...))); #else - write(fmt::vformat(fmt, fmt::make_format_args(std::forward(args)...))); + write(std::vformat(fmt, std::make_format_args(std::forward(args)...))); #endif } diff --git a/src/vtbackend/ViCommands.cpp b/src/vtbackend/ViCommands.cpp index a325d3febd..2306dc7457 100644 --- a/src/vtbackend/ViCommands.cpp +++ b/src/vtbackend/ViCommands.cpp @@ -6,8 +6,7 @@ #include -#include - +#include #include namespace vtbackend diff --git a/src/vtbackend/ViInputHandler.cpp b/src/vtbackend/ViInputHandler.cpp index 9453193a8c..b9cdead00e 100644 --- a/src/vtbackend/ViInputHandler.cpp +++ b/src/vtbackend/ViInputHandler.cpp @@ -179,18 +179,18 @@ void ViInputHandler::registerAllCommands() // operate on the full line, with yy or oo. registerCommand(ModeSelect::Normal, - fmt::format("{}{}", key, key), + std::format("{}{}", key, key), [this, op]() { _executor->execute(op, ViMotion::FullLine, count()); }); for (auto && [motionChars, motion]: MotionMappings) { // Passing motion as motion=motion (new variable) is yet another workaround for Clang 15 (Ubuntu) this time. registerCommand(ModeSelect::Normal, - fmt::format("{}{}", key, motionChars), + std::format("{}{}", key, motionChars), [this, op, motion=motion]() { _executor->execute(op, motion, count()); }); } - auto const s3 = [key](char ch) { return fmt::format("{}{}.", key, ch); }; + auto const s3 = [key](char ch) { return std::format("{}{}.", key, ch); }; registerCommand(ModeSelect::Normal, s3('t'), [this, op]() { _executor->execute(op, ViMotion::TillBeforeCharRight, count(), _lastChar); }); registerCommand(ModeSelect::Normal, s3('T'), [this, op]() { _executor->execute(op, ViMotion::TillAfterCharLeft, count(), _lastChar); }); registerCommand(ModeSelect::Normal, s3('f'), [this, op]() { _executor->execute(op, ViMotion::ToCharRight, count(), _lastChar); }); @@ -203,10 +203,10 @@ void ViInputHandler::registerAllCommands() for (auto const& [objectChar, obj]: TextObjectMappings) { registerCommand(ModeSelect::Normal, - fmt::format("y{}{}", scopeChar, objectChar), + std::format("y{}{}", scopeChar, objectChar), [this, scope = scope, obj = obj]() { _executor->yank(scope, obj); }); registerCommand(ModeSelect::Normal, - fmt::format("o{}{}", scopeChar, objectChar), + std::format("o{}{}", scopeChar, objectChar), [this, scope = scope, obj = obj]() { _executor->open(scope, obj); }); } } @@ -226,7 +226,7 @@ void ViInputHandler::registerAllCommands() for (auto const& [scopeChar, scope]: ScopeMappings) for (auto const& [objectChar, obj]: TextObjectMappings) registerCommand(ModeSelect::Visual, - fmt::format("{}{}", scopeChar, objectChar), + std::format("{}{}", scopeChar, objectChar), [this, scope = scope, obj = obj]() { _executor->select(scope, obj); }); } @@ -286,7 +286,7 @@ void ViInputHandler::handlePendingInput() auto const mappingResult = mapping.search(_pendingInput, TrieMapAllowWildcardDot); if (std::holds_alternative>(mappingResult)) { - inputLog()("Executing handler for: {}{}", _count ? fmt::format("{} ", _count) : "", _pendingInput); + inputLog()("Executing handler for: {}{}", _count ? std::format("{} ", _count) : "", _pendingInput); _lastChar = unicode::convert_to(std::string_view(_pendingInput.data(), _pendingInput.size())) .back(); diff --git a/src/vtbackend/ViInputHandler.h b/src/vtbackend/ViInputHandler.h index 41223c47db..4968889117 100644 --- a/src/vtbackend/ViInputHandler.h +++ b/src/vtbackend/ViInputHandler.h @@ -266,9 +266,9 @@ class ViInputHandler: public InputHandler // {{{ fmtlib custom formatters template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::TextObjectScope scope, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::TextObjectScope scope, auto& ctx) const { using TextObjectScope = vtbackend::TextObjectScope; string_view name; @@ -282,9 +282,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::TextObject textObject, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::TextObject textObject, auto& ctx) const { using TextObject = vtbackend::TextObject; string_view name; @@ -307,9 +307,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::ViOperator op, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ViOperator op, auto& ctx) const { string_view name; using vtbackend::ViOperator; @@ -327,9 +327,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::ViMotion motion, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ViMotion motion, auto& ctx) const { string_view name; using vtbackend::ViMotion; diff --git a/src/vtbackend/bench-headless.cpp b/src/vtbackend/bench-headless.cpp index 159dec42e6..3b9f6833fc 100644 --- a/src/vtbackend/bench-headless.cpp +++ b/src/vtbackend/bench-headless.cpp @@ -13,8 +13,7 @@ #include #include -#include - +#include #include #include #include @@ -23,8 +22,6 @@ using namespace std; -using namespace contour; - namespace { @@ -62,17 +59,16 @@ int baseBenchmark(Writer&& writer, BenchOptions options, string_view title) options.sgr = true; } - auto const titleText = fmt::format("Running benchmark: {} (test size: {} MB)", title, options.testSizeMB); + auto const titleText = std::format("Running benchmark: {} (test size: {} MB)", title, options.testSizeMB); cout << titleText << '\n' << string(titleText.size(), '=') << '\n'; - auto tbp = contour::termbench::Benchmark { std::forward(writer), - options.testSizeMB, - 80, - 24, - [&](contour::termbench::Test const& test) { - cout << fmt::format("Running test {} ...\n", test.name); - } }; + auto tbp = termbench::Benchmark { std::forward(writer), + options.testSizeMB, + termbench::TerminalSize { 80, 24 }, + [&](termbench::Test const& test) { + cout << std::format("Running test {} ...\n", test.name); + } }; if (options.manyLines) tbp.add(termbench::tests::many_lines()); @@ -166,17 +162,17 @@ class ContourHeadlessBench: public crispy::app static int showMetaInfo() { // Show any interesting meta information. - fmt::print("SimpleCell : {} bytes\n", sizeof(vtbackend::SimpleCell)); - fmt::print("CompactCell : {} bytes\n", sizeof(vtbackend::CompactCell)); - fmt::print("CellExtra : {} bytes\n", sizeof(vtbackend::CellExtra)); - fmt::print("CellFlags : {} bytes\n", sizeof(vtbackend::CellFlags)); - fmt::print("Color : {} bytes\n", sizeof(vtbackend::Color)); + std::cout << std::format("SimpleCell : {} bytes\n", sizeof(vtbackend::SimpleCell)); + std::cout << std::format("CompactCell : {} bytes\n", sizeof(vtbackend::CompactCell)); + std::cout << std::format("CellExtra : {} bytes\n", sizeof(vtbackend::CellExtra)); + std::cout << std::format("CellFlags : {} bytes\n", sizeof(vtbackend::CellFlags)); + std::cout << std::format("Color : {} bytes\n", sizeof(vtbackend::Color)); return EXIT_SUCCESS; } BenchOptions benchOptionsFor(string_view kind) { - auto const prefix = fmt::format("bench-headless.{}.", kind); + auto const prefix = std::format("bench-headless.{}.", kind); auto opts = BenchOptions {}; opts.testSizeMB = parameters().uint(prefix + "size"); opts.manyLines = parameters().boolean(prefix + "cat"); @@ -210,7 +206,7 @@ class ContourHeadlessBench: public crispy::app benchOptionsFor("grid"), "terminal with screen buffer"); if (rv == EXIT_SUCCESS) - cout << fmt::format("{:>12}: {}\n\n", "history size", *vt.terminal.maxHistoryLineCount()); + cout << std::format("{:>12}: {}\n\n", "history size", *vt.terminal.maxHistoryLineCount()); return rv; } @@ -261,7 +257,7 @@ class ContourHeadlessBench: public crispy::app } }; // Perform benchmark - fmt::print("Running PTY benchmark ...\n"); + std::cout << std::format("Running PTY benchmark ...\n"); auto const startTime = steady_clock::now(); auto stopTime = startTime; while (stopTime - startTime < benchTime) @@ -280,21 +276,23 @@ class ContourHeadlessBench: public crispy::app auto const mbPerSecs = static_cast(bytesTransferred) / static_cast(secs.count()); - fmt::print("\n"); - fmt::print("PTY stdout throughput bandwidth test\n"); - fmt::print("====================================\n\n"); - fmt::print("Writes per loop : {}\n", WritesPerLoop); - fmt::print("PTY write size : {}\n", PtyWriteSize); - fmt::print("PTY read size : {}\n", PtyReadSize); - fmt::print("Test time : {}.{:03} seconds\n", msecs.count() / 1000, msecs.count() % 1000); - fmt::print("Data transferred : {}\n", crispy::humanReadableBytes(bytesTransferred)); - fmt::print("Reader loop iterations : {}\n", loopIterations); - fmt::print( + std::cout << std::format("\n"); + std::cout << std::format("PTY stdout throughput bandwidth test\n"); + std::cout << std::format("====================================\n\n"); + std::cout << std::format("Writes per loop : {}\n", WritesPerLoop); + std::cout << std::format("PTY write size : {}\n", PtyWriteSize); + std::cout << std::format("PTY read size : {}\n", PtyReadSize); + std::cout << std::format( + "Test time : {}.{:03} seconds\n", msecs.count() / 1000, msecs.count() % 1000); + std::cout << std::format("Data transferred : {}\n", + crispy::humanReadableBytes(bytesTransferred)); + std::cout << std::format("Reader loop iterations : {}\n", loopIterations); + std::cout << std::format( "Average size per read : {}\n", crispy::humanReadableBytes(static_cast(static_cast(bytesTransferred) / static_cast(loopIterations)))); - fmt::print("Transfer speed : {} per second\n", - crispy::humanReadableBytes(static_cast(mbPerSecs))); + std::cout << std::format("Transfer speed : {} per second\n", + crispy::humanReadableBytes(static_cast(mbPerSecs))); return EXIT_SUCCESS; } diff --git a/src/vtbackend/cell/CompactCell.h b/src/vtbackend/cell/CompactCell.h index e8dc3b9129..a4401daf16 100644 --- a/src/vtbackend/cell/CompactCell.h +++ b/src/vtbackend/cell/CompactCell.h @@ -482,18 +482,18 @@ inline bool beginsWith(std::u32string_view text, CompactCell const& cell) noexce } // namespace vtbackend template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtbackend::CompactCell const& cell, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::CompactCell const& cell, auto& ctx) const { std::string codepoints; for (auto const i: crispy::times(cell.codepointCount())) { if (i) codepoints += ", "; - codepoints += fmt::format("{:02X}", static_cast(cell.codepoint(i))); + codepoints += std::format("{:02X}", static_cast(cell.codepoint(i))); } - return formatter::format(fmt::format("(chars={}, width={})", codepoints, cell.width()), + return formatter::format(std::format("(chars={}, width={})", codepoints, cell.width()), ctx); } }; diff --git a/src/vtbackend/doc-tool.cpp b/src/vtbackend/doc-tool.cpp index 30107f1f04..ab055116d8 100644 --- a/src/vtbackend/doc-tool.cpp +++ b/src/vtbackend/doc-tool.cpp @@ -1,8 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include - +#include #include using namespace vtbackend; @@ -19,41 +18,41 @@ int main() pair { Category::OSC, "Operating System Commands"sv }, pair { Category::DCS, "Device Control Sequences"sv } }) { - fmt::print("## {} - {}\n\n", category, headline); + std::cout << std::format("## {} - {}\n\n", category, headline); for (auto const& fn: vtbackend::allFunctions()) { std::string markdown; - markdown += fmt::format("## {} - {}\n\n", fn.documentation.mnemonic, fn.documentation.comment); + markdown += std::format("## {} - {}\n\n", fn.documentation.mnemonic, fn.documentation.comment); - markdown += fmt::format("### Conformance Level\n\n"); + markdown += std::format("### Conformance Level\n\n"); if (fn.extension != VTExtension::None) - markdown += fmt::format("{} extension\n\n", fn.extension); + markdown += std::format("{} extension\n\n", fn.extension); else - markdown += fmt::format("{}\n\n", fn.conformanceLevel); + markdown += std::format("{}\n\n", fn.conformanceLevel); - markdown += fmt::format("### Syntax\n\n```\n"); + markdown += std::format("### Syntax\n\n```\n"); if (!fn.documentation.parameters.empty()) - markdown += fmt::format("{}{} {}{} {}\n", + markdown += std::format("{}{} {}{} {}\n", fn.category, - fn.leader ? fmt::format(" {}", fn.leader) : "", + fn.leader ? std::format(" {}", fn.leader) : "", fn.documentation.parameters, - fn.intermediate ? fmt::format(" {}", fn.intermediate) : "", + fn.intermediate ? std::format(" {}", fn.intermediate) : "", fn.finalSymbol); else - markdown += fmt::format("{}\n", fn); - markdown += fmt::format("```\n\n"); + markdown += std::format("{}\n", fn); + markdown += std::format("```\n\n"); if (!fn.documentation.description.empty()) - markdown += fmt::format("### Description\n\n{}\n\n", fn.documentation.description); + markdown += std::format("### Description\n\n{}\n\n", fn.documentation.description); if (!fn.documentation.notes.empty()) - markdown += fmt::format("### Notes\n\n{}\n\n", fn.documentation.notes); + markdown += std::format("### Notes\n\n{}\n\n", fn.documentation.notes); if (!fn.documentation.examples.empty()) - markdown += fmt::format("### Examples\n\n```\n{}\n```\n\n", fn.documentation.examples); + markdown += std::format("### Examples\n\n```\n{}\n```\n\n", fn.documentation.examples); - fmt::print("{}", markdown); + std::cout << std::format("{}", markdown); } } return EXIT_SUCCESS; diff --git a/src/vtbackend/primitives.h b/src/vtbackend/primitives.h index dc69167665..246ab7b2ab 100644 --- a/src/vtbackend/primitives.h +++ b/src/vtbackend/primitives.h @@ -147,7 +147,7 @@ struct [[nodiscard]] CellLocation inline std::ostream& operator<<(std::ostream& os, CellLocation coord) { - return os << fmt::format("({}, {})", coord.line, coord.column); + return os << std::format("({}, {})", coord.line, coord.column); } inline CellLocation operator+(CellLocation a, CellLocation b) noexcept @@ -886,9 +886,9 @@ struct numeric_limits // {{{ fmt formatter template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::CursorShape value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::CursorShape value, auto& ctx) const { string_view name; switch (value) @@ -903,36 +903,36 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::CellLocation coord, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::CellLocation coord, auto& ctx) const { - return formatter::format(fmt::format("({}, {})", coord.line, coord.column), ctx); + return formatter::format(std::format("({}, {})", coord.line, coord.column), ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::PageSize value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::PageSize value, auto& ctx) const { - return formatter::format(fmt::format("{}x{}", value.columns, value.lines), ctx); + return formatter::format(std::format("{}x{}", value.columns, value.lines), ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::GridSize value, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::GridSize value, auto& ctx) const { - return formatter::format(fmt::format("{}x{}", value.columns, value.lines), ctx); + return formatter::format(std::format("{}x{}", value.columns, value.lines), ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(const vtbackend::ScreenType value, format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::ScreenType value, auto& ctx) const { string_view name; switch (value) @@ -945,18 +945,18 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(const vtbackend::PixelCoordinate coord, format_context& ctx) const -> format_context::iterator + auto format(const vtbackend::PixelCoordinate coord, auto& ctx) const { - return formatter::format(fmt::format("{}:{}", coord.x.value, coord.y.value), ctx); + return formatter::format(std::format("{}:{}", coord.x.value, coord.y.value), ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtbackend::ViMode mode, format_context& ctx) const -> format_context::iterator + auto format(vtbackend::ViMode mode, auto& ctx) const { using vtbackend::ViMode; string_view name; diff --git a/src/vtbackend/test_helpers.h b/src/vtbackend/test_helpers.h index 7355ce83f6..91dee029e0 100644 --- a/src/vtbackend/test_helpers.h +++ b/src/vtbackend/test_helpers.h @@ -101,13 +101,13 @@ template template void logScreenTextAlways(Screen const& screen, std::string const& headline = "") { - fmt::print("{}: ZI={} cursor={} HM={}..{}\n", - headline.empty() ? "screen dump" : headline, - screen.grid().zero_index(), - screen.realCursorPosition(), - screen.margin().horizontal.from, - screen.margin().horizontal.to); - fmt::print("{}\n", dumpGrid(screen.grid())); + std::cout << std::format("{}: ZI={} cursor={} HM={}..{}\n", + headline.empty() ? "screen dump" : headline, + screen.grid().zero_index(), + screen.realCursorPosition(), + screen.margin().horizontal.from, + screen.margin().horizontal.to); + std::cout << std::format("{}\n", dumpGrid(screen.grid())); } template @@ -125,7 +125,7 @@ void logScreenText(Screen const& screen, std::string const& headline = "") UNSCOPED_INFO(headline + ":"); for (auto const line: ::ranges::views::iota(0, *screen.pageSize().lines)) - UNSCOPED_INFO(fmt::format("[{}] \"{}\"", line, screen.grid().lineText(LineOffset::cast_from(line)))); + UNSCOPED_INFO(std::format("[{}] \"{}\"", line, screen.grid().lineText(LineOffset::cast_from(line)))); } inline void logScreenText(vtbackend::Terminal const& terminal, std::string const& headline = "") diff --git a/src/vtparser/CMakeLists.txt b/src/vtparser/CMakeLists.txt index 734aea8da5..be2ddba100 100644 --- a/src/vtparser/CMakeLists.txt +++ b/src/vtparser/CMakeLists.txt @@ -10,7 +10,6 @@ add_library(vtparser STATIC set_target_properties(vtparser PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_EXE}") target_link_libraries(vtparser PUBLIC Microsoft.GSL::GSL - fmt::fmt-header-only range-v3::range-v3 unicode::unicode ) diff --git a/src/vtparser/Parser-impl.h b/src/vtparser/Parser-impl.h index 93e4ef3232..fd899541ea 100644 --- a/src/vtparser/Parser-impl.h +++ b/src/vtparser/Parser-impl.h @@ -349,7 +349,7 @@ void Parser::processOnceViaStateMachine(uint8_ if (auto const t = Table.transitions[s][static_cast(ch)]; t != State::Undefined) { - // fmt::print("VTParser: Transitioning from {} to {}", _state, t); + // std::cout << std::format("VTParser: Transitioning from {} to {}", _state, t); handle(ActionClass::Leave, Table.exitEvents[s], ch); handle(ActionClass::Transition, Table.events[s][static_cast(ch)], ch); _state = t; diff --git a/src/vtparser/Parser.cpp b/src/vtparser/Parser.cpp index 39ef20b579..f68d4ae35d 100644 --- a/src/vtparser/Parser.cpp +++ b/src/vtparser/Parser.cpp @@ -2,10 +2,9 @@ #include #include -#include - #include +#include #include #include @@ -30,7 +29,7 @@ void parserTableDot(std::ostream& os) // {{{ auto const ch = static_cast(i); if (targetState != State::Undefined) { - // os << fmt::format("({}, 0x{:0X}) -> {}\n", static_cast(sourceState), ch, + // os << std::format("({}, 0x{:0X}) -> {}\n", static_cast(sourceState), ch, // targetState); auto const t = Transition { static_cast(sourceState), targetState }; if (!transitions[t].empty() && ch == transitions[t].back().last + 1) @@ -59,18 +58,18 @@ void parserTableDot(std::ostream& os) // {{{ continue; auto const targetStateName = targetState == State::Ground && targetState != sourceState - ? fmt::format("{}_{}", targetState, ++groundCount) - : fmt::format("{}", targetState); + ? std::format("{}_{}", targetState, ++groundCount) + : std::format("{}", targetState); // if (isReachableFromAnywhere(targetState)) - // os << fmt::format(" {} [style=dashed, style=\"rounded, filled\", fillcolor=yellow];\n", + // os << std::format(" {} [style=dashed, style=\"rounded, filled\", fillcolor=yellow];\n", // sourceStateName); if (targetState == State::Ground && sourceState != State::Ground) - os << fmt::format(" \"{}\" [style=\"dashed, filled\", fillcolor=gray, label=\"ground\"];\n", + os << std::format(" \"{}\" [style=\"dashed, filled\", fillcolor=gray, label=\"ground\"];\n", targetStateName); - os << fmt::format(R"( "{}" -> "{}" )", sourceState, targetStateName); + os << std::format(R"( "{}" -> "{}" )", sourceState, targetStateName); os << "["; os << "label=\""; for (auto const&& [rangeCount, u]: enumerate(t.second)) @@ -82,9 +81,9 @@ void parserTableDot(std::ostream& os) // {{{ os << "\\n"; } if (u.first == u.last) - os << fmt::format("{:02X}", u.first); + os << std::format("{:02X}", u.first); else - os << fmt::format("{:02X}-{:02X}", u.first, u.last); + os << std::format("{:02X}-{:02X}", u.first, u.last); } os << "\""; os << "]"; @@ -94,12 +93,12 @@ void parserTableDot(std::ostream& os) // {{{ // equal ranks os << " { rank=same; "; for (auto const state: { State::CSI_Entry, State::DCS_Entry, State::OSC_String }) - os << fmt::format(R"("{}"; )", state); + os << std::format(R"("{}"; )", state); os << "};\n"; os << " { rank=same; "; for (auto const state: { State::CSI_Param, State::DCS_Param, State::OSC_String }) - os << fmt::format(R"("{}"; )", state); + os << std::format(R"("{}"; )", state); os << "};\n"; os << "}\n"; diff --git a/src/vtparser/Parser.h b/src/vtparser/Parser.h index 72ddd9300c..61b018b407 100644 --- a/src/vtparser/Parser.h +++ b/src/vtparser/Parser.h @@ -4,14 +4,13 @@ #include #include -#include - #include #include #include #include #include +#include #include #include #include @@ -466,18 +465,18 @@ struct numeric_limits // {{{ fmtlib custom formatter specializations template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtparser::State state, format_context& ctx) const -> format_context::iterator + auto format(vtparser::State state, auto& ctx) const { return formatter::format(vtparser::to_string(state), ctx); } }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtparser::ActionClass value, format_context& ctx) const -> format_context::iterator + auto format(vtparser::ActionClass value, auto& ctx) const { auto constexpr Mappings = std::array { "Enter", "Event", "Leave", "Transition" }; return formatter::format(Mappings.at(static_cast(value)), ctx); @@ -485,9 +484,9 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtparser::Action value, format_context& ctx) const -> format_context::iterator + auto format(vtparser::Action value, auto& ctx) const { return formatter::format(vtparser::to_string(value), ctx); } diff --git a/src/vtparser/Parser_test.cpp b/src/vtparser/Parser_test.cpp index bcb3555398..22528a473b 100644 --- a/src/vtparser/Parser_test.cpp +++ b/src/vtparser/Parser_test.cpp @@ -16,7 +16,7 @@ class MockParserEvents final: public vtparser::NullParserEvents std::string pm; size_t maxCharCount = 80; - void error(string_view const& msg) override { INFO(fmt::format("Parser error received. {}", msg)); } + void error(string_view const& msg) override { INFO(std::format("Parser error received. {}", msg)); } void print(char32_t ch) override { text += unicode::convert_to(ch); } size_t print(std::string_view s, size_t cellCount) override { diff --git a/src/vtpty/CMakeLists.txt b/src/vtpty/CMakeLists.txt index 8bbcf76891..c0636171b5 100644 --- a/src/vtpty/CMakeLists.txt +++ b/src/vtpty/CMakeLists.txt @@ -13,7 +13,7 @@ if(EXISTS "/.flatpak-info") set(CONTOUR_WITH_UTEMPTER OFF) endif() -set(vtpty_LIBRARIES crispy::core fmt::fmt-header-only Microsoft.GSL::GSL) +set(vtpty_LIBRARIES crispy::core Microsoft.GSL::GSL) set(vtpty_SOURCES MockPty.cpp diff --git a/src/vtpty/ImageSize.h b/src/vtpty/ImageSize.h index 8526d815a0..46ca11b074 100644 --- a/src/vtpty/ImageSize.h +++ b/src/vtpty/ImageSize.h @@ -2,6 +2,7 @@ #pragma once #include +#include #include @@ -89,10 +90,11 @@ constexpr ImageSize max(ImageSize a, ImageSize b) noexcept } // namespace vtpty template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtpty::ImageSize value, format_context& ctx) const -> format_context::iterator + auto format(vtpty::ImageSize value, auto& ctx) const { - return formatter::format(fmt::format("{}x{}", value.width, value.height), ctx); + return formatter::format(std::format("{}x{}", value.width.value, value.height.value), + ctx); } }; diff --git a/src/vtpty/Process.h b/src/vtpty/Process.h index 3ad0e889cd..673f54a03b 100644 --- a/src/vtpty/Process.h +++ b/src/vtpty/Process.h @@ -6,9 +6,8 @@ #include #include -#include - #include +#include #include #include #include @@ -110,27 +109,26 @@ class [[nodiscard]] Process: public Pty } // namespace vtpty template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtpty::Process::ExitStatus const& status, - format_context& ctx) const -> format_context::iterator + auto format(vtpty::Process::ExitStatus const& status, auto& ctx) const { auto const text = std::visit(overloaded { [&](vtpty::Process::NormalExit exit) { - return fmt::format("{} (normal exit)", exit.exitCode); + return std::format("{} (normal exit)", exit.exitCode); }, [&](vtpty::Process::SignalExit exit) { char buf[256]; #if defined(_WIN32) strerror_s(buf, sizeof(buf), errno); - return fmt::format("{} (signal number {})", buf, exit.signum); + return std::format("{} (signal number {})", buf, exit.signum); #else - return fmt::format("{} (signal number {})", + return std::format("{} (signal number {})", strerror_r(errno, buf, sizeof(buf)), exit.signum); #endif } }, status); - return fmt::formatter::format(text, ctx); + return std::formatter::format(text, ctx); } }; diff --git a/src/vtpty/Process_unix.cpp b/src/vtpty/Process_unix.cpp index 9d3d09b1b5..31ec34e740 100644 --- a/src/vtpty/Process_unix.cpp +++ b/src/vtpty/Process_unix.cpp @@ -6,14 +6,13 @@ #include #include -#include - #include #include #include #include #include #include +#include #include #include #include @@ -171,21 +170,21 @@ void Process::start() realArgs.emplace_back("--host"); realArgs.emplace_back("--watch-bus"); realArgs.emplace_back( - fmt::format("--env=TERMINFO={}", terminfoBaseDirectory.generic_string())); + std::format("--env=TERMINFO={}", terminfoBaseDirectory.generic_string())); if (stdoutFastPipe) { - realArgs.emplace_back(fmt::format("--forward-fd={}", StdoutFastPipeFdStr)); + realArgs.emplace_back(std::format("--forward-fd={}", StdoutFastPipeFdStr)); realArgs.emplace_back( - fmt::format("--env={}={}", StdoutFastPipeEnvironmentName, StdoutFastPipeFdStr)); + std::format("--env={}={}", StdoutFastPipeEnvironmentName, StdoutFastPipeFdStr)); } if (!_d->cwd.empty()) - realArgs.emplace_back(fmt::format("--directory={}", _d->cwd.generic_string())); - realArgs.emplace_back(fmt::format("--env=TERM={}", "contour")); + realArgs.emplace_back(std::format("--directory={}", _d->cwd.generic_string())); + realArgs.emplace_back(std::format("--env=TERM={}", "contour")); for (auto&& [name, value]: _d->env) - realArgs.emplace_back(fmt::format("--env={}={}", name, value)); + realArgs.emplace_back(std::format("--env={}={}", name, value)); if (stdoutFastPipe) realArgs.emplace_back( - fmt::format("--env={}={}", StdoutFastPipeEnvironmentName, StdoutFastPipeFd)); + std::format("--env={}={}", StdoutFastPipeEnvironmentName, StdoutFastPipeFd)); realArgs.push_back(_d->path); for (auto const& arg: _d->args) realArgs.push_back(arg); @@ -326,7 +325,7 @@ vector Process::loginShell(bool escapeSandbox) if (isFlatpak() && escapeSandbox) { char buf[1024]; - auto const cmd = fmt::format("flatpak-spawn --host getent passwd {}", pw->pw_name); + auto const cmd = std::format("flatpak-spawn --host getent passwd {}", pw->pw_name); FILE* fp = popen(cmd.c_str(), "r"); auto fpCloser = crispy::finally { [fp]() { pclose(fp); @@ -374,7 +373,7 @@ string Process::workingDirectory() const #if defined(__linux__) try { - auto const path = fs::path { fmt::format("/proc/{}/cwd", _d->pid) }; + auto const path = fs::path { std::format("/proc/{}/cwd", _d->pid) }; auto const cwd = fs::read_symlink(path); return cwd.string(); } diff --git a/src/vtpty/Process_win32.cpp b/src/vtpty/Process_win32.cpp index 64b4040e89..1f264ea8f8 100644 --- a/src/vtpty/Process_win32.cpp +++ b/src/vtpty/Process_win32.cpp @@ -6,14 +6,13 @@ #include #include -#include - #include #include #include #include #include #include +#include #include #include #include @@ -212,7 +211,7 @@ void Process::start() char buf[1024]; size_t len = 0; if (getenv_s(&len, buf, sizeof(buf), "PATH") == 0) - env[name] = fmt::format("{};{}", value, buf); + env[name] = std::format("{};{}", value, buf); } } auto const envScope = InheritingEnvBlock { env }; diff --git a/src/vtpty/SshSession.cpp b/src/vtpty/SshSession.cpp index cd48c4b6b4..a12611e439 100644 --- a/src/vtpty/SshSession.cpp +++ b/src/vtpty/SshSession.cpp @@ -186,15 +186,15 @@ std::string SshHostConfig::toString() const } }; if (!username.empty()) - result += fmt::format("{}@", username); + result += std::format("{}@", username); if (!hostname.empty()) { if (port) { if (hostname.find(':') != std::string::npos) - result += fmt::format("[{}]:{}"sv, hostname, port); + result += std::format("[{}]:{}"sv, hostname, port); else - result += fmt::format("{}:{}"sv, hostname, port); + result += std::format("{}:{}"sv, hostname, port); } else result += hostname; @@ -203,15 +203,15 @@ std::string SshHostConfig::toString() const result += "*:" + std::to_string(port); if (!privateKeyFile.empty()) - add(fmt::format("private key: {}", privateKeyFile.string())); + add(std::format("private key: {}", privateKeyFile.string())); if (!publicKeyFile.empty()) - add(fmt::format("public key: {}", privateKeyFile.string())); + add(std::format("public key: {}", privateKeyFile.string())); if (!knownHostsFile.empty()) - add(fmt::format("known hosts: {}", knownHostsFile.string())); + add(std::format("known hosts: {}", knownHostsFile.string())); - add(fmt::format("ForwardAgent: {}", forwardAgent ? "Yes" : "No")); + add(std::format("ForwardAgent: {}", forwardAgent ? "Yes" : "No")); return result; } @@ -222,20 +222,20 @@ std::string SshHostConfig::toConfigString(std::string const& host) const auto const prefix = host.empty() ? ""sv : " "sv; if (!host.empty()) - result += fmt::format("Host {}\n", host); + result += std::format("Host {}\n", host); if (!hostname.empty()) - result += fmt::format("{}HostName {}\n", prefix, hostname); + result += std::format("{}HostName {}\n", prefix, hostname); if (port != 22) - result += fmt::format("{}Port {}\n", prefix, port); + result += std::format("{}Port {}\n", prefix, port); if (!username.empty()) - result += fmt::format("{}User {}\n", prefix, username); + result += std::format("{}User {}\n", prefix, username); if (!privateKeyFile.empty()) - result += fmt::format("{}IdentityFile {}\n", prefix, privateKeyFile.string()); + result += std::format("{}IdentityFile {}\n", prefix, privateKeyFile.string()); if (!knownHostsFile.empty()) - result += fmt::format("{}KnownHostsFile {}\n", prefix, knownHostsFile.string()); - result += fmt::format("{}ForwardAgent {}\n", prefix, forwardAgent); - result += fmt::format("\n"); + result += std::format("{}KnownHostsFile {}\n", prefix, knownHostsFile.string()); + result += std::format("{}ForwardAgent {}\n", prefix, forwardAgent); + result += std::format("\n"); return result; } @@ -450,7 +450,7 @@ void SshSession::processState() } case State::AuthenticatePasswordStart: { setState(State::AuthenticatePasswordWaitForInput); - injectRead(fmt::format("\U0001F511 Username: {}\r\n", _config.username)); + injectRead(std::format("\U0001F511 Username: {}\r\n", _config.username)); injectRead("\U0001F511 Password: "); [[fallthrough]]; } @@ -901,7 +901,7 @@ void SshSession::injectRead(std::string_view buf) void SshSession::logInject(std::string_view message) const { - const_cast(this)->injectRead(fmt::format("\U0001F511 \033[1;33m{}\033[m\r\n", message)); + const_cast(this)->injectRead(std::format("\U0001F511 \033[1;33m{}\033[m\r\n", message)); } void SshSession::logInfo(std::string_view message) const @@ -977,7 +977,7 @@ bool SshSession::connect(std::string_view host, int port) if (::connect(_p->sshSocket, addrEntry->ai_addr, addrEntry->ai_addrlen) == 0) { auto const addrAndPort = - port == 22 ? std::string(addrStr) : fmt::format("{}:{}", addrStr, port); + port == 22 ? std::string(addrStr) : std::format("{}:{}", addrStr, port); if (host != addrStr) logInfoWithInject("Connected to {} ({})", host, addrAndPort); else @@ -1073,7 +1073,7 @@ bool SshSession::verifyHostKey() case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND: { // TODO: Ask user whether to add host key to known_hosts file auto const comment = - fmt::format("{}@{}:{} (added by Contour)", _config.username, _config.hostname, _config.port); + std::format("{}@{}:{} (added by Contour)", _config.username, _config.hostname, _config.port); auto const typeMask = LIBSSH2_KNOWNHOST_TYPE_PLAIN | LIBSSH2_KNOWNHOST_KEYENC_RAW | knownhostType; libssh2_knownhost_addc(knownHosts, _config.hostname.c_str(), @@ -1147,21 +1147,23 @@ int SshSession::waitForSocket(std::optional timeout) if (dir & LIBSSH2_SESSION_BLOCK_INBOUND) { readfd = &fd; - fmt::print("({}) SshSession: waiting for socket to become readable\n", crispy::threadName()); + std::cout << std::format("({}) SshSession: waiting for socket to become readable\n", + crispy::threadName()); } if (dir & LIBSSH2_SESSION_BLOCK_OUTBOUND) { writefd = &fd; - fmt::print("({}) SshSession: waiting for socket to become readable\n", crispy::threadName()); + std::cout << std::format("({}) SshSession: waiting for socket to become readable\n", + crispy::threadName()); } auto const rc = ::select((int) (_p->sshSocket + 1), readfd, writefd, nullptr, timeout ? &tv : nullptr); - fmt::print("({}) SshSession: select() returned {}{}{}\n", - crispy::threadName(), - rc, - readfd && FD_ISSET(_p->sshSocket, readfd) ? " [readable]" : "", - writefd && FD_ISSET(_p->sshSocket, writefd) ? " [writable]" : ""); + std::cout << std::format("({}) SshSession: select() returned {}{}{}\n", + crispy::threadName(), + rc, + readfd && FD_ISSET(_p->sshSocket, readfd) ? " [readable]" : "", + writefd && FD_ISSET(_p->sshSocket, writefd) ? " [writable]" : ""); return rc; #else crispy::ignore_unused(timeout); diff --git a/src/vtpty/SshSession.h b/src/vtpty/SshSession.h index ac12e17873..4640e5e5e8 100644 --- a/src/vtpty/SshSession.h +++ b/src/vtpty/SshSession.h @@ -123,23 +123,23 @@ class SshSession final: public Pty void logInfoWithInject(std::string_view message) const; template - void logInfoWithInject(fmt::format_string fmt, Args&&... args) const + void logInfoWithInject(std::format_string fmt, Args&&... args) const { - logInfoWithInject(fmt::format(fmt, std::forward(args)...)); + logInfoWithInject(std::format(fmt, std::forward(args)...)); } template - void logInfo(fmt::format_string fmt, Args&&... args) const + void logInfo(std::format_string fmt, Args&&... args) const { - logInfo(fmt::format(fmt, std::forward(args)...)); + logInfo(std::format(fmt, std::forward(args)...)); } void logError(std::string_view message) const; template - void logError(fmt::format_string fmt, Args&&... args) const + void logError(std::format_string fmt, Args&&... args) const { - logError(fmt::format(fmt, std::forward(args)...)); + logError(std::format(fmt, std::forward(args)...)); } SshHostConfig _config; @@ -167,9 +167,9 @@ class SshSession final: public Pty } // namespace vtpty template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtpty::SshSession::State const& state, format_context& ctx) const -> format_context::iterator + auto format(vtpty::SshSession::State const& state, auto& ctx) const { std::string_view name; // clang-format off @@ -199,23 +199,22 @@ struct fmt::formatter: fmt::formatter::format(name, ctx); + return std::formatter::format(name, ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtpty::SshSession::ExitStatus const& status, - format_context& ctx) const -> format_context::iterator + auto format(vtpty::SshSession::ExitStatus const& status, auto& ctx) const { return std::visit(overloaded { [&](vtpty::SshSession::NormalExit exit) { - return fmt::formatter::format( - fmt::format("{} (normal exit)", exit.exitCode), ctx); + return std::formatter::format( + std::format("{} (normal exit)", exit.exitCode), ctx); }, [&](vtpty::SshSession::SignalExit exit) { - return fmt::formatter::format( - fmt::format("{} ({})", exit.signal, exit.errorMessage), ctx); + return std::formatter::format( + std::format("{} ({})", exit.signal, exit.errorMessage), ctx); } }, status); } diff --git a/src/vtrasterizer/BoxDrawingRenderer.cpp b/src/vtrasterizer/BoxDrawingRenderer.cpp index 447a2042fa..154423b3b1 100644 --- a/src/vtrasterizer/BoxDrawingRenderer.cpp +++ b/src/vtrasterizer/BoxDrawingRenderer.cpp @@ -5,14 +5,13 @@ #include -#include - #include #include #include #include #include +#include using namespace std::string_view_literals; @@ -130,7 +129,7 @@ namespace detail auto const w = unbox(imageSize.width); auto const h = unbox(imageSize.height); - // fmt::print("{}.drawArc: size={}\n", arc, imageSize); + // std::cout << std::format("{}.drawArc: size={}\n", arc, imageSize); auto const putpixel = [&](int x, int y, uint8_t alpha = 0xFFu) { auto const fy = clamp((unsigned) y, 0u, h - 1); auto const fx = clamp((unsigned) x, 0u, w - 1); @@ -871,7 +870,7 @@ namespace detail auto const x1 = x0 + 1; auto const y1 = y0 + 1; - // fmt::print("- block sextant pos {}: x={} y={} x0={} y0={} x1={} y1={}\n", + // std::cout << std::format("- block sextant pos {}: x={} y={} x0={} y0={} x1={} y1={}\n", // position, x, y, x0, y0, x1, y1); fillBlock(image, size, { x0 / 2_th, y0 / 3_th }, { x1 / 2_th, y1 / 3_th }, [](int, int) { diff --git a/src/vtrasterizer/Decorator.h b/src/vtrasterizer/Decorator.h index 7d918248b2..06d19a434a 100644 --- a/src/vtrasterizer/Decorator.h +++ b/src/vtrasterizer/Decorator.h @@ -1,9 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 #pragma once -#include - #include +#include #include #include #include @@ -80,9 +79,9 @@ struct std::numeric_limits }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtrasterizer::Decorator value, format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::Decorator value, auto& ctx) const { auto constexpr Mappings = std::array { "underline", "double-underline", "curly-underline", "dotted-underline", "dashed-underline", diff --git a/src/vtrasterizer/FontDescriptions.h b/src/vtrasterizer/FontDescriptions.h index d6f0077fdb..4917efaca9 100644 --- a/src/vtrasterizer/FontDescriptions.h +++ b/src/vtrasterizer/FontDescriptions.h @@ -79,9 +79,9 @@ constexpr bool operator<(TextStyle a, TextStyle b) noexcept // {{{ fmt formatter template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtrasterizer::TextStyle value, format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::TextStyle value, auto& ctx) const { string_view name; switch (value) @@ -97,9 +97,9 @@ struct fmt::formatter: fmt::formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtrasterizer::FontLocatorEngine value, format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::FontLocatorEngine value, auto& ctx) const { string_view name; switch (value) @@ -112,9 +112,9 @@ struct fmt::formatter: fmt::formatter -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtrasterizer::TextShapingEngine value, format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::TextShapingEngine value, auto& ctx) const { string_view name; switch (value) @@ -128,12 +128,11 @@ struct fmt::formatter: fmt::formatter -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtrasterizer::FontDescriptions const& fd, - format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::FontDescriptions const& fd, auto& ctx) const { - return formatter::format(fmt::format("({}, {}, {}, {}, {}, {}, {}, {})", + return formatter::format(std::format("({}, {}, {}, {}, {}, {}, {}, {})", fd.size, fd.dpi, fd.dpiScale, diff --git a/src/vtrasterizer/GridMetrics.h b/src/vtrasterizer/GridMetrics.h index b21f30ef94..4698f9a4c0 100644 --- a/src/vtrasterizer/GridMetrics.h +++ b/src/vtrasterizer/GridMetrics.h @@ -6,7 +6,7 @@ #include #include -#include +#include namespace vtrasterizer { @@ -95,13 +95,12 @@ struct GridMetrics } // namespace vtrasterizer template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtrasterizer::GridMetrics const& v, - fmt::format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::GridMetrics const& v, auto& ctx) const { return formatter::format( - fmt::format( + std::format( "(pageSize={}, cellSize={}, baseline={}, underline={}@{}, margin=(left={}, bottom={}))", v.pageSize, v.cellSize, diff --git a/src/vtrasterizer/ImageRenderer.cpp b/src/vtrasterizer/ImageRenderer.cpp index d423702a5f..2c12e06ff0 100644 --- a/src/vtrasterizer/ImageRenderer.cpp +++ b/src/vtrasterizer/ImageRenderer.cpp @@ -36,7 +36,7 @@ void ImageRenderer::setCellSize(ImageSize cellSize) void ImageRenderer::renderImage(crispy::point pos, vtbackend::ImageFragment const& fragment) { - // std::cout << fmt::format("ImageRenderer.renderImage: {}\n", fragment); + // std::cout << std::format("ImageRenderer.renderImage: {}\n", fragment); AtlasTileAttributes const* tileAttributes = getOrCreateCachedTileAttributes(fragment); if (!tileAttributes) diff --git a/src/vtrasterizer/Pixmap.h b/src/vtrasterizer/Pixmap.h index 8d2b11926b..2be2cde8ce 100644 --- a/src/vtrasterizer/Pixmap.h +++ b/src/vtrasterizer/Pixmap.h @@ -7,12 +7,11 @@ #include -#include - #include #include #include +#include #include namespace vtrasterizer @@ -300,9 +299,9 @@ Pixmap& Pixmap::segment_bar(int which, More... more) } // end namespace vtrasterizer template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtrasterizer::Arc value, format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::Arc value, auto& ctx) const { using vtrasterizer::Arc; string_view name; diff --git a/src/vtrasterizer/RenderTarget.h b/src/vtrasterizer/RenderTarget.h index 56e330692f..34908dfcc1 100644 --- a/src/vtrasterizer/RenderTarget.h +++ b/src/vtrasterizer/RenderTarget.h @@ -219,25 +219,24 @@ inline Renderable::TextureAtlas::TileCreateData Renderable::createTileData(atlas // {{{ fmt template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtrasterizer::RenderTileAttributes value, - format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::RenderTileAttributes value, auto& ctx) const { - return fmt::formatter::format( - fmt::format("tile +{}x +{}y", value.x.value, value.y.value), ctx); + return std::formatter::format( + std::format("tile +{}x +{}y", value.x.value, value.y.value), ctx); } }; template <> -struct fmt::formatter>: - fmt::formatter +struct std::formatter>: + std::formatter { auto format(vtrasterizer::atlas::TileAttributes const& value, - format_context& ctx) const -> format_context::iterator + auto& ctx) const { return formatter::format( - fmt::format("(location {}; bitmap {}; {})", value.location, value.bitmapSize, value.metadata), + std::format("(location {}; bitmap {}; {})", value.location, value.bitmapSize, value.metadata), ctx); } }; diff --git a/src/vtrasterizer/Renderer.h b/src/vtrasterizer/Renderer.h index 454f4a7eec..3562a6632c 100644 --- a/src/vtrasterizer/Renderer.h +++ b/src/vtrasterizer/Renderer.h @@ -17,10 +17,9 @@ #include #include -#include - #include +#include #include #include diff --git a/src/vtrasterizer/TextClusterGrouper_test.cpp b/src/vtrasterizer/TextClusterGrouper_test.cpp index 48de38237d..bb9a39ed9e 100644 --- a/src/vtrasterizer/TextClusterGrouper_test.cpp +++ b/src/vtrasterizer/TextClusterGrouper_test.cpp @@ -8,14 +8,16 @@ #include -#include -#include +#include +#include +#include #include #include #include +#include #include #include @@ -98,18 +100,20 @@ struct FrameWriter } // namespace -// {{{ fmt::formatter for cuswtom times +// {{{ std::formatter for cuswtom times template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { template auto format(TextClusterGroup const& group, FormatContext& ctx) const { return formatter::format( - fmt::format("TextClusterGroup {{ codepoints: \"{}\", @{}, clusters={}, style: {}, color: {} }}", + std::format("TextClusterGroup {{ codepoints: \"{}\", @{}, clusters={}, style: {}, color: {} }}", crispy::escape(unicode::convert_to(std::u32string_view(group.codepoints))), group.initialPenPosition, - group.clusters, + group.clusters + | ::ranges::views::transform([](int cluster) { return std::to_string(cluster); }) + | ::ranges::views::join(", ") | ::ranges::to(), group.style, group.color), ctx); @@ -117,13 +121,13 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { template auto format(BoxDrawingCell const& cell, FormatContext& ctx) const { return formatter::format( - fmt::format("BoxDrawingCell {{ position: {}, codepoint: U+{:04X}, color: {} }}", + std::format("BoxDrawingCell {{ position: {}, codepoint: U+{:04X}, color: {} }}", cell.position, (unsigned) cell.codepoint, cell.foregroundColor), @@ -132,15 +136,15 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { template auto format(Event const& event, FormatContext& ctx) const { if (std::holds_alternative(event)) - return formatter::format(fmt::format("{}", std::get(event)), ctx); + return formatter::format(std::format("{}", std::get(event)), ctx); else - return formatter::format(fmt::format("{}", std::get(event)), ctx); + return formatter::format(std::format("{}", std::get(event)), ctx); } }; // }}} @@ -183,7 +187,7 @@ ostream& operator<<(std::ostream& os, u32string_view text) ostream& operator<<(std::ostream& os, TextClusterGroup const& group) { - return os << fmt::format("{}", group); + return os << std::format("{}", group); } } // namespace std // }}} diff --git a/src/vtrasterizer/TextRenderer.cpp b/src/vtrasterizer/TextRenderer.cpp index 9e67f0ea94..d3dae95815 100644 --- a/src/vtrasterizer/TextRenderer.cpp +++ b/src/vtrasterizer/TextRenderer.cpp @@ -141,9 +141,6 @@ Making use of reserved glyph slots #include #include -#include -#include - #include #include @@ -408,7 +405,7 @@ Renderable::AtlasTileAttributes const* TextRenderer::ensureRasterizedIfDirectMap restrictToTileSize(*tileCreateData); Require(tileCreateData->bitmapSize.width <= textureAtlas().tileSize().width); - // fmt::print("Initialize direct mapping {} ({}) for {}; {}; {}\n", + // std::cout << std::format("Initialize direct mapping {} ({}) for {}; {}; {}\n", // tileIndex, // tileLocation, // glyph, @@ -442,7 +439,7 @@ void TextRenderer::renderLine(vtbackend::RenderLine const& renderLine) void TextRenderer::renderCell(vtbackend::RenderCell const& cell) { - // fmt::print("renderCell: {} {} {} {} {}\n", + // std::cout << std::format("renderCell: {} {} {} {} {}\n", // cell.position, // unicode::convert_to(u32string_view(cell.codepoints)), // _forceUpdateInitialPenPosition ? "forcedRestart" : "-", @@ -490,7 +487,7 @@ point TextRenderer::applyGlyphPositionToPen(point pen, //- tileAttributes.bitmapSize.height.as() // -> bitmap height ; - // fmt::print("pen! {} <- {}, gpos {}, glyph offset {}x+{}y, glyph height {} ({})\n", + // std::cout << std::format("pen! {} <- {}, gpos {}, glyph offset {}x+{}y, glyph height {} ({})\n", // Point { x, y }, // pen, // gpos, diff --git a/src/vtrasterizer/TextureAtlas.h b/src/vtrasterizer/TextureAtlas.h index 1c9b97795b..cc8a24654b 100644 --- a/src/vtrasterizer/TextureAtlas.h +++ b/src/vtrasterizer/TextureAtlas.h @@ -8,9 +8,8 @@ #include #include -#include - #include +#include #include // monostate #include @@ -371,7 +370,7 @@ struct DirectMappingAllocator uint32_t const baseIndex = currentlyAllocatedCount; currentlyAllocatedCount += count; - // fmt::print("DirectMappingAllocator.allocate: {} .. {} (#{})\n", + // std::cout << std::format("DirectMappingAllocator.allocate: {} .. {} (#{})\n", // baseIndex, baseIndex + count - 1, count); return DirectMapping { baseIndex, count }; } @@ -462,7 +461,7 @@ inline vtbackend::ImageSize computeAtlasSize(AtlasProperties const& atlasPropert squareEdgeCount * unbox(atlasProperties.tileSize.height)))); // clang-format on - // fmt::print("computeAtlasSize: tiles {}+{}={} -> texture size {}x{} (tile size {})\n", + // std::cout << std::format("computeAtlasSize: tiles {}+{}={} -> texture size {}x{} (tile size {})\n", // atlasProperties.tileCount, // atlasProperties.directMappingCount, // totalTileCount, @@ -503,7 +502,7 @@ TextureAtlas::TextureAtlas(AtlasBackend& backend, AtlasProperties atla Require(_atlasProperties.tileCount.value <= _tileCache->capacity()); Require(_atlasProperties.directMappingCount + _atlasProperties.tileCount.value <= _tilesInX * _tilesInY); - // fmt::print("TextureAtlas: tiles {}x{} (locations: {} >= {}) texture {}; props {}\n", + // std::cout << std::format("TextureAtlas: tiles {}x{} (locations: {} >= {}) texture {}; props {}\n", // _tilesInX, // _tilesInY, // _tileLocations.size(), @@ -667,11 +666,11 @@ void TextureAtlas::setDirectMapping(uint32_t tileIndex, TileCreateData template void TextureAtlas::inspect(std::ostream& output) const { - output << fmt::format("TextureAtlas\n"); - output << fmt::format("------------------------\n"); - output << fmt::format("atlas size : {}\n", _atlasSize); - output << fmt::format("tile size : {}\n", _atlasProperties.tileSize); - output << fmt::format("direct mapped : {}\n", _atlasProperties.directMappingCount); + output << std::format("TextureAtlas\n"); + output << std::format("------------------------\n"); + output << std::format("atlas size : {}\n", _atlasSize); + output << std::format("tile size : {}\n", _atlasProperties.tileSize); + output << std::format("direct mapped : {}\n", _atlasProperties.directMappingCount); output << '\n'; _tileCache->inspect(output); } @@ -682,9 +681,9 @@ void TextureAtlas::inspect(std::ostream& output) const // {{{ fmt support template <> -struct fmt::formatter: formatter +struct std::formatter: formatter { - auto format(vtrasterizer::atlas::Format value, format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::atlas::Format value, auto& ctx) const { std::string_view name; switch (value) @@ -698,33 +697,30 @@ struct fmt::formatter: formatter }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtrasterizer::atlas::TileLocation value, - format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::atlas::TileLocation value, auto& ctx) const { - return formatter::format(fmt::format("Tile {}x+{}y", value.x.value, value.y.value), ctx); + return formatter::format(std::format("Tile {}x+{}y", value.x.value, value.y.value), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtrasterizer::atlas::RenderTile const& value, - format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::atlas::RenderTile const& value, auto& ctx) const { return formatter::format( - fmt::format("RenderTile({}x + {}y, {})", value.x.value, value.y.value, value.tileLocation), ctx); + std::format("RenderTile({}x + {}y, {})", value.x.value, value.y.value, value.tileLocation), ctx); } }; template <> -struct fmt::formatter: fmt::formatter +struct std::formatter: std::formatter { - auto format(vtrasterizer::atlas::AtlasProperties const& value, - format_context& ctx) const -> format_context::iterator + auto format(vtrasterizer::atlas::AtlasProperties const& value, auto& ctx) const { - return formatter::format(fmt::format("tile size {}, format {}, direct-mapped {}", + return formatter::format(std::format("tile size {}, format {}, direct-mapped {}", value.tileSize, value.format, value.directMappingCount), diff --git a/vcpkg.json b/vcpkg.json index 61b306e329..06f32bbdc8 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -3,9 +3,8 @@ "builtin-baseline": "80403036a665cb8fcc1a1b3e17593d20b03b2489", "dependencies": [ { "name": "catch2", "version>=": "3.4.0" }, - { "name": "fmt", "version>=": "10.2.0" }, { "name": "libssh2", "version>=": "1.11.0" }, - { "name": "ms-gsl"}, + { "name": "ms-gsl" }, { "name": "range-v3", "version>=": "0.12.0" }, { "name": "yaml-cpp" }, "freetype",